Reputation: 41
First here is the code:
HTML:
<div id="foreground">
<button type="button" id="go">Start</button>
</div>
<div id="background">
<p>You are on the background</p>
</div>
JS:
$(function () {
$("#go").click(function (e) {
var $q = $(this);
var $vazy = $('<button type="button" id="vazy"> Vazy </button>');
var $loc = $('<input type="text" id="placename" placeholder="Location"/>');
$vazy.insertAfter($q);
$loc.insertAfter($q);
$q.hide();
e.stopPropagation();
});
$("#vazy").live("click", function () {
alert('k');
//$("#foreground").hide();
//$("#background").show();
});
});
CSS:
#background {
display: none;
}
The problem is at the line 15 where the button with the ID #vazy
seems not to respond to my click event even with the live binding.
Am I missing something?
Thanks for any response :)
Upvotes: 0
Views: 74
Reputation: 4443
Try this
$("body").on("click","#vazy" function () {
alert('k');
//$("#foreground").hide();
//$("#background").show();
});
Upvotes: 3
Reputation: 74410
Your best bet: {foreground is the closest static container, use it as delegate}
$("#foreground").on("click",'#vazy', function () {...});
Upvotes: 0
Reputation: 148178
live is deprecated use on() to bind event to dynamically added elements. You can delegate event to parent of the element or document.
$(document).on("click", "#vazy", function () {
alert('k');
//$("#foreground").hide();
//$("#background").show();
});
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
Upvotes: 1