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?
source to share
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.
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'});
});
source to share
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.
source to share