Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Apr 2005
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    change id by url

    Hi there,

    I'm a total javascript newbie, but I figure my request is pretty basic for someone with any experience.

    I have a navigation in unordered list < ul > format. I apply an id of "active" to the anchor <a id="active"> within a list item <li> in order to indicate the current section/page. Here is a sample of what it would look like for the 'about' section:

    <ul>
    <li><a href="/about" id="active">About</a></li>
    <li><a href="/contact">Contact</a></li>
    etc.
    </ul>

    I would like to generate the 'active' id automatically, I'm assuming by using location.href even if it means using absolute URL's.

    So I was thinking something like:

    function setactivestate() {
    if (document.getelementbyhref) <-- I know this doesn't exist but that's where you're supposed to help me!
    {
    var nodeobj = document.getelementbyhref;
    if nodeobj = location.href {
    nodeobj.id = active;
    }
    }

    I know this is probably very simplistic, but maybe someone could tweak it to work.

    The caveat is I'd like to have it so that it would apply the 'active' id to the 'about' link when you're on domain.com/about, but also when you're on a sub page in that section like domain.com/about/philosophy.html.

  • #2
    New to the CF scene
    Join Date
    Apr 2005
    Location
    Norway, Haugesund
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts
    You could use this function:

    Code:
    function setActiveState() {
    	var anchors = document.getElementsByTagName("A");
    
    	for( var i=0; i<anchors.length; i++ ) {
    		if( anchors[i].getAttribute( "href" ) == location.href ) {
    			anchors[i].setAttribute( "id", "active" );
    			break;
    		}
    	}
    }
    Haven't tested it, but it should work.

  • #3
    Senior Coder
    Join Date
    Aug 2002
    Location
    UK
    Posts
    2,789
    Thanks
    2
    Thanked 14 Times in 14 Posts
    Sorry, misunderstood the question
    Last edited by Mr J; 04-16-2005 at 11:07 PM.
    The silent one.

    The most dangerous thing in the world is an idea.
    The most dangerous person in the world is the one with an idea.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •