Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .live on load event

Tags:

jquery

I need a way to use the jquery .live() function to act on elements that are loaded via ajax.

For instance a div is loaded via ajax .load()

<div id="mydiv"></div>

Normally I do .live() with a click event, but I need to know how to tell the dom that this new div has loaded without any explicit actions/events from the user.

This code doesn't work, but I want to do something like this:

mydiv = $("#mydiv");

mydiv.live("mydiv.length > 0", function() {
       // do something
});

The "mydiv.length" being a substitue for the typical "click" or other event.

like image 781
djburdick Avatar asked Mar 30 '10 20:03

djburdick


People also ask

How can call Click event on page load in jQuery?

$("document"). ready(function() { setTimeout(function() { $("ul. galleria li:first-child img"). trigger('click'); },10); });

What is .live in jQuery?

jQuery live() Method The live() method attaches one or more event handlers for selected elements, and specifies a function to run when the events occur. Event handlers attached using the live() method will work for both current and FUTURE elements matching the selector (like a new element created by a script).

How do you call one event from another event in jQuery?

$('#b1'). on('click', function(){ $('#select_item'). trigger('change'); }); $('#select_item'). on('change', function(){ var jbyr = $(this).


1 Answers

Another way to do this would be to use trigger() to trigger your own custom event (let's call it content_loaded). load() takes a callback function it calls on completion:

function callback_function(responseText, textStatus, XMLHttpRequest) {
    //if we have valid data ...
    trigger("content_loaded");
}

$("your_selector").load("your_url", callback_function);

And then just set up an event listener and run it whenever your event is fired.

$("your_selector").bind("content_loaded", your_results_loaded_function);
like image 85
Sean Vieira Avatar answered Sep 28 '22 08:09

Sean Vieira