Ekumahost Ekumahost - 1 year ago 105
jQuery Question

How to execute Javascript on infinite-scroll loaded page

I am working on product listing page more products are loaded with infinite scroll
The problem is when the new page load, the jQuery on click event on the loaded page will not execute when user click on "add to cart". the script would have worked if it was loaded with jquery load(). but infinite scroll is using something else like I don't know.

$(document).ready(function() {
navSelector: "#mynext:last",
nextSelector: "#mynext:last",
itemSelector: "#mycontent",
debug: false,
dataType: 'html',
maxPage: <?php echo $pages_load;?>,
path: function(index) {
return "pages/index" + index + ".html";

// appendCallback : false, // USE FOR PREPENDING
}, function(newElements, data, url) {


Answer Source

From my comment: Simply use a delegated event handler, attached to document, loaded once at start up, to handle the click event. They will still fire on elements loaded later.

Assuming your add to cart buttons have a class of "addtocart" you could do something like this:

$(document).on('click', '.addtocart', function(){
   // handle click here

It works by delegating the event listening to an ancestor element (e.g. document), then it applies the jquery selector to the elements in the bubble chain, then it applies your event function to the matching elements that caused the event.

The upshot of delegated events is that the elements do not need to exist at event registration time, but only at event time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download