Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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...
like image 472
Andrew Avatar asked Feb 20 '13 06:02

Andrew


4 Answers

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..

like image 183
Anujith Avatar answered Nov 05 '22 04:11

Anujith


$(document).on("click", "a[name=modal]", function(e) {
    $("#mask, #modal").show();
    e.preventDefault();
etc...
like image 29
Atif Avatar answered Nov 05 '22 05:11

Atif


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

like image 4
bipen Avatar answered Nov 05 '22 03:11

bipen


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.

like image 3
Tieson T. Avatar answered Nov 05 '22 03:11

Tieson T.