HTML
<div id='header'>top of page</div> <div class='message'>hello, how are you</div> <div class='message'>I am fine</div>
jquery
$(document).ready(function () { $('#header').append('<div class='message'>appended DIV</div>'); $('div.message').hover( function () { alert('hi'); }, function () { alert('bye'); } ); });
Why do the existing DIVs in the HTML trigger the mouse even and hence alert, but the appended DIV will not and is ‘dead.’ How can the appended DIV react like the existing ones?
edit: in summary this was the solution:
$('<span />').addClass('message').text('(mouse 1)').appendTo('#header'); $('<span />').addClass('message').text('(mouse 2)').appendTo('#header'); $('.message').hover( function () { $('#header').prepend('in'); }, function () { $('#header').prepend('out'); } );
Note, if the SPANs are placed below the hover function, it won’t work.
Here is the resulting generated XHTML from your current code:
As you can see, the part you expect to hover over has no text.
Try:
You will now see the text inside a new
divwith themessageclass attached.