Forum Moderators: open

Message Too Old, No Replies

Getting an <li> ID from onClick

Problem with Global variables and an OnClick function

         

harry_bigby

10:23 am on Oct 8, 2010 (gmt 0)

10+ Year Member



I'm trying to create a horizontal, tabbed menu where the selected tab changes its appearance as set by a 'selected' class.

The following code changes the specified tab as I require,

var previous="t1";
var selected="t4";

document.getElementById(previous).className="";//Clear the previously selected <li>.
document.getElementById(selected).className="selected";//Set the current selection.

The following code selects the ID of a clicked tab,

var idd;

window.onload=function()
{
el=document.body.getElementsByTagName('*');
for(j=0;j<el.length;j++)
{
el[j].onclick=function()
{
idd=this.id;
if (idd!="")
{
alert(idd);
}
}
}
}

What I can't managed is to put the two together!

Even 'though the variable 'idd' is created outside the function and should be global, it doesn't preserve the value generated in the function.
i.e. alert(idd); outside of the function returns "undefined".

If I include the className statements inside the function the required changes take place but the original state returns once the function ends.

My problem is that I don't really know exactly what is happening when a tab is clicked.

Any help would be greatly appreciated.

Fotiman

1:38 pm on Oct 8, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Welcome to WebmasterWorld! I believe your problem is here:

el=document.body.getElementsByTagName('*');


You are attaching event listeners to EVERY element in the page, which is terribly inefficient. But more importantly, events will bubble up and your event handler function will be called multiple times each time you click on something. For example:


<div id="firedLast">
<div id="fired3rd">
<div id="fired2nd">
<a href="#" id="fired1st">Click Me</a>
</div>
</div>
</div>

Attaching an event handler to all elements means that when you click on the link in the example above, the event handler will fire for element "fired1st", then "fired2nd", then "fired3rd", then "firedLast", and so on up the document tree.

So you probably want to attach the event handler only to those elements that care about the event. Alternatively, might be able to attach the handler to a single parent element, and calculate which "tab" was clicked from the event itself.

Hope that helps.