Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .load isn't checking if my element is loaded

I have this code

<script type="text/javascript">
$("#main_photo_display").load(function(){
    alert("loaded");
});
</script>

<div id="main_photo_display"></div>

I need it to do something once that div has loaded. Currently it does nothing. When I substitute window for "#main_photo_display" it works. I have googled and I keep coming across .load as how to check if a page element has been loaded.

like image 695
Chris Avatar asked Dec 21 '11 00:12

Chris


People also ask

How do I ensure jQuery is loaded?

Checking if jQuery Is Loaded With JavaScriptgetElementByID() , which selects an HTML element on the page using its ID attribute. Of course, most JavaScript programmers are familiar with the $() function from jQuery, not as an alias of document. getElementByID() .

How do you know if an element is loaded?

How check element is loaded or not in jQuery? if iFrame is already loaded — execute code else — $('#iframe'). load(function() { /*execute code*/ });All of the following syntaxes are equivalent: $( handler )

How do I know if my jQuery console is working?

Type this command in the Chrome Developer Tools Javascript console window to see what version of the jQuery is being used on this page: console. log(jQuery().

Is jQuery load deprecated?

The load() method was deprecated in jQuery version 1.8 and removed in version 3.0. Use the on() or trigger() method instead.


2 Answers

The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

Source: http://api.jquery.com/load-event/

Further down on the same page they state:

It doesn't correctly bubble up the DOM tree

So you can't delegate this event, the event handler must be attached to the element on which the load event fires.

like image 161
Jasper Avatar answered Nov 04 '22 20:11

Jasper


Or you can run the script after the DOM is ready like so:

<script type="text/javascript">
$(document).ready(function() {
    $("#main_photo_display").load(function(){
        alert("loaded");
    });
});
</script>

<div id="main_photo_display"></div>

Sorry I think I read it wrong :) You need this:

<script type="text/javascript">
    $(document).ready(function() {
        alert('loaded');
    });
</script>
like image 42
Indranil Avatar answered Nov 04 '22 21:11

Indranil