1

I have this piece of code that works great, but as soon as I refresh a div on my page, the code breaks, and .item_control_box is no longer hidden, I'm thinking I have to rewrite this to work with .live, but I'm not sure how.

$(document).ready(function() {
    $(".item_control_box").hide();
    jQuery('.each_item_container').hover(function() {
        jQuery(this).find('.item_control_box').show()
    }, function() {
        jQuery(this).find('.item_control_box').hide();
    });
});

Thanks!

DobotJr
  • 3,929
  • 9
  • 36
  • 49

2 Answers2

2

Are you re-loading your div dynamically via AJAX? Just curious. Here's what I see:

You current js code will run when the document is rendered

$(document).ready(function() {
    $(".item_control_box").hide();

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

this will hide all CURRENT elements with class item_control_box that are already present

jQuery('.each_item_container').hover(function() {
    jQuery(this).find('.item_control_box').show()
}, function() {
    jQuery(this).find('.item_control_box').hide();
});

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Attach hover event handler to all CURRENT elements with class each_item_container and then find children of item_control_box on hover.

});

If you are loading new data into your div via AJAX or another means you need to ensure two things:

1) elements with item_control_box are not displayed at first. This you can accomplish with simple style="display:none;"

2) ensure that hover events are assigned to .each_item_container. This you need to do via live method jQuery('.each_item_container').live('hover', function()... described by @PeterStuart

Last but not least, not sure what version jquery you are using but in 1.7+ live() method is deprecated. use on() method instead. Here's the link for reference: http://api.jquery.com/live/

Alexey Gerasimov
  • 2,131
  • 13
  • 17
1

You would change:

jQuery('.each_item_container').hover(function() {

to

jQuery('.each_item_container').live('hover', function() {

To answer on your comment above your HTML should just be fine, as long if you have a div class called "each_item_container". When you hover over it is should now change your backreound color:)

Let me know if it doesn't work:)

Peter Stuart
  • 2,362
  • 7
  • 42
  • 73