Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a proper way to add listeners to new elements after using AJAX to get the html content? (jQuery, Javascript)

I am making something that can loads new setting pages via AJAX, I am not sure what's the most efficient way to bind listeners to those elements from the new content page?

Here's my thought. I can make a function that compares file path, and for each condition, then I will apply correct listeners to those new elements based on what page that AJAX loaded. I feel like it will makes the function so big if I have a large amount of pages.

Thanks!

like image 810
Lumin Avatar asked Jul 23 '13 21:07

Lumin


2 Answers

Two ways:

1) Bind on a non-dynamic parent container using .on()

$('.some-parent-class').on('click', '.element', function() {
  // DO STUFF!
});

2) Bind the new elements after ajax call is completed

$.ajax(url, {
  // ajax options
}).done( function(data) {
  var newEl = $('<div class="element"></div>');
  // Setup your newEl with data here...
  newEl.on('click', function() {
    // do stuff
  });
  newEl.appendTo($('.some-parent-class'));
});

The former usually results in quicker ajax response times, but may also slow click responsiveness down.

like image 112
Populus Avatar answered Nov 07 '22 10:11

Populus


Use jQuery's .on() to handle event delegation. The first element you supply is a static element (never removed / replaced). the first argument is the event you wish to delegate against, mouseover/click, etc. The 2nd argument is the element we wish to have the event fire on when the event occurs. The 3rd argument is the callback, which is the function to run when the event fires.

$(document).on('event', 'elementIdentifier', function(){
    //your code
});
like image 23
Ohgodwhy Avatar answered Nov 07 '22 10:11

Ohgodwhy