September 15, 2013

jQuery scripts on ajax content WITHOUT using $(document).on

Tonechild’s Question:

I am using an infinite scroll plugin which uses ajax.

When the ‘next page’ is loaded via ajax, all other ajax related scripts that are on the next page do not work. I have been told that I have to use ‘delegated events'(ie change $(id).click() to $(document).on) – problem is that means editing multiple plugins and changing dozens of function calls.

Is there any way I can avoid changing everything to $(document).on and do something cool with the infinite scroll?????

I’d much rather modify the infinite scroll plugin rather than modifying other ajax related plugins to make them fit.

Unfortunately you have very few options here, and switching to delegated events is by far the best of them.

The problem is that your old code was assigning behaviour to “particular elements” when what it should really have been doing is creating page-wide responses to “certain types of actions”.

I see 3 possibilities, and only one of them is guaranteed to work.

  1. Run any scripts that are needed on new pages each time a new page is loaded. The downside here being that unless you are careful about also “tearing down” between content loads you will have behaviours repeating or colliding with each other (eg: double popups, broken animations).
  2. Encapsulate the dynamic areas in <iframe>s. Depending on your architecture this may or may not be possible, and certainly won’t be easy to integrate with some kind of infinite scrolling plugin which already expects a certain page structure.
  3. Bite the bullet and fix the crappy code.

Loading scripts inside your ajax loaded content is a bad way to start with anyway. What you need is event delegation to attach itself to any dynamically added elements.

$("body").on("click", ".yourclass", function() {
    //This function will run for every element with `yourclass` class you load via ajax
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!