user3376865
user3376865

Reputation: 5

jquery load function for a div not working

I just want to alert 'OK' when a div with id="Box" loads. But load function is not working. Here is my code in wordpress. I have included the jquery library and other jquery is working fine.

jQuery(function(){

jQuery( '#Box' ).load(function() {

alert('ok');
        });

    });

Upvotes: 1

Views: 16201

Answers (2)

Jens A. Koch
Jens A. Koch

Reputation: 41737

Question:

I just want to alert 'OK' when a div with id="Box" loads. But load function is not working.


You are using .load().

Answer A : This method will not work with a div.

Answer B : This method was deprecated in jQuery 1.8. Stop using it!

This method is a shortcut for .on( "load", handler ).

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.

https://api.jquery.com/load-event/


Possible solution:

Use the shorthand method .ajax(), .load(), .get to load content and trigger your stuff in the callback function or success handler.

.load() Load data from the server and place the returned HTML into the matched element.

http://api.jquery.com/load/

Example 1

Specify what to load in the first parameter and act in the callback function. The content of test.html is loaded, after that it's inserted into #box and the alert is fired.

$( "#result" ).load( "ajax/test.html", function() {
    alert( "Load was performed." );
});

Example 2

Ajax Example with load alert:

$.get("ajax/test.html", function(data) {
    $("#box").html(data);
    alert("Ok. Load.");
});

You are loading test.html the content is returned as data. It is assigned as new html content to the dom element #box. Then you fire the alert.

Example 3

The alternative is using the .ajax method and define a success handler:

function getData() {
    $.ajax({
        url : 'test.html',
        type: 'GET',
        success : alert('Ok.Loaded')
    });
}

Upvotes: 1

Hardy
Hardy

Reputation: 5631

It does not work with DIV elements:

See: https://api.jquery.com/load-event/

"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."

Upvotes: 5

Related Questions