0

I have a list of buttons that load a different url via ajax .get into a specific part of my page.

I have a function that gets the data attr from the click event and passes it onto another function that does a bit of logic.

The problem I have is the new html loaded via ajax is unseen by the js, it also has filter functions in it. I have read a few articles on here about event binding but I cant quite get the synax right for my example. I am not sure how to tie in the ".each" with this type of answer (below).

Jquery `on` event handler: event delegation and passing custom data

I am looking for the correct way to write the following code so that when the html is loaded via the .get request the js "sees" the html.

var filterThemeBtn = $('.js-discoveries__theme-filter');
var counter = 0;

function getDataValueTheme() {
      filterThemeBtn.each(function () {
      var $this = $(this);
      $this.on( "click", {param1: $(this).attr('data-filter')},theme_url);
   });             
}

function theme_url(e){
   // if click event
   if (e) {
      selectedTheme = e.data.param1;
      selectedThemeUrl = "/discoveries/ajax/type/" + selectedTheme + "/" + counter + "/" + "16";

      // other logic ect

      $.get(selectedThemeUrl, function(data, status) {
         grid.append(data);
      })
}


Adam Adams
  • 63
  • 10
  • create the jsfiddle to quick answer and understand, i think you declare event like this: $(document).on("click", '.js-discoveries__theme-filter', function(){ //your code }) Don't worry about data comes from ajax or present on window. it will works on all kind of data. – Ws Memon Jul 22 '22 at 12:05

1 Answers1

0

Thanks, after trying a few things I just went with not separating the two functions and using the methods described in the various posts and Ws Memon's reply. I didn't want to really do it this way as it looks "messy" - it works though. Thanks

   // gets data from theme click event loads relevant url via get 
   function theme_url(){
      $("body").on("click", ".js-discoveries__theme-filter", function(){
      var param1 = this.getAttribute('data-filter');
      selectedTheme = param1;
      alert(selectedTheme);
      selectedThemeUrl = "/discoveries-foula/ajax/type/" + selectedTheme + "/" + counter + "/" + "16";
      // remove items from grid
      $(".js-item").remove();
     // add items to grid based on category or "all"
     themeLogic();
     // when buttons in card are clicked add checked value to releveant top button
     addChecked();
     // load more recognising selected category
     $(loadMoreButton).off('click').on('click', function(){
          counter++
          selectedThemeUrl = "/discoveries-foula/ajax/type/" + selectedTheme + "/" + counter + "/" + "16";
          allItemsUrl = "/discoveries-foula/ajax/category/all/" + counter + "/" + "16";
          themeLogic();                        
       });                        
   });
}
Adam Adams
  • 63
  • 10