Zac
Zac

Reputation: 12836

Load scripts along with content in ajax

I am loading a set of images from another page using jquery load() function. I want the images that are loaded to be able to trigger the colorbox script but it is not working. I have all of the scripts on the page that triggers the load, but the script does not get applied to the fresh ajax content. How could I make this work?

Update

Thanks for the responses! It now works using the on function.. so I have something like this :

<a href="http://something.com" class="cbox"><img ... /></a>

        $j(".cbox").on( "click", function(){
              $j.fn.colorbox({ iframe:true,  scrolling: false, innerWidth: '650px', innerHeight: '390px' }); 
              return false;
              });

It seems to sort of work.. however now colorbox cant grab the href, it is returning that as undefined... but I guess that is another matter.

Upvotes: 5

Views: 180

Answers (2)

mowwwalker
mowwwalker

Reputation: 17334

Use jQuery's new .on() method, which replaces .live() and .delegate(). It works on elements that were added to the DOM after the code ran.

Had you posted some code, I'd have some to post back, but basically it looks like

$('imgselect').on('event',function(){
    //do stuff
});

event can be mouseenter, mouseleave, click, etc.

http://api.jquery.com/on/

Upvotes: 3

Eric Hodonsky
Eric Hodonsky

Reputation: 5897

Try using requireJS.

This works as a script loader, and a library module controller for defining use for script methods.

http://requirejs.org/docs/start.html -----EDIT-------

Okay I only half read your question. Try using .delegate() instead of binding to just an element, because when a fresh element is loaded in via Javascript whether in a string, DOM addition, or AJAX call, that selector that executed initially doesn't see the new element.

However .delegate() can work while watching a certain DOM element for change, and if it may be global I'd do something like this:

$('body').delegate("a[rel='theTriggerElement']", "click", function () { //Do Trigger Event});

This will watch the body element for any new "a[rel='theTriggerElement']" elements, and apply the event to them. Remember not to use .live() as it's deprecated.

Upvotes: 1

Related Questions