Function not running during the load event of the document - javascript

I am writing a chrome extension, that has this content_script. I have written 3 functions to be triggered by 2 respective events - The double Click and Load function.
The Double Click event executes the function written for it, but, the load function or onload function are not executing their respective functions.
$("*").dblclick(function(){
alert("Double Click");
})
document.addEventListener ("onload", myMain, false);
function myMain (evt) {
alert("On Load");
}
document.addEventListener ("load", myMain, false);
function myMain (evt) {
alert("Load");
}

Using jQuery, here is my understanding of desired events :
$(window).on('load', function() {
alert('Loaded');
});
$(document).ready(function() {
alert('Ready');
});
$(window).on('dblclick', function() {
alert('Double click');
});
The difference between event 'load' and 'ready' is :
'Load' is triggered when your page is completely loaded (images,
charts ...).
'Ready' is triggered when your page script's is safe to manipulate.
Just check jQuery documentation for event on document loading : https://api.jquery.com/category/events/document-loading/
There is no event to trigger a document 'onload'.

You can use the DOMContentLoaded event in JS to achieve this. Like this:
window.addEventListener('DOMContentLoaded', myMain);
function myMain (evt) {
alert("Load");
}
Hope that's how you wanted it to work.
You can check here for more info - DOMContentLoaded Event

Related

Script loading: jQuery vs vanilla JS -- why a difference?

