1

I have some html appended using handlebars, but am unable to get the event from a hyperlink to fire:

JS - this code is called during document.ready.

$(".media-item a.meddelete").unbind("click");
$(".media-item a.meddelete").click(function (event) {
    event.preventDefault();
    var id = $(this).data("assetid");
    alert(id);
});

HTML

<div class="media-item">
   <p><a href="ImageManipulation.aspx">Edit</a></p>
   <p><a href="#" class="meddelete">Delete</a></p>
</div>

I can't see what is wrong, any ideas?

2
  • 1
    Does the binding happen before or after the HTML is injected? Commented Sep 16, 2013 at 15:11
  • Handlebars will also be running at document.ready() so the above html will not exist until after that. The 2 answers below, using 'on()' & delegation will fix this problem. If they do not work then there is something else wrong. Commented Sep 16, 2013 at 15:18

2 Answers 2

2

Assuming by 'injected' you mean that the elements in your example are appended to the DOM dynamically after the page has loaded, you need to use a delegated event handler:

$(document).on('click', '.media-item a.meddelete', function (event) {
    event.preventDefault();
    var id = $(this).data("assetid");
    alert(id);
});

Note that document in my example should be changed to be the nearest static element for best performance.

Sign up to request clarification or add additional context in comments.

3 Comments

Its not appended as such, its 'put' into the dom somewhere between the start and end. Will your code example still work?
It will. You should use this method (delegated events) to hook to any element which is created after the page was loaded.
Worked like a charm, as you suggested I bound this to the div that holds the appended element.
2

Change this:

$(".media-item a.meddelete").click(function (event) {

to this:

$(document).on('click', ".media-item a.meddelete", function (event) {

If you're dynamically adding elements to the page, you need to use jQuery's event delegation syntax.

2 Comments

Thanks, what's the difference, as I copied from another piece of code that works that is doen like above?
The syntax you used in your question will work for elements that already exist at the time the code is executed. The code I posted will work for any elements that exist at the time the code was executed, as well as any new matching elements that are dynamically added later.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.