0

I've developed a search page with infinite scroll (using jQuery, no plug-ins) and now I wonder how can I add some behavior to the HTML I get back from the WS I call. I need to add some JavaScript via jQuery selectors, but I've always relied on the

$(document).ready(function(){});

so far, that doesn't trigger when I append HTML code to may page. The only idea I had is to inject the JS code after the jQuery AJAX call in case of SUCCESS event

function injectJS(){
   $('.elementA').click(function(){ /* do something */ });
   $('.elementB').click(function(){ /* do something */ });
   ...
   $('.elementZ').click(function(){ /* do something */ });
}

$.ajax({
   url: "/ajax/v1/path",
   type: "post",
   data: data, 
   success: function (data) {
      // 1. Add HTML to the page
      // 2. Inject JS to DOM objects
      injectJS
   },
   error: function (e) {
      console.log('error:'+e);
   }
});

Is this the only solution?

I have to say this approach appear rather bad to me because It will inject the code to all the matching elements in the page, even those previously fetched.

vzwick
  • 11,008
  • 5
  • 43
  • 63
Max
  • 2,508
  • 3
  • 26
  • 44

1 Answers1

1

Short answer:

function injectJS(){
   $(document).on('click', '.elementA', function(){ /* do something */ });
   // ...
}

Long answer:

Look up

vzwick
  • 11,008
  • 5
  • 43
  • 63