简体   繁体   中英

How to use JS for “active page” status class

My website uses a css navigation similar to this tutorial, http://net.tutsplus.com/tutorials/html-css-techniques/creating-a-floating-html-menu-using-jquery-and-css/

It's a single page website.

I need to make it so when you click a link and it scrolls down to it's relevant content, that the my class named "active" will be applied to the markup.

This is what I have attempted so far:

aObj = document.getElementById('navigation').getElementsByTagName('a');
      for(i=0;i<aObj.length;i++) {
        if(document.location.href.indexOf(aObj[i].href)>=0) {
          aObj[i].className='active';
        }
      }
    }
    window.onload = function() {
    if (window.location.hash.length > 1) {
        page = window.location.hash.split("#")[1];
        load(page);
    }

}

I don't know JS and this is out of my comfort zone. Thanks

EDIT

A friend pointed me to this website http://imakewebthings.github.com/jquery-waypoints/ .

A brief overview of how my page is setup:

<div id="home">
  <h1>Homepage</h1>
</div>
<div id="portfolio">
  <h1>Portfolio</h1>
</div>
<div id="contact">
  <h1>Contact Us</h1>
</div>
<div id="navigation">
  <ul>
    <li><a href="#home">home</a><li>
  </ul>
</div>

It still will not add the class to the markup, any suggestions?

One adjustment I will point out - you set navigation elements to "active" class, but never remove it. This will take care of that:

aObj = document.getElementById('navigation').getElementsByTagName('a');
for(i=0;i<aObj.length;i++)
{
    if(document.location.href.indexOf(aObj[i].href)>=0)
    {
        aObj[i].className='active';
    }
    else
    {
        aObj[i].className='inactive';
        //or set to '', or whatever your default is    
    }
}

Something like this?

window.onload = function() {
    aObj = document.getElementById('navigation').getElementsByTagName('a');
    for(i=0;i<aObj.length;i++)
    {
        aObj[i].onclick = function()
        {
            //alert(this.href.split("#")[1]);
            load(this.href.split("#")[1]);
        }
    }

    if (window.location.hash.length > 1) {
        page = window.location.hash.split("#")[1];
        load(page);
    }
}
function load(p)
{
    aObj = document.getElementById('navigation').getElementsByTagName('a');
    for(i=0;i<aObj.length;i++)
    {
        aObj[i].className = (p==aObj[i].href.split("#")[1]) ? 'active':'';
    }
}

Just to be clear, you are calling the code that adds the "active" class to the link in the onclick of all links, right? Because that's what's missing from your example code. It simply runs through all links once. So in the current state, when a user clicks a link, your javascript code doesn't run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM