0

I've an unordered list of elements and I want to bind hover event to each of these elements. The HTML structure is as follows :

<ul>
  <li id="url_1">item 1</li>
  <li id="url_2">item 2</li>
</ul>

I figured using a for-loop would be the best way to do it. So my jQuery code is as follows:

for(i=1;i<=2;i++){
   $("li#url_"+i).hover(function () { /* do something on mouseenter */}, function () { /* do something on mouseleave */ }); }

This should bind the hover event to li#url_1 & li#url_2. But it is not working!

Can you please suggest the right (and more efficient) way to do this?

Cheers, Kartik Rao

1

1 Answer 1

1

first, don't forget to put your jQuery code inside a $(document).ready(function { }) block, so it would perform only the DOM is loaded.

Second, why not assign an ID, or class, or whatever what will help you access that UL element in the top, and then do this:

$("ul#yourId > li").hover(function() { ............. }, function() { ...   });

instead of building a cycle. Inside the event handlers, use this to access the li element, and see its id if needed. The event handlers will be assigned to all the li elements which are direct children of that ul element with yourid as the id, for example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.