Newly added div does not inherit event handler in rendered document

If I add a new div to the run, the newly created div doesn't connect to an event handler in the document.

for example http://jsfiddle.net/nFG24/

how to assign a new div to the current event handler in document ready?

+3


source to share


3 answers


Handlers shortcut events (eg click()

, mouseover()

etc.) apply only to the elements available to DOM when the page loads. When adding items dynamically, you must attach the event to the static parent and provide the filter to which you want to delegate events, for example:

$("body").on('mouseover', '.hoverme', function() {
    $(this).css({backgroundColor: '#000'});                    
});
$("body").on('mouseout', '.hoverme', function() {
    $(this).css({backgroundColor: '#0af'});                 
});

      

Note that I have used body

this as the primary selector here. Ideally, you should use the closest containing element to elements .hoverme

that are not dynamically added to the DOM.

Working violin



Alternatively, you can clean up your code slightly using hover()

:

$("body").on('hover', '.hoverme', function(e) {
    if (e.type === 'mouseenter')
        $(this).css({backgroundColor: '#000'}); 
    else
        $(this).css({backgroundColor: '#0af'});          
});

      

Sample script

+8


source


Have you tried using .on ()? or .bind () in earlier jQuery 1.7-?

.on ()

Description: Attach an event handler function for one or more events to the selected items. http://api.jquery.com/on/



.bind ()

Description: Attach a handler to the event for items.

http://api.jquery.com/bind/

+1


source


Or use live (). This is available for jquery 1.4+, it was deprecated in 1.7 but still works

$(".hoverme").live('mouseover', function()
{
    $(this).css({backgroundColor: '#000'});                    
});
$(".hoverme").live('mouseout', function()
{
    $(this).css({backgroundColor: '#0af'});                   
});

      

0


source







All Articles