Reputation: 417
I'm trying to create an 'Are you sure' confirmation for a link, similar to the one on the report button on reddit posts. When clicked, the link is replaced with the text "Are you sure Yes / No" where "yes" will do the action and "no" will restore the link. I'm able to replace the link with the confirmation but unable to get the "no" link to hide the confirmation.
The relevant code:
<span id="confirm"><a href="#>Confirm</a></span>
<script type="text/javascript">
$(function() {
$("#confirm").click(function() {
$(this).html('Are you sure? <a href="#">Yes</a> / <a id="unconfirm" href="#">No</a>');
});
$("#unconfirm").click(function() {
$(this).parents("span").html('<a href="#">Confirm</a>');
});
});
</script>
Upvotes: 2
Views: 645
Reputation: 94121
Since your #unconfirm
element is generated dynamically you need to use delegation with on()
to attach the event:
$(closestStaticParent).on('click', '#unconfirm', function() { ... })
Upvotes: 1
Reputation: 166021
The #unconfirm
element doesn't exist in the DOM at the time the event binding is executed. You need to delegate the event handler further up the DOM tree:
$(document).on("click", "#unconfirm", function() {
$(this).parents("span").html('<a href="#">Confirm</a>');
});
This uses the .on()
method, which will bind the event handler to the selected element (the document
) but only execute the handler function if the event originated on an element matching the 2nd argument (#unconfirm
).
Note that .on()
was added in jQuery 1.7. If you're stuck on an older version you can use .delegate()
instead.
Also note that it would be more efficient to replace document
with some other ancestor element (since then the event has less distance to travel until it triggers the delegated event handler).
Upvotes: 5