1

Works:

var magic_div = $('<div>');
$('body').html(magic_div);
$(magic_div).append('<a href="#" class="bind-event">click</p>');
$( '.bind-event' , magic_div).bind('click' , function(){ console.log('bind works'); });

Doesn't work:

var magic_div = $('<div>');
$('body').html(magic_div);
$(magic_div).append('<a href="#" class="bind-event">click</p>');
$( '.bind-event' , magic_div).live('click' , function(){ console.log('bind works'); });

This probably explains it, but I don't understand why it shouldn't work if DOM elements are present.

Community
  • 1
  • 1
Jonathan Hendler
  • 1,239
  • 1
  • 17
  • 23
  • 2
    While I do understand that you might be using `j` in your projects for compatibility issues, please convert them to `$` when posting here, so that it's easier to read. – Joseph Silber Aug 30 '11 at 17:57

3 Answers3

4

If you change j('#bind-event',magic_div) with j('#bind-event'), it works fine in both cases. (There's no point in applying a context to an ID.)

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
2

You are binding click event on an anchor without preventing the default behavior of it. So when you click on the anchor it triggeres the click event and after that it tries to redirect to href set into it.

Now since bind directly attaches the event handler on the element it works where as live binds the click event to the DOM's document element. As browser events bubble up through the DOM tree, the click event is triggered for any matching elements. Since you are not preventing the default behavior of the anchor the event is not getting bubbled. Try this it will work.

var magic_div = j('<div>');
j('body').html(magic_div);
j(magic_div).append('<a href="#" id="bind-event">click</p>');
j( '#bind-event' , magic_div).live('click' , function(e){ 
  e.preventDefault();
  console.log('bind works'); 
});
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
0

Had a conversation today and learned that live() is less forgiving and will not accept a jQuery object, but will accept a DOM element.

The following works:

var magic_div = $('<div>');
$('body').html(magic_div);
$(magic_div).append('<a href="#" class="bind-event">click</p>');
$( '.bind-event' , magic_div.get(0) ).live('click' , function(){ console.log('bind works'); });
Jonathan Hendler
  • 1,239
  • 1
  • 17
  • 23