Why does vanilla JS's onload work where jQuery's load on does not when it comes to loading scripts?
So...
thisScript.onload=function Event triggers as expected.
$(thisScript).bind({load:function Event does not trigger
$(thisScript).on({load:function Event does not trigger
JS load and jQuery onload both work fine when it comes to loading
thisImg.onload=function Event triggers as expected
is the same as...
$(thisImg).bind({load:function Event triggers as expected
$(thisImg).on({load:function Event triggers as expected
...but not for scripts.
I'm aware of $.getScript but I'm curious about the above discrepancy.
Question Is there an event binding for jQuery that works for script loading?
The following test is revealing:
window.onload=()=>
var thisSrc, thisScript, thisTest;
thisSrc="testScript.js"; //See contents below
thisTest="JS";
//thisTest="JQ";
if(thisTest=="JS"){
thisScript=document.head.appendChild(document.createElement("script"));
thisScript.onload=function(){
alert("Event Triggered"); //EVENT TRIGGERS AND THE SCRIPT LOADS.
}
thisScript.src=thisSrc;
}else if(thisTest=="JQ"){
thisScript=$("<script>")
.attr({src:thisSrc})
// .bind({
.on({
load:function(){
alert("Event Triggered"); //EVENT DOES NOT TRIGGER BUT THE SCRIPT LOADS.
}
})
.appendTo(document.head)[0];
}
}
Contents of testScript.js:
alert("Script Loaded");
Both JS and jQuery successfully load the script. It's just the JQ event listener that doesn't trigger.
Resolved -- issue is order of commands.
src needs to be defined after the <script> element is in the DOM and the listeners are assigned.
So this works reliably...
$("<script>")
.appendTo(document.head)
.on({
load:function(){
alert("Event Triggered");
}
})
.attr({src:thisSrc});
Order of .on and .appendTo can be reversed, but have happen before .attr

window.addEventListener not working but window.onhashchange working?

window.addEventListener("hashchange",myFunction);
console.log(window.onhashchange); //This one prints NULL
window.onhashchange = myFunction;
console.log(window.onhashchange); // This one working fine.
function myFunction() {
alert("The anchor part has changed!");
}
Why I am not able to attach event listener using the addEventListener method ? But window.onhashchange working fine
EDIT I am indeed using the 'hashchange' not 'onhashchange' it was a typo.
There is no onhashchange event. There is a hashchange event:
window.addEventListener('hashchange', myFunction, false);
Likewise, there is no onclick event, but there is a click event:
element.addEventListener('click', someFunction, false);
testing on* properties for bound events is not an appropriate way to verify that a callback is bound. For testing, you'll have to trigger the event in some manner and have a test within the callback:
window.onhashchange = function () {
console.log('onhashchange property works');
};
window.addEventListener('hashchange', function () {
console.log('addEventListener method works');
}, false);
Click this to test
Successfully bound callbacks will not be exposed via the property.

Unbind events added by an external script loaded with jQuery's getScript function

I am loading an external script using jQuery's $.getScript function and it has something in it which I cannot understand:
if (!!window.addEventListener){ // FF
window.addEventListener('load', init, false);
} else if (!!window.attachEvent){ // IE
window.attachEvent('onload', init);
} else {
window.onclick = init;
}
Can someone please explain what this does?
I'm not sure but it adds some event listeners to check that the page is loaded.
But since I am loading the script with $.getScript function, I don't need those listeners anymore.
Is there a way to unbind them in the callback of the $.getScript function?
addEventListener adds event handlers, and attachEvent does the same for browsers that doesn't support addEventListener, which is just older IE.
The condition you have checks which one is available, and attaches an event handler to the window.onload event that calls the function init().
If none of the regular onload handler are available, it falls back to calling the init() function once the window is first clicked.
To remove the function, you'll have to try and do the opposite once the script has loaded.
You say you're using $.getScript, and that has a callback, so something like :
$.getScript('myscript.js', function() {
if (window.removeEventListener) {
window.removeEventListener( 'load', init, false );
}else if ( window.detachEvent ) {
window.detachEvent( 'onload', init );
}else{
window.onclick = function() {};
}
});
of course, it would be much easier and better to just remove the original event handler in the script you're loading if you no longer need that event handler.

Mixing window.onload and jQuery $(function(){})

Is it OK to mix window.onload and $(function(){}); of jQuery in the same script?
<script type="text/javascript">
this.onload = function () {
// do something
}
$(function () {
//do something
});
</script>
it is perfectly acceptable to do what you asked:
// check when DOM is ready
$(function(){
// place code here
console.log('DOM ready');
});
// check when all images, links and assets have been loaded
window.load = function(){
// place code here
console.log('window loaded');
};
also you can do this to make sure the DOM is ready before checking the load event
// check when DOM is ready
$(function(){
// check when all images, links and assets have been loaded
$(window).on('load',function(){
// place code here
console.log('window loaded');
});
console.log('DOM ready');
});
or with native javascript for window.load event
// check when DOM is ready
$(function(){
// check when all images, links and assets have been loaded
window.load = function(){
// place code here
console.log('window loaded');
};
console.log('DOM ready');
});
Even the JQuery API docs ready() say its ok: http://api.jquery.com/ready/
You can do this to make sure the DOM is ready before checking the window.load event. It can be placed outside yes, but sometimes due to different browser inconsistencies, and other scripts loading in.
Its perfectly acceptable for the window.load event to go inside the ready function to guarantee the window.load event fires after the DOM is ready, and not before.
Since the jQuery ready function, in some instances, will sometimes fire before all images have been loaded. when inside the ready() event, the window.load event will fire immediately once the ready handler is run if all images, links, etc have loaded.
You're referring to window.onload = function () { }; Which will be triggered after all images have been loaded, etc.
$(function () { }); or $(document).ready(function () { }); is triggered after the DOM has been successfully created, and thus, when you can be certain you can select any/specific elements.
This will work because $(function () { // ... }) is the short form of $(document).ready() and this event fires immediately after DOM is parsed/ready but window.onload fires after all resources have been loaded, including all images, so $(function () { // ... }) will fire once at first and then the onload event will fire again.
$(function () {
console.log('reday event'); // this will fire at first
});
this.onload = function () {
console.log('load event'); // this/second will fire after "ready" event
}
Also, remember, window.onload is equivalent of jQuery's load event, i.e. $( window ).load(function() { // ... }).
Check this example, (both events fire one after another, ready then onload).
I am not sure why you would as they do basically the same thing, so there should be no issue.

document won't fire mousemove event if mousedown occurred in iframe

I have a same origin iframe. Mouse events in the iframe are triggered in the document like so:
// this won't work
$('iframe').contents().find('body').on('mousedown mouseup mousemove', function(e) {
$(document).trigger(e);
});
// this does work
$('iframe').contents().on('mousedown mouseup mousemove', function(e) {
$(document).trigger(e);
});
My problem is if the mousedown occurs in the iframe and the mouse leaves the iframe, the document won't trigger it's own mousemove events until a mouseup occurs.
I've tried triggering mouseup in both the iframe and the document once the mouse leaves the iframe, but the document mousemove events won't resume until a physical mouseup occurs.
This is what worked for me on a page that had multiple iFrames:
$(function() {
$('iframe').each(function(index) {
$(this).load(function () {
$(this).contents().on("mousedown", function (e) {
$(document).trigger(e);
})
.on("mouseup", function (e) {
$(document).trigger(e);
});
});
});
});
It would work with only one iframe too. The important part is to wait for the frame load to complete before binding events, otherwise it may not work properly. In my case, the mouse events were detected properly in one iframe, but not in the other.
using object literal notation you can add multiple events to the .on(). then i added the .contents() to get all of your events to work within an Iframe. here's a working fiddle
$('.myiframe').contents().on({
mousedown: function () {
console.log('mouse down triggered');
},
mouseup: function () {
console.log('mouse up triggered');
},
mousemove: function() {
console.log('mouse move triggered');
}
});
When u call the above code from a page, it takes some time to load the frame body. Hence it cannot attach the frame mousemove event listener. If you call it with settimeout function it will be able to get the content of frame and movemove will get attched to body of frame.
:)

Categories

Resources