If I append new div on the run, the newly created div doesn't get connected with event handler in document ready.
for example, http://jsfiddle.net/nFG24/
how to assign new div to current event handler in document ready?
If I append new div on the run, the newly created div doesn't get connected with event handler in document ready.
for example, http://jsfiddle.net/nFG24/
how to assign new div to current event handler in document ready?
The shortcut event handlers (such as click()
, mouseover()
etc) will only apply to elements which are available to the DOM on page load. When appending elements dynamically you have to attach the event to a static parent element, and supply a filter which you wish to delegate events to, like this:
$("body").on('mouseover', '.hoverme', function() {
$(this).css({backgroundColor: '#000'});
});
$("body").on('mouseout', '.hoverme', function() {
$(this).css({backgroundColor: '#0af'});
});
Note that I've used body
here as the primary selector. Ideally you should use the closest containing element to the .hoverme
elements which is not dynamically appended to the DOM.
Also, you can slightly tidy your code by using hover()
:
$("body").on('hover', '.hoverme', function(e) {
if (e.type === 'mouseenter')
$(this).css({backgroundColor: '#000'});
else
$(this).css({backgroundColor: '#0af'});
});
Have you tried using .on() yet ? or .bind() in older versions of jQuery 1.7- ?
.on()
Description: Attach an event handler function for one or more events to the selected elements. http://api.jquery.com/on/
.bind()
Description: Attach a handler to an event for the elements.
Or use live(). This is available for jquery 1.4+, it's deprecated in 1.7 but still works
$(".hoverme").live('mouseover', function()
{
$(this).css({backgroundColor: '#000'});
});
$(".hoverme").live('mouseout', function()
{
$(this).css({backgroundColor: '#0af'});
});