0

The filter mechanism (item_filter) below returns fresh html-content (product_data) via an ajax function (load_resorts). In this freshly loaded html content is (also) a class which -when clicked- should trigger a function (via class myresort).

<span class="myresort badge" data-src="549">+add</span>

The myresort click function works for the default loaded resorts (on page load), but not for the ones loaded via ajax. I have used a bind function.

http://skiweather.eu/wheretoski/

$('.item_filter').on('click', function(event) {
  $('.product-data').html('<div id="loaderpro" style="" ></div>');
  sure = multiple_values('sure');
  country = multiple_values('country');
  altitude = multiple_values('altitude');
  level = multiple_values('level');
  size = multiple_values('size');
  price = multiple_values('price');
  offpiste = multiple_values('offpiste');
  family = multiple_values('family');
  apresski = multiple_values('apresski');
  load_resorts($("#snow1").val(), $("#snow2").val());
});

function load_resorts(ssnow, esnow) {
  $.ajax({
    url: "ajax.php",
    type: 'post',
    data:{sure:sure,country:country,altitude:altitude,level:level,offpiste:offpiste,family:family,apresski:apresski,size:size,price:price,ssnow:ssnow,esnow:esnow,filter_order:filter_order},
    success: function(result) {
      $('.product-data').fadeIn('slow').html(result);
    }
  });
}

$('span.myresort').on('click', function(event) {
  var myres = $(this).attr('data-src');
  $.ajax({
    type: 'POST',
    url: '/v4/ajax/myresorts.php',
    data: {
      myresort: myres
    },
    success: function(msg) {
      $('#myresorts').fadeOut(800, function() {
        if ($('*[data-src="' + myres + '"]').hasClass('loveit')) {
          $('*[data-src="' + myres + '"]').removeClass('loveit');
          $('*[data-src="' + myres + '"]').html('+add').fadeIn().delay(1000);
        } else {
          $('*[data-src="' + myres + '"]').addClass('loveit');
          $('*[data-src="' + myres + '"]').html('-remove').fadeIn().delay(1000);
        }
        $('#myresorts').html(msg).fadeIn().delay(1500);

      });
    }
  });
});
Mark Henry
  • 2,449
  • 6
  • 37
  • 48
  • Also a duplicate of the deleted question https://stackoverflow.com/questions/50346265/bind-click-function-to-ajax-loaded-content – mplungjan May 15 '18 at 11:42

1 Answers1

1

This could be jquery event delegation issue: You need to bind jquery to the elements created dynamically (using ajax) which were not on the DOM when page for ready. To do this, change you code like this:

$(document).on('click', 'span.myresort', function(event) {

And it should work for all.

For more details, please check this out.

Himanshu Upadhyay
  • 6,220
  • 1
  • 13
  • 32