views:

54

answers:

4

i have dyanmic divs as rows

<table border=1><tr><td>
<div id='div1'>fgg</div>
<div id='div2'>dfgdfg</div>
<div id='div3'>vcbcvb</div>
<div id='div4'>sdfsdf</div>
</td></tr></table>

How can i call jquery funtion on moueover of each div.? These divs are dyanmic, can vary the number .

+2  A: 

Use event delegation, either .live() or .delegate() to bind events to elements that are created dynamically.

John Strickler
+3  A: 
$("td div").live("mouseover", function() {
 //mouseover code here
});

I suggest using a class for your divs, and using a selector: $(".rows") or similar. However, the above will work for the markup you've given.

If you must use id, this will allow you to add it by id. Keep in mind that as you add new items, you will have to run this code for the id (defeating the dynamic part of your original question).

$("#mydivid").mouseover(function() {
  //mouseover code here
});

which you could utilize in a list like so:

var divs = ["mydiv1", "mydiv2", "mydiv3"];
$(divs).each(function() {
  $("#" + this).mouseover(function() {
    //mouseover code here
  });
});

This is really a bad approach, I strongly suggest using a class instead.

sworoc
this working fine, but this will affect the entire divs in the tds. Can i have 5 divs with id mydiv andi want to call only these divs, is it possible. i try its not working.$("td div mydiv").live . any solution
zod
$("#mydiv").mouseover( ??
zod
I would suggest using a class for the divs you want to apply it to, and then use a $(".rows") selector or similar. If you must do it by id, and not class, you will want to use the form that I am adding to my answer.
sworoc
A: 

one another easy way is to give the same class name to all the divs. you can hook the click event by class name instead of id.In the code you can also refer the current div block by using "this" keyword

gov
A: 

Unless there is some reason you specifically cannot use a repeating class name for each div, the live() method is the way to go. Using a class would be much more efficient, however.

dmackerman