Forum Moderators: open

Message Too Old, No Replies

Can javascript change a css class?

         

nfs2

3:38 pm on Apr 11, 2006 (gmt 0)

10+ Year Member



here's the problem i have. I have a site that has a static header, and 3 tabs in the header. I need to know which tab is active, but since the tabs are in the same header shown on every page, i cant change the class to active..

<div id="tabs">
<ul>
<li><a class="active" href="1">Home</a></li>
<li><a href="2">Journal</a></li>
<li><a href="3">Pictures</a></li>
</ul>
</div>

So basically i need a way to switch the active class between the tabs depending on what page is loaded. I could probably do this in php, but im thinking javascript might be easier.

Anyone have any idea how to do it?

daosmith

4:22 pm on Apr 11, 2006 (gmt 0)

10+ Year Member



You can use regular DOM methods to achieve this. Suppose you give each of your tab li elements a suitable id. Then you could use a simple function along the lines of

function setActiveTab(tabID) {

var currTabElem = document.getElementById(tabID);

currTabElem.setAttribute("class", "some_class_name");
currTabElem.setAttribute("className", "some_class_name");

return;
}

The second variant where the className is set is to cater for IE, which for reasons best known to MS does not recognise the class attribute.

You can also do this without giving the li elements ids if you prefer: then you will need to access the parent div (id='tabs') by ID, and traverse the DOM tree to the descendent li elements. Each of these can then be identified by their href values.

You would need to call this function with the appropriate argument on document load - I'm not sure from what you say in your post if this is a problem, but if so you could do something tricky like determine the active tab by looking at the value of the h1/title elem or something like that.

Hope this helps.

nfs2

4:48 pm on Apr 11, 2006 (gmt 0)

10+ Year Member



Thanks for you reply, im sure your code is very helpful, but im afraid you've over-estimated my profecency with javascript.

Could you describe in more detail how to use the code?

bedlam

6:09 pm on Apr 11, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Check out message three in this thread from last summer [webmasterworld.com] for an explanation of a javascript solution and message four from this thread [webmasterworld.com] for a css-only method.

-b