Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach event to window or document object inside a JQuery call Back function does not work

I have a script attached with the tag that download some file contents using JQuery:

$.get('the_file', function(data){

}

I need the contents to modify the web layout.

If I try to use the contents inside the onload event:

window.addEventListener('load', useTheContents, false);

It does not work because the contents are not ready.

So I dispatch an event at the end of the $.get(){} call back function like this:

$.get('the_file', function (data) {
    var e = jQuery.Event("MyCustomEvent");
    jQuery("body").trigger(e);
}

Then I have this in the main script:

$( "body" ).on( "MyCustomEvent", modifyLayout);

function modifyLayout(){

  // The stuff

}

And It works fine.

But if I use "window" or "document" instead of "body" it does not work.

I would like to know why.

like image 215
gastonbs Avatar asked Sep 18 '25 13:09

gastonbs


1 Answers

But if I use "window" or "document" instead of "body" it does not work.

Hope you are not putting window/document inside quotes. body should be inside quotes. Refer below:

$("body") -> valid
$(window) -> valid
$(document) -> valid
$("window") -> Invalid
$("document") -> Invalid
like image 114
Rajesh Avatar answered Sep 21 '25 02:09

Rajesh