views:

162

answers:

3

Hi there, for this code:

<div id="header">top of page</div>
<div class="message">hello, how are you</div>
<div class="message">I am fine</div>


$(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 appeneded DIV will not and is 'dead.' How can the appended DIV react like the existing ones?

thank you.


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.

+1  A: 

It doesn't work because this way you are appending text and not creating a DOM object, which you can later select.

You should probably do something like:

var divObj = $('<div>').attr('class', 'message');
$('#header').append(divObj);

$(divObj).hover(  
 function() {  
  alert('hi');
 },  
 function() {  
   alert('bye');
 }  
);
andi
This doesn't work: try here: http://jobs.happyzion.com/test.html
Adrian33
it worked for me in firefox on that test page
mkoryak
A: 

Hi Adrian!

Your code actually works perfectly for me in Firefox, so I think it must be something else that's the problem. Anything else you think could be affecting it?

Stuart Memo
+2  A: 

Here is the resulting generated XHTML from your current code:

<div id="header2">put mouse here<div class="message"></div></div>

As you can see, the part you expect to hover over has no text.

Try:

$('<div />').addClass('message').text('appended DIV').appendTo('#header');

You will now see the text inside a new div with the message class attached.

John Rasch
nice work! mouseover - "Appended DIV"
Adrian33