2

I have a $(document).ready function that sets up listeners for certain elements. However, all of the #leave-ride elements are added dynamically.

Listeners:

$(document).ready(function() {
    $("#post-ride").click(function() {
        addRide(currentDriver, $(destinationInput).val(), $(originInput).val(), $(dateInput).val(), $(timeInput).val());
        $.getScript("scripts/myRides.js", function() {});
    });

    $("#request-ride").click(function() {
        requestRide(currentDriver, $(destinationInput).val(), $(originInput).val(), $(dateInput).val(), $(timeInput).val());
        $.getScript("scripts/myRides.js", function() {});
    });

    $("#leave-ride").click(function() {
        console.log("leave Ride");
        leaveRide(currentDriver, $("leave-ride").closest("div").attr("id"));
        $.getScript("scripts/myRides.js", function() {});
    });
});

What do I need to do to get that listener to listen to dynamic content?

David G
  • 94,763
  • 41
  • 167
  • 253
gfreestone
  • 143
  • 2
  • 12
  • 1
    possible duplicate of [Javascript event loading w/dynamic content](http://stackoverflow.com/questions/9163637/javascript-event-loading-w-dynamic-content) – Bergi Dec 03 '12 at 22:41
  • An id should only be used once in your document, and `$('leave-ride')` is most likely going to be empty. – Ja͢ck Dec 03 '12 at 22:47

3 Answers3

10

Yes, ready runs only once. You can use event delegation:

Take the element closest to the #leave-ride which is not loaded dynamically (document in extreme cases). Then attach the handler on it, and use #leave-ride as the selector for the delegated event.

Assuming a div having the id #container is that static element:

$('div#container').on('click', '#leave-ride', function(){…});

See also Event binding on dynamically created elements?

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
3

Use on, change your event declaration

$("#post-ride").click(function() {

to

$("body").on('click',"#post-ride",(function() {
Travis J
  • 81,153
  • 41
  • 202
  • 273
0

Use .on()

Example:

$("#leave-ride").on('click', function() {
   console.log("leave Ride");
   leaveRide(currentDriver, $("leave-ride").closest("div").attr("id"));
   $.getScript("scripts/myRides.js", function() {
    });
});
Sparky
  • 98,165
  • 25
  • 199
  • 285
romo
  • 1,990
  • 11
  • 10