javascript - Highlight active (opened) link -


i want highlight active (opened) link . color must maintained time when link open. not on mouse click or hover.

here js way tried:

<script type="text/javascript">     $(document).ready(function(){      $("a.nav1").click(function () {       $(".active").removeclass("active");         $(this).addclass("active");       });     }); </script> 

html links:

 <div id="navigation">                         <ul>           <li><a class="nav1" data-tab="#home" id="link-home"href="#home">home</a></li>           <li><a class="nav1" data-tab="#football" id="link-football" href="#football">football</a></li>           <li><a class="nav1" data-tab="#hockey" id="link-hockey"href="#hockey">hockey</a </li>           </ul>      </div> 

it work problem refresh , button. not change color previous link. other js ways got same problem.

only css not work. example:

  <div id="navigation">                            <ul>               <li><a class="nav1" data-tab="#home" id="link-home"href="#home">home</a></li>               <li><a class="nav1" data-tab="#football" id="link-football" href="#football">football</a></li>               <li><a class="nav1" data-tab="#hockey" id="link-hockey"href="#hockey">hockey</a     </li>               </ul>          </div> 

and css

#home .nav1 {     color: #000;     background-image:url(farba3.png);  } #football .nav1 {     color: #000;     background-image:url(farba3.png);  } #hockey .nav1 {     color: #000;     background-image:url(farba3.png);  } 

you'll want listen hash change events (window.onhashchange), , change active link accordingly.

here's example:

function locationhashchanged() {     $('.nav1').removeclass('active'); // remove active class elements     $('.nav1[href="' + location.hash + '"]').addclass('active'); // add active class element href equals new fragment identifier ("hashtag") }  window.onhashchange = locationhashchanged; // listen hash change event locationhashchanged(); // add active class appropriate link on initial page load 

then, in css, you'll add rule list items have .active class.

want try it? there go.

note history api available , allows clean, nice urls. why not use it? using fragment identifiers outdated , not nice happen have js disabled.

if want use history api , worried browser support, can use history.js, makes using history api possible browsers don't support it. more info, please see repository.


Comments

Popular posts from this blog

My HTML document is not linking to my CSS stylesheet properly -

php array slice every 2th rule -

node.js - Sending sockets to client side, Error: Converting circular structure to JSON -