Marco Allori
Marco Allori

Reputation: 3314

bind event before append jquery object

How can I bind event to a not jet printed jquery object?

Example my div is:

var $div = $("<div>my div</div>");

I want to bind a click to this not rendered div and then print it on DOM, something like:

$div.click(function(){alert("hello")});
$(body).append($div);

thx

Upvotes: 1

Views: 3082

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318758

Your code is almost correct - you just forgot some quotes around body:

var $div = $("<div>my div</div>");
$div.click(function(){alert("hello")});
$('body').append($div);

Instead of $('body') you could also use $(document.body)

Upvotes: 4

Related Questions