ahuang7
ahuang7

Reputation: 2190

.on("click", function() not working when link rendered with ajax

The link below shows a modal and runs an ajax request to render a partial within the modal based on the object id . The link works fine and the modal pops up when the page is fully loaded with an http request, but if I render the link with an ajax request (e.g. a different modal pops up and renders a few of the links) then the js function doesn't run. I tried an alert(); just to check and it doesnt run when its rendered with ajax.

I'm using JQuery 1.9.1, previously the js worked with .live('click'), but that has since been removed. I have also tried .click()

Any ideas? Thank you!

Link

<a href="/an-object-id" data-remote=true name="modal">    

JS

$(document).ready(function() {
$("a[name=modal]").on("click", function(e) {
    $("#mask, #modal").show();
    e.preventDefault();
etc...

Upvotes: 13

Views: 7818

Answers (4)

Tieson T.
Tieson T.

Reputation: 21191

Basically, you need to bind the listener for your click event to something in the DOM that doesn't get altered. on() has an optional parameter that lets you filter event triggers to a child element of the item selected as the listener. The simplest is to use document, but I prefer to use the closest parent I know I won't change. So, assuming I had this markup:

<div id="super-awesome-parent">
    <ul>
        <li><a href="#">Some link text</a></li>
        <li><a href="#">Some link text</a></li>
        <li><a href="#">Some link text</a></li>
        <li><a href="#">Some link text</a></li>
        <li><a href="#">Some link text</a></li>
    </ul>
</div>

I could write a on() delegate like so:

$('#super-awesome-parent').on('click', 'a', function(event){ 
    // ... code 
});

Then, any <a> elements that are added to #super-awesome-parent after the ready() event will still be handled by the delegate.

Upvotes: 3

Anujith
Anujith

Reputation: 9370

Attach an event handler to a parent element using .on(), and pass the selector as an argument.

Example:

$(document).on("click", "a[name=modal]", function(e) {...});

which works for dynamically generated elements as well..

Upvotes: 24

bipen
bipen

Reputation: 36531

use on event delegation..since your link is dynamically generated... click event won't be fired... use document to delegate the event..

 $(document).on("click","a[name='modal']", function(e) {
       ..
 });

you can go through the link to read more about on delegated events.. it will be much better if you delegate the event with closest element that is present in the document than document for better performance

Upvotes: 4

Atif
Atif

Reputation: 10880

$(document).on("click", "a[name=modal]", function(e) {
    $("#mask, #modal").show();
    e.preventDefault();
etc...

Upvotes: 5

Related Questions