On my page I numerous sections that I want to highlight when the mouse goes over. This can be accomplished using onmouseover and onmouseout. I have more than 100 sections though and I don’t think that it is very efficient to call the methods on each section. Like so.
<li id="1" onmouseover="h(1)" onmouseout="h(1)">
<label>1</label>
</li>
<li id="2" onmouseover="h(2)" onmouseout="h(2)">
<label>2</label>
</li>
<li id="3" onmouseover="h(3)" onmouseout="h(3)">
do something
</li>
...
<li id="4" onmouseover="h(4)" onmouseout="h(4)">
do something
</li>
I’m hoping to get this answer in Javascript as I do not know jQuery.
What you are after is event delegation. That is binding the event handler to a common ancestor. In your case it could be something along the lines:
DEMO
This is only an example and you have to adjust it to your needs, e.g. if the
lielements contain elements themselves, things are a bit different.I recommend to read the great articles on quirksmode.org if you want to learn more about event handling.
That said, jQuery would make this a lot easier, also because it simulates the
mouseenterandmouseleaveevents from IE, which are much more useful, and takes care of the cross-browser issues.For example:
If you work a lot with event handling and/or DOM manipulation, jQuery is really to be recommended.