Noob javascript, why is this firing onload? - javascript

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;

Related

function create button with a passing argument onclick function

Can someone explain me like i'm five why is it executing the function without the click event. And how to fix it. Thanks.
function test(){
alert("works");
}
function createButton(name,location,id,funX){
var button = document.createElement("input");
button.type = "submit";
button.name = name;
button.id = id;
button.onclick = funX;
var placeHolder = document.getElementById(location);
placeHolder.appendChild(button);
};
window.onload = function () {
createButton("Submit","content","submitEnd",test());
};
http://jsfiddle.net/mabui91/yLoty39s/
When you add parenthesis to a function, you call it. Not later, but right then and there, and you return what ever the function returns.
A function in javascript returns undefined by default, unless you explicitly return something else.
What you're really writing is
createButton("Submit", "content", "submitEnd", undefined);
The last undefined is because you called the function, it would be the same as
var result = test(); // undefined
createButton("Submit", "content", "submitEnd", result);
The way to solve it, is to reference the function, not call it
createButton("Submit", "content", "submitEnd", test);
See, no parenthesis.
FIDDLE

Create a function that uses a variable if it has already been initialized

My problem is this, there is a function out of the DOM that requires a variable that is initialized to load the DOM. The problem is even if the function is not invoked before loading the DOM, it creates this error: ReferenceError: variable is not defined. How to do so, preferably with an if statement, that as long as the variable is not initialized, the part that takes the variable is ignored?
<script>
function check(){
if(num>100) alert('test');
else alert('test2');
}
window.onload = function() {
var num = Math.floor(Math.random()*11);
check();
}
</script>
I know that changing function check() with function check(num) and check(); with check(num); working properly, but I do not like this solution, I would like to understand why my code does not work...
The scope of num is all wrong. Try this:
var num;
function check(){
if(num>100) alert('test');
else alert('test2');
}
window.onload = function() {
num = Math.floor(Math.random()*11);
check();
}
num is only defined inside the onload function. You cannot access it in the check function unless you pass it as a parameter.
function check(num) {
if( num>100) alert("Test");
else alert("Test2");
}
window.onload = function() {
var num = Math.floor(Math.random()*11);
check(num);
};
(function (num) {
if( num>100) alert("Test");
else alert("Test2");
})(Math.floor(Math.random()*11));
If you're not bothered about explicitly using the window.onload event, you could just use an anonymous function like above.

how to use window.setTimeout with javascript and the module pattern

i have this example:
var myApp = (function() {
var inputClick = function() {
console.log('inputClick');
};
var loadRecentTimeout = function()
{
window.setTimeout("inputClick()",3000);
};
return {
loadRecentTimeout:loadRecentTimeout,
inputClick:inputClick
};
})();
myApp.loadRecentTimeout(); // this returns inputClick() undefined
window.setTimeout("myApp.inputClick();",3000); // this one seems to work , but it calls that method only one time and not every 3 seconds
can anyone explain how can i make this code call the inputClick() method every 3 seconds?
thanks
You want to call setInterval instead of setTimeout
var eventInterval = window.setInterval(function () {
myApp.inputClick();
},3000);
You also should pass your function as a function instead of a string.
If you need to cancel your repeating event you can call clearInterval
clearInterval(eventInterval)
When you use a string "functionName()" it evals it in window scope. Instead, assign a reference to the function with just using the name. setTimeout only fires once, you want to use a setInterval.
var myApp = (function() {
var inputClick = function() {
console.log('inputClick');
};
var loadRecentTimeout = function()
{
window.setInterval(inputClick,3000);
};
return {
loadRecentTimeout:loadRecentTimeout,
inputClick:inputClick
};
})();

JavaScript function on event running on declaration

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

How do I call a function defined in a javascript variable

I have a function defined in a javascript variable. How do I call that function within a javascript function?
function clear_viewer() {
var stop_function = "jwplayer.stop();";
// call stop_function here
}
Thanks.
function clear_viewer() {
var stop_function = "jwplayer.stop();";
eval(stop_function);
}
You shouldn't do this though, eval should be avoided if at all possible. Instead you should do something more like this, which creates a function directly for later execution.
function clear_viewer() {
var stop_function = function() {
jwplayer.stop();
};
stop_function();
}
Could always go with the 'all evil' eval():
eval(stop_function);
Obviously you need to be very careful when using eval so that you don't wind up executing malicious code accidentally. Another option would be to turn stop_function into an anonymous function that executes your code:
var stop_function = function(){
jwplayer.stop();
};
stop_function();
function clear_viewer() {
var stop_function = function(){ jwplayer.stop();};
stop_function();
}

Categories

Resources