I am having some problems with function declarations in IE. It appears, even if I link the function directly to the window object. I tried switching with document in stead of window, but with no success.
Here is the basic code that I am trying to use:
window.addEventListener('load', function () {
function initChart (id) {...}
//linking to window object
window.initChart = initChart;
});
As I said, I even tried to link it directly: window.initchart(id){...}. More that that, I even included the js file I declared the function inside the body(due to a rumor that says that IE doesn't see function declared in head section)
After that, inside script tags i call initChart() with a valid id and I get this error inside the IE console: 'initChart' is undefined.
<script>
initChart('chart');
</script>
The strange thing is that in Chrome, Firefox and Opera has no such problem. Any ideeas?
PS: If this is a duplicate, I did not found the question that covers this.
You also need to do initChart('chart'); inside of the window load event handler (this one or a later added one). Or you can do that in another event handler that you know for sure happens after this window load event handler.
As your code is processed by the browser, it knows to do something on the window load event, which is to set your window.initChart.
But then later on you are using it right away, without the event of window load happening yet.
If it doesn't happen in Chrome, I am wondering if everything is loaded, but even so, I'd think your window.initChart is set in the next event cycle. (let me try to do some experiments -- you are not doing any of these in the debugger but all inside an HTML file?). But it really shouldn't be ok in Chrome, because the load event handler doesn't occur before your <script> tag is parsed and executed, which does initChart('chart'); already.
But in any event, it is best to follow the event sequence: if you set window.initChart on window load event handler, then also only call window.initChart() in the same and later added event handler, or in an event handler that happens afterwards.
You can see in the following HERE 02 happens before HERE 01:
window.addEventListener('load', function() {
console.log("HERE 01");
});
console.log("HERE 02");
I am running the following in Chrome and I did get an error as expected:
window.addEventListener('load', function() {
function foo() {
console.log("HERE 01");
}
window.foo = foo;
});
foo();
But this one worked as expected:
window.addEventListener('load', function() {
function foo() {
console.log("HERE 01");
}
window.foo = foo;
});
window.addEventListener('load', function() {
foo();
});
The problem apparently was not the linkage between the function and the window object. In my load event I had some ES6 string interpolation(something like this: console.log(`#${id}`)) and IE falls short on this. He doesn't know what to do with it. So as a consequence, my window.initChart() was not even compiled. After I commented the code in matter, my initChart function was working fine. Thanks for help tho, #nopole!
Related
I'm working on a plugin for Trumbowyg where I'm trying to store a function in a variable so it can be called later but also be over-writable without altering the included javascript file.
The problem is, the function is not being called when I try to call it.
Here is my relevant code:
init: function (trumbowyg) {
var plugins = trumbowyg.o.plugins;
...
if(!plugins.giphycrumbs.close_modal) {
plugins.giphycrumbs.close_modal = function() {
console.log('close modal');
$(plugins.giphycrumbs.modal_selector).modal('hide');
}
}
$(document).on('click', '.add_giphy', function() {
trumbowyg.execCmd('insertImage', $(this).attr('src'), false, true);
plugins.giphycrumbs.close_modal;
});
// If the plugin is a button
trumbowyg.addBtnDef('giphycrumbs', {
//this function is handled exactly the same way except it actually works
fn: plugins.giphycrumbs.open_modal
});
}
In my code above, you can see I am checking if plugins.giphycrumbs.close_modal is NOT set, and if thats true, I set it to a function which is supposed to close a modal.
In my click handler for .add_giphy, the insertImage code works, but plugins.giphycrumbs.close_modal is never executed (I don't get the console.log message embedded in the function)
If I do console.log(plugins.giphycrumbs.close_modal) the expected function is put into the console.
Why is the close_modal function not executed in my code?
Answer
Try adding parentheses to close_modal inside your click handler.
Explanation
It seems to me like you are not invoking (calling) this function.
In your click handler, there's this line plugins.giphycrumbs.close_modal;
In javascript, this is a reference to a property on the giphycrumbs object. Though it happens to be a function, it will not be invoked as such unless you use parentheses after it (and optionally give it some arguments).
Hope that helps! 👍
I'm facing a weird issue. The console.log() outside the onload function works, but the console.log() inside doesn't work... Would it mean that my page never fully loads ? I had a look at the developer tools of Chrome and it shows me that the page is loaded, so I don't really understand... (here is a screen of the devtool)
Here is my code:
console.log("hello1");
window.onload = function()
{
console.log("hello2");
};
(I'm using this in a WordPress website, but I don't think it changes anything)
Thanks in advance,
ArbreMojo.
Some other code is probably assigning another function value to the window.onload method, so it basically overrides your assignment.
Instead of window.onload = function you can do:
window.addEventListener('load', function() {
console.log('loaded')
})
which allows attaching an arbitrary number of handlers for that event. This ensures nothing can override your callback function.
See: EventTarget.addEventListener for more info.
I have observed a strange behavior while learning jQuery and Javascript. When I call a variable that is defined inside the $(document).ready, from outside these tags it appears undefined, even when I define it as a global variable,
For example:
$(document).ready(function() {
myVar = "test";
});
alert(typeof(myVar));
//Results "undefined"
If I call the same variable inside the document.ready tags it works as expected
$(document).ready(function() {
myVar = "test";
alert(typeof(myVar));
//Results "String"
});
The result is same even after using window prefix.
$(document).ready(function() {
window.myVar = "test";
});
alert(typeof(window.myVar));
//Results "undefined"
I understand about the variable scopes but why even global variables aren't working this way. I am so confused.
The code inside the "ready" handler will not run until the DOM has been fully built. The code outside the handler will run as soon as it is encountered. Thus, your alert() runs before the code in the handler runs, so the outcome makes perfect sense: the global variable has not yet been initialized, so its value is undefined.
You can see the sequence of execution clearly by putting alert() (or, better, console.log()) calls inside the "ready" handler:
$(document).ready(function() {
console.log("In the 'ready' handler");
});
console.log("Outside the 'ready' handler");
When that runs, you'll see the "Outside" message logged first.
Because the alert() is executed before your document is perfectly ready.. You may try even by declaring the variable before $(document).ready() still it will return undefined..
The $(document).ready() gets fired after the page is fully loaded
When the script tag is fully loaded the alert gets executed.
So
Script tag is loaded => Execute alert
Continue loading page
Page completly loaded => fire $(document).ready
You var is getting set
The alert gets executed before your var is set
The other answers are correct but it is probably important to also note the $(document).ready(...) is also hiding your variable from the global scope. You could declare your variable then update it within the function
var myVar;
$(document).ready(function() {
myVar = "test";
});
console.log(myVar) // test
The execution plan it's like
//this statement shall fix the driver, not run it
$(document).ready(function() {//-->this it's an event handler waiting to be fired when content is fully loaded
myVar = "test";//-->myVar won't exists until this event is triggered
});
//this execute the alert function but myVar not exist yet
alert(typeof(myVar));
$(document).ready() is like to assign an event who will execute after the content is loaded, which means alert(myVar) will run before the lambda execution which was set as the content-loaded event. I hope you'll understand me.
I am facing an issue where a jQuery function is not being called even though the proxy has successfully loaded (from what I can tell). The call we are making works fine on first load, but when we try to load this script in via AJAX it calls the required $.proxy() to the Initialise function, but then doesn't actually call that function.
The dynamic loaded in code is:
<script language="JavaScript"><!--
var ctrl = new VideoControl({"Id":"bc1093c8290a4037846c2052695a7d3a"}, "...");
//-->
</script>
And the javascript to create the object is:
function VideoControl(controlIds, videoMarkUp) {
this.controlIds = controlIds;
this.videoMarkUp = videoMarkUp;
var thisControl = this;
$(function () { $.proxy(thisControl.Initialise(), thisControl); });
}
VideoControl.prototype.Initialise = function () {
// do stuff
}
So the main function is called, but the Initialise() is not called when this is loaded in via AJAX controls in Chrome or IE...this does however work in firefox.
There is a stackoverflow answer which explains why $function is not being called but how do I get it to a point it will call (similar to how firefox deals with it)
Is anyone aware of something that firefox does differently when working with jQuery vs the other browsers?
There are no errors showing on the chrome developer tools, is there anywhere else that could be looked at in order to diagnose this?
Thank you in advance.
So the main function is called, but the Initialise() is not called
when this is loaded in via AJAX
$(function() {}) is alias for .ready() ; handlers for .ready() should be called at most once . AJAX appear to occur after document is loaded ? , where .ready() has previously called , $.isReady set to true preventing handlers within subsequent .ready() or $(function(){}) from being called.
Try removing $(function() {}) wrapper surrounding
function VideoControl(controlIds, videoMarkUp) {
this.controlIds = controlIds;
this.videoMarkUp = videoMarkUp;
var thisControl = this;
$.proxy(thisControl.Initialise, thisControl);
}
use
$(document).ready(VideoControl)
Though , not certain why $.proxy is used here ? , as the context of thisControl.Initialise not appear to be changed to a different context : this ?
Note also that js at Question thisControl.Initialise() called function; where function should be referenced jQuery.proxy( function, context [, additionalArguments ] )
This is a SSCCE.
Consider the following code:
<html>
<head>
<script type="text/javascript">
window.addEventListener("load", eventWindowLoaded, false);
var eventWindowLoaded = function () {
console.log('event window loaded');
};
</script>
</head>
<body>
</body>
</html>
It's not working but the question is not how to fix it. Rather the question is why is JavaScript failing so silently when the eventWindowLoaded variable is not yet assigned. When debugging in Chrome I see nothing printed on the console and have no indication that something went amiss. The code just silently fails. What options / tools do I have to ensure that while developing JavaScript fails more spectacularly than that? ("use strict"; does nothing either).
As you seem to know about hoisting (judging by the down votes) you know why your code isn't working. So to get to the point of ensuring JS fails more spectacularly you could change your code to:
window.addEventListener("load", eventWindowLoaded || function(){ throw new Error('An error message' )}, false);
The eventWindowLoaded variable is "hoisted", so when the window.addEventListener method is called this is passed as "undefined". Internally the event listener must be set to ignore undefined or null methods quietly.
There is nothing wrong here.
If you use a function declaration instead of a function expression your code will work as expected.
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded () {
console.log('event window loaded');
};
I won't explain but read up on JavaScript Hoisting.
Function expressions (as in your example) are not hoisted to the top on page load. Function declarations are however.
As a result at the time that your load event calls eventWindowLoaded it is undefined.
So either use a function declaration or, place your function expression above your load event.