I'm using in a project the following code which is not working:
window.onload=function(){
//code here
};
but if I add at the end () it works:
window.onload=function(){
//code here
}();
My question is, what's the difference? What does the () at the end?
I presume that the first one doesn't work because somewhere else the "onload" has been already called killing this one.
Would it have the same behaviour if I always use the second option ?
() at the end of function, calls this function immediately after declaration
window.onload=function(){
//code ehere
}() // function is called
And in this case
window.onload=function(){
//code here
};
function will be called after
window.onload()
When you have () after a lambda function such as that, it means you're calling the function immediately on that line.
So, for example,
var x=function() {
return 5;
}();
console.log(x);
would log 5 in the console. In the case of
window.onload=function() {
//code here
}();
that function most likely returns another function that gets called when the page loads.
For example,
window.onload=function() {
return function() {
console.log("Hello!");
};
}();
will log "Hello!" in the console when the page loads.
function is assigned to onload
window.onload=function(){
//code ehere
};
result of function is assigned to onload
window.onload=function(){
//code ehere
}();
With the () the function you define is called immediately. In that case, it better return a function to assign to window.onload.
Related
I have tried using a function to execute two functions when the page loads using window.onload, the issue I am having is that the function (myFunc) only executes the first function from the top (Func1) but not (Func2), the function looks like this
window.onload = function myFunc(){
return Func1();
return Func2();
}
So how can I execute both of them?
Try this :)
make sure you define Functions before calling them, this is good practice
//Arrow function and remove the return
const Func1 = () => {
console.log('This is Func1');
}
const Func2 = () => {
console.log('This is Func2');
}
window.onload = myFunc = () => {
Func1();
Func2();
}
do not return because after return goes out of function
window.onload = function myFunc(){
Func1();
Func2();
}
Remove the return keywords, and just run the function as is.
Ref: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
window.onload = function() {
Func1();
Func2();
};
No need for return statements and naming the function. It should trigger both functions, if not please make sure the code change is reflected in the source by putting a breakpoint or adding a debugger; inside the function. Also check if both the function body are doing the same action so that you are concluding as second one not executing.
js engine finishes the execution of function on return keyword.
so dont use return keyword to execute both functions
I have the following code:
function fn($){
return function(){
innerFn = function(){
setTimeout(show, 1000);
};
show = function(){
$.alert("TEST");
}
}
}
But, after one second, when the function show is run, it says $ is undefined. How do I resolve this issue?
how to pass arguments to a function in setTimeout
setTimeout has a built in mechanism for adding params
var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
use it.
If you're going to use this - you should be careful. but that's another question.
There are a number of things at play here. The most important being that your setTimeout never gets called, since innerFn never gets called. This should do the trick.
function fn($){
return function(){
setTimeout(function(){
$.alert("TEST");
}, 1000);
}
}
fn(window)(); //triggers your alert after 1000ms
Your code makes no any sense, because nothing is called:
function fn($){
return function(){
innerFn = function(){
setTimeout(show, 1000);
};
show = function(){
$.alert("TEST");
}
}
}
Let's say I'm calling fn passing window, then a function is returned, that I can executed. But because this function is containing only function declaration - you also forget var so you pollute the global scope, that is bad - nothing is happen.
You'll need at least one function call inside, like:
function fn($){
return function(){
var innerFn = function(){
setTimeout(show, 1000);
};
var show = function(){
$.alert("TEST");
}
innerFn();
}
}
fn(window)();
And that will works. However, it's definitely redundant. You can just have:
function fn($){
return function(){
function show(){
$.alert("TEST");
}
setTimeout(show, 1000);
}
}
To obtain the same result. However, if you're goal is just bound an argument to setTimeout, you can use bind. You could use the 3rd parameter of setTimeout as the documentation says, but it seems not supported in IE for legacy reason.
So, an example with bind will looks like:
function show() {
this.alert('test');
}
setTimeout(show.bind(window), 1000);
Notice also that window is the global object by default, so usually you do not have to do that, just alert is enough. However, I suppose this is not your actual code, but just a mere test, as the alert's string says.
If you prefer having window as first parameter instead, and you're not interested in the context object this, you can do something like:
function show($) {
$.alert('test');
}
setTimeout(show.bind(null, window), 1000);
So I dont understand why the console logs 1 right away onload or something when i have one.onclick = alterIt(1) shouldn't it wait till i click one. Anyway, obviously I am not ver good at javascript, thanks for your help.
window.onload = initialize;
function initialize() {
if (1 == 1){
calculation();
}
}
function calculation() {
var one = document.getElementById('one');
one.onclick = alterIt(1);
}
function alterIt(x) {
console.log(x);
}
When you wrote:
one.onclick = alterIt(1);
...then you invoked the alterIt function and set the return value as the onclick handler. Instead, you wanted:
one.onclick = function(){ alterIt(1) };
// ...or better yet
one.addEventListener('click',function(){ alterIt(1) },false);
When the line one.onclick = alterIt(1); is executed, alterIt(1) is actually evaluated. What you want is to bind a function to one.onclick, which is only executed when the onclick event fires. You need something like
one.onclick = function() { alterIt(1) };
which doesn't bind the result of alterIt(1) to one.onclick, but rather the result of the function evaluation.
Wrap the function call like this so it doesn't fire until click:
window.onload = initialize;
function initialize() {
if (1 == 1){
calculation();
}
}
function calculation() {
var one = document.getElementById('one');
one.onclick = function(){ alterIt(1);};
}
function alterIt(x) {
console.log(x);
}
Example fiddle: http://jsfiddle.net/RkH6Q/
There are two ways that you could code to work around this issue:
//Anonymous Closures
one.onclick = function(){ alterIt(1); };
//Bind Closures
one.onclick = alertIt.bind(window, 1);
Note: Function.bind() is supported by all the browsers for a year. If you care about old browsers, anonymous closures is the way to go.
What is happening is that you are calling the alterIt function when you should just be passing it in. So remove the parenthesis like so:
one.onclick = alterIt;
Why when i load page it runs function and alerts me "function run" i did not call it nowhere i need function to only trigger on element click.
<script type="text/javascript">
open_close = function() {
alert("function run");
//some code ...
}
window.onload = function() {
//some code ...
var myButton = document.getElementById('button');
myButton.onclick = open_close();
//some code ...
}
</script>
Here's jfiddle demo http://jsfiddle.net/ayeBP/
Ah, but you did run it:
myButton.onclick = open_close();
Parentheses invoke a function. Use this instead:
myButton.onclick = open_close;
Better still (click through for legacy IE support):
myButton.addEventListener('click', open_close);
Okay this was simplidied function i need to actually pass 2 variables to it e.g. myButton.onclick = open_close(var1,var2);
You still cannot use parentheses as you keep trying to do, because parentheses invoke the function. Use an anonymous function:
myButton.onclick = function () {
open_close(var1, var2);
};
// or, even better,
myButton.addEventListener('click', function () {
open_close(var1, var2);
});
Replace open_close() with open_close
Using parentheses here will invoke the function immediately and assign the return value of it to myButton.onclick
Let me start here. At w3cshools.com - http://www.w3schools.com/jsref/met_win_setinterval.asp - they have a snippet demo-ing how to use javascript setInterval function (surprisingly it has a mismatched </form> but thats beside the point).
I needed to use setInterval() and at times I like referring to some "standard" body to take a glimpse of the recommended usage. In my development environment, something seems to be mangling setInterval() behavior/working when I use it within a jquery $(document).ready(function() { ... }); block.
Illustration 1 - WORKS: Typical/Traditional <script> block
<script type="text/javascript">
var refreshIntervalId;
function testMessage() {
window.alert("Hello");
}
refreshIntervalId = setInterval("testMessage()", 5000);
</script>
Illustration 2 - DOES NOT WORK: jQuery block
<script type="text/javascript">
$(document).ready(function() {
var refreshIntervalId;
function testMessage() {
window.alert("Hello");
}
refreshIntervalId = setInterval("testMessage()", 5000);
});
</script>
Illustration 3 - WORKS:
jQuery block - using setInterval(testMessage, 5000) instead of setInterval("testMessage()", 5000)
<script type="text/javascript">
$(document).ready(function() {
var refreshIntervalId;
function testMessage() {
window.alert("Hello");
}
refreshIntervalId = setInterval(testMessage, 5000);
});
</script>
It turns out that if I try to pass the function as a string from with the $(document).ready(function() {}); block, I get an error indicating that the function is not defined. Just so we dont get side-tracked IE, Chrome, and Firefox all report errors:
IE: Microsoft JScript runtime error: The value of the property 'testMessage' is null or undefined, not a Function object
Chrome: Uncaught ReferenceError: testMessage is not defined (anonymous function)
Firefox: testMessage is not defined.
What I would like to find out (if possible) is, could this be a result of standards non-conformance or what be going wrong when I try to use setInterval("testMessage()", 5000) from within the jQuery block? Could some mangling be happening or is this the right behavior?
setTimeout and setInterval break scope, so it can't find testMessage when it goes looking for it (because that function is scoped inside the anonymous function you pass to ready). Browsers are behaving correctly.
This is one of the reasons you should never, ever use the string format … or try to learn from the dreadful W3Schools.
The reason that the browsers say that the function isn't defined, is that it's not defined in the scope where the interval runs. You have declared the function locally inside another function, so it doesn't exist in the global scope where the interval runs.
This is not due to jQuery, simply due to the anonymous function that you wrap the code in. This code shows the same error:
(function() {
function testMessage() {
window.alert("Hello");
}
var refreshIntervalId = window.setInterval("testMessage()", 5000);
})();
You can declare the function globally instead, then you can use a string for the interval:
function testMessage() {
window.alert("Hello");
}
(function() {
var refreshIntervalId = window.setInterval("testMessage()", 5000);
})();
Common practice is to use the function itself rather than a string in the interval call:
(function() {
function testMessage() {
window.alert("Hello");
}
var refreshIntervalId = window.setInterval(testMessage, 5000);
})();
If you need to pass a value to the function, you can use an anonymous function in the call:
(function() {
function testMessage(msg) {
window.alert(msg);
}
var refreshIntervalId = window.setInterval(function() { testMessage("Hello"); }, 5000);
})();
function testMessage() and any other function must be declared OUTSIDE $(document).ready()
as #Quentin mentioned it's because the testMessage function is defined within the document ready and so outside the scope of the interval.
If you must define you're interval within the document ready you could do
refreshIntervalId = setInterval(function() {
window.alert("Hello");
}, 5000);