Javascript function to add class to a list element based on # in url.

Posted by Jason on Stack Overflow See other posts from Stack Overflow or by Jason
Published on 2010-05-20T19:46:54Z Indexed on 2010/05/20 19:50 UTC
Read the original article Hit count: 293

Filed under:
|
|
|

I am trying to create a javascript function to add and remove a class to a list element based on the #tag at the end of the url on a page. The page has several different states, each with a different # in the url.

I am currently using this script to change the style of a given element based on the # in the url when the user first loads the page, however if the user navigates to a different section of the page the style added on the page load stays, I would like it to change.

<script type="text/javascript">

var hash=location.hash.substring(1);

if (hash == 'strategy'){
document.getElementById('strategy_link').style.backgroundPosition ="-50px";
}
if (hash == 'branding'){
document.getElementById('branding_link').style.backgroundPosition ="-50px";
}
if (hash == 'marketing'){
document.getElementById('marketing_link').style.backgroundPosition ="-50px";
}
if (hash == 'media'){
document.getElementById('media_link').style.backgroundPosition ="-50px";
 }
if (hash == 'management'){
document.getElementById('mangement_link').style.backgroundPosition ="-50px";
}

if (hash == ''){
document.getElementById('shop1').style.display ="block";
}

</script>

Additionally, I am using a function to change the class of the element onClick, but when a user comes to a specific # on the page directly from another page and then clicks to a different location, two elements appear active.

<script type="text/javascript">
 function selectInList(obj)
{
    $("#circularMenu").children("li").removeClass("highlight");
    $(obj).addClass("highlight");
}
</script>

You can see this here: http://www.perksconsulting.com/dev/capabilities.php#branding

Thanks.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about hash