Search code examples
javascriptjquerydynamiceventtrigger

jQuery SPA Dynamically created elements, trigger events multiple times


I made some 'SPA interface' using jquery, my main function which load pages, looks like that:

$('body').on('click', '.go-to', function(event) {
    event.preventDefault();
    var _this = $(this);
    var main_container = $('#main-container');
    main_container.fadeOut('fast');
    $('.preloader').delay(400).fadeIn('slow');
    $.get(_this.attr('href'), { id : _this.attr('data-id') }, function(result) {
        main_container.html(result);
        $('.preloader').fadeOut('fast');
        main_container.delay(1000).fadeIn('slow');
    });
    return false;
});

When I load some page multiple times, the event for loaded element is triggered many times. For example when i load page1 5 times, this code will return 'Test' 5 times.

   $('body').on('click', '#select-all', function(event) {
      console.log('Test');
   });

Anybody knows how to fix it?


Solution

  • you can use safely .off() before loading the .on() again to remove the previous .on() event handler you issued from the same js script you loaded

    $('body').off('click');
    $('body').on('click', '#select-all', function(event) {
          console.log('Test');
       });
    

    http://api.jquery.com/off/

    but as a practice why do you need to load again the event listener? I recommend you to just only load the event listener once as .on() binds event to any dynamically generated element