2

My problem is that I have to create event listeners on certain DOM elements before I insert them into the dom.

Now generally this is quite easy like so:

var button = $('<button>Click Me</button>');

button.on('click', function(){ alert('clicked'); });

$('body').append(button);

However, the problem is that I need to wrap the button in other html as in this example:

http://jsfiddle.net/a8xjJ/

The Event Listener breaks if I mix the button object with a string of html. That's when the Event Listener looses touch with the object, quite logically.

My problem is that I need to use strings of html, that's a constraint of the project. Maybe there is a way in which I can use the dom selector on a string? Or maybe you can think of another way of making the above fiddle work.

1
  • 2
    I'm guessing this is what you're trying to do -> FIDDLE ??
    – adeneo
    Sep 27, 2012 at 9:32

2 Answers 2

4

You can bind the dynamic elements by using .delegate() function of JQuery.

I have updated your fiddle to this.

var button = $('<button>Click Me</button>');
var html = '<form>' + button.clone().wrap('<div/>').parent().html() + '</form>';
$('div').append(html);

$(document).delegate(button,'click', function(e){ 
    e.preventDefault(); 
    alert('Clicked');
});

You may also use .on() to bind the events on dynamic elements.

$(document).on('click', button, function(e){ 
    e.preventDefault(); 
    alert('Clicked');
});

Notice that this method takes event as its first parameter.

1
  • Both the answers solve my problem, shame I can't tick them both. But I can vote yours up! Thanks! Sep 27, 2012 at 9:51
2

If you started to work with objects, try not to use their string representation (it outputs the shell only but not the events and other data). One possible solution of you problem:

$("<button>Click Me</button>").on("click", function(e) {
    e.preventDefault();
    alert("Clicked");
}).wrap("<form><div></div></form>").closest("form").appendTo("div");

DEMO: http://jsfiddle.net/a8xjJ/2/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.