Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running JQuery scripts on AJAX loaded content

Tags:

I am using .load() to pull static HTML files onto my main HTML page. The scripts and selectors that I have written exist within:

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

But they don't work on the AJAX loaded content. I have read that this is because the selectors that I am using are not available.

Is there a better way to do this? Adding the script to the window.load function doesn't work either:

$(window).load(function() {}); 
like image 540
mmcglynn Avatar asked Nov 19 '10 15:11

mmcglynn


People also ask

How run JavaScript after loading AJAX?

When the link li#menu-item-318 a gets clicked it removes the ready class which then reverses the css transition and then loads a new html document. On the Aja load I once again want to add the ready class to the same elements inserted by the Ajax call. The code below has a callback to add the ready class, which works.

Can you use jQuery with AJAX?

jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!

Can jQuery be loaded from an external site?

Yes, it's possible, but you'll need 1 line of PHP :) If you only need RSS feeds and you don't mind relying on Google you could use jquery-feeds.

Can I do AJAX call in JavaScript?

Ajax is a programming concept. Below are some ways to make Ajax call in JavaScript. Approach 1: In this approach, we will use the XMLHttpRequest object to make Ajax call. The XMLHttpRequest() method which create XMLHttpRequest object which is used to make request with server.


2 Answers

$(document).ajaxComplete(function(){     // fire when any Ajax requests complete }) 

ajaxComplete()

like image 117
Jman Avatar answered Oct 04 '22 10:10

Jman


There are more than one option:

  1. you can add initialization scripts [ $(this).click... ] into callback function of $.load()
  2. you can use $.live(), which creates handlers even for dynamically loaded/created objects.

More here:
callback: http://api.jquery.com/load/ (notice the "complete()" function)
bind: http://api.jquery.com/live/

Edit: My mistake, it was live(), not bind(), thank you guys

like image 20
Adam Kiss Avatar answered Oct 04 '22 09:10

Adam Kiss