JavaScript function on event running on declaration - javascript

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

Related

why does function() need to be typed before the function name when using onkeydown in javascript?

I'm pretty new to javascript, and I was practicing a bit with events on W3Schools. In their tutorial, they show this line of code:
document.getElementById("demo").onkeydown = function() {myFunction()};
function myFunction() {
document.getElementById("demo").style.backgroundColor = "red";
}
I don't understand why you have to type function() {function name()} rather than just typing the function you are trying to call. Basically, I'm not understanding the logic behind that line of code. Can someone please explain it to me?
You don't need function, you can just put the function name there.
document.getElementById("demo").onkeydown = myFunction;
function myFunction() {
document.getElementById("demo").style.backgroundColor = "red";
}
<input id="demo">
You would need to wrap it inside another function if you wanted to do more than just call the function directly.
document.getElementById("demo").onkeydown = function() {
console.log("Keydown");
myFunction();
};
function myFunction() {
document.getElementById("demo").style.backgroundColor = "red";
}
<input id="demo">
You can do it, you must pass it as reference:
document.getElementById("demo").onkeydown = myFunction(); - myFunction will be called immediately and not as callback. Callback would be return value of myFunction.
You them assign it as reference:
document.getElementById("demo").onkeydown = myFunction - note that you can't pass parameters at runtime here!
In the example you give:
document.getElementById("demo").onkeydown = function() {myFunction()};
function myFunction() {
document.getElementById("demo").style.backgroundColor = "red";
}
the value of the onkeydown property of an element must be a function - not a call to a function. So you could not have for example:
document.getElementById("demo").onkeydown = myFunction();
What that would do would be to try to run myFunction and put the result from that into the onkeydown property.
Actually it would fail as at the time the system tried to run it that function doesn't yet exist.
What you could do is declare the function first and then use that as the value for the assignment.
function myFunction() {
document.getElementById("demo").style.backgroundColor = "red";
}
document.getElementById("demo").onkeydown = myFunction;

A function to execute two functions but only one executes?

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

Event Handler as a name vs anonymous functions

While implementing a closure function, I have noticed that if I provide a "named function" as an event handler then it gets executed straightaway when the event gets attached to the buttons. However, if I keep the function inline as an anonymous function then it doesn't execute straightaway and fires only on the
event happens. Please can anyone explain this behaviour?
var buttons = document.getElementsByTagName('button');
//function buttonHandler(buttonName){
//// return function(){
//// console.log(buttonName);
//// }
// alert("hello");
//}
var buttonHandler = function(name){
alert(name);
}
for(var i = 0; i < buttons.length; i += 1) {
var button = buttons[i];
var buttonName = button.innerHTML;
button.addEventListener('click', buttonHandler(buttonName));
button.addEventListener('click', function(buttonName){
alert("hi");
});
}
Many Thanks!
This has nothing to do with the function being named. This is about your code explicitly calling the function.
If you put (some,arguments) after a function then you will call it.
!foo() // calls the function
!function () { }(); // Also calls the function
So:
button.addEventListener('click', buttonHandler(buttonName));
Calls buttonHandler, passing buttonName as an argument to it
Calls addEventListener, passing "click" and the return value of 1 to it
buttonHandler has no return statement, so that return value of undefined which isn't a useful thing to pass to addEventListener.
The commented out version of buttonHandler returns a function. That would be a useful thing to pass to addEventListener.
As pointed out in the answers above the code
button.addEventListener('click', buttonHandler(buttonName));
is making direct call the function so if you only need to pass parameters to the handler function you may use an anonymous function instead of directly calling the function as recommended here (https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)
I updated my code as below
button.addEventListener('click', function (){ buttonHandler(buttonName)}, false);

Noob javascript, why is this firing onload?

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;

Javascript's object.onClick runs the function instead of setting onClick, how can I prevent that from happening and only execute the function onClick?

I have the following code:
function sdefaults()
{
alert("test");
}
var btnpos, sbtn;
btnpos = document.getElementsByName('somePosition')[0];
sbtn = document.createElement('input');
btnpos.parentNode.insertBefore(sbtn, btnpos.nextSibling);
sbtn.type = "button";
sbtn.name = "social";
sbtn.value = "Defaults";
sbtn.onClick = sdefaults();
The button appears where I want it to and the name/value are set correctly. However when I load the page, the sdefaults() function is run and then if I click the button, nothing happens. Could anyone provide any insight into how to prevent the function from running on load and force it to only run onclick?
Thanks
Change:
sbtn.onClick = sdefaults();
to:
sbtn.onClick = sdefaults;
sbtn.onClick = sdefaults(); means: "Run the sdefaults function and store the result in sbtn.onClick.
btn.onClick = sdefaults; means: "Set sbtn.onClick to the function sdefaults", which is what you're looking for.
You have to understand the difference between function referencing, and function invocation.
Consider the following function
function foo()
{
alert( 'Hello World' );
}
Now, lets look at some samples of referencing this function. To reference a function, we use its symbol name, just like any other variable.
// Alert contents of foo
alert( foo );
// Set foo as the click handler for the body
document.body.onclick = foo;
// Assign a new function to foo
foo = function(){ alert( 'Goodbye!' ); }
Now we'll consider function invocation. This means the function executes and its return value is sent back to the calling scope.
// Invoke foo simply
foo();
// Invoke foo with a specific scope
foo.apply( this ); // or foo.call( this );
Now, it's entirely possible to modify your code snippet just by changing the code of sdefaults(). Here's how that would look.
function sdefaults()
{
return function()
{
alert("test");
}
}
Now, when you execute sbtn.onClick = sdefaults(); what happens is the onClick property receives what its expecting, a function, since we've modified sdefaults to not actually alert "test", but to return an anonymous function which itself will alert "test". (As a side note, this specific technique is commonly called a lambda or delegate function)
Hope that clears it up.

Categories

Resources