difference between alert("Hi!") and function(){alert("Hi!")} [duplicate] - javascript

This question already has answers here:
What is the difference between a function call and function reference?
(6 answers)
Closed 7 years ago.
When we are doing inline command in the button:
<button id="myButton" onclick="alert('Hi!')">
Why does
document.getElementById("myButton").onclick = alert('Hi!')
not work but give the alert as the page is loaded? I can't understand how it works with function() added to it and without function(). I hope you guys understand my question. I'm missing something here.

document.getElementById("myButton").onclick = alert('Hi!')
is wrong since onclick should be assigned to a function reference, not the function call result itself.
It will execute alert('Hi!') when the page is loaded but that is not the intention here, is it? The intention behind assigning an onclick handler is to ensure that when the button is clicked this alert will be executed.
For that to happen it should be:
document.getElementById("myButton").onclick = function(){alert('Hi!')};
Also, this will not work unless it is wrapped inside the window.onload event:
window.onload = function(){
document.getElementById("myButton").onclick = function(){alert('Hi!')};
};

alert('Hi!') is a function call that alerts 'Hi' and returns nothing (undefined).
onclick expects to get a function and you are passing the function call's result which is undefined.
Since JavaScript is not a strong typed framework you don't get an error on bad assignments.
So why does the following work:
<button id = "myButton" onclick="alert('Hi!')">
It's because the html parser (in this case, your browser) does some work behind the scenes and wraps the call with a function.

document.getElementById("myButton").onclick expects a function to be called later.
<button id = "myButton "onclick="alert('Hi!')"> expects a block of code to be executed later.

alert('Hi')
Here alert is an inbuilt function called by browser which opens a alert box.
function callAlert(){
alert('Hi');
}
Here callAlert is a custom function which calls the inbuilt function alert
In your example, when appending a click event, you have to define the function
document.getElementById("myButton").onclick = alert('Hi!') //alert is
already executed
document.getElementById("myButton").onclick = function (){ alert('Hi!') };
//a function is defined/declared which will be executed when the onclick action is performed

See this post for explanation for why the inline version works.
In short, the browser doesn't just assign alert('Hi!') to onclick but instead wraps it in a function.

Related

Java script addEventListnere to keypress event [duplicate]

This question already has answers here:
What is the difference between a function call and function reference?
(6 answers)
Closed 7 years ago.
When we are doing inline command in the button:
<button id="myButton" onclick="alert('Hi!')">
Why does
document.getElementById("myButton").onclick = alert('Hi!')
not work but give the alert as the page is loaded? I can't understand how it works with function() added to it and without function(). I hope you guys understand my question. I'm missing something here.
document.getElementById("myButton").onclick = alert('Hi!')
is wrong since onclick should be assigned to a function reference, not the function call result itself.
It will execute alert('Hi!') when the page is loaded but that is not the intention here, is it? The intention behind assigning an onclick handler is to ensure that when the button is clicked this alert will be executed.
For that to happen it should be:
document.getElementById("myButton").onclick = function(){alert('Hi!')};
Also, this will not work unless it is wrapped inside the window.onload event:
window.onload = function(){
document.getElementById("myButton").onclick = function(){alert('Hi!')};
};
alert('Hi!') is a function call that alerts 'Hi' and returns nothing (undefined).
onclick expects to get a function and you are passing the function call's result which is undefined.
Since JavaScript is not a strong typed framework you don't get an error on bad assignments.
So why does the following work:
<button id = "myButton" onclick="alert('Hi!')">
It's because the html parser (in this case, your browser) does some work behind the scenes and wraps the call with a function.
document.getElementById("myButton").onclick expects a function to be called later.
<button id = "myButton "onclick="alert('Hi!')"> expects a block of code to be executed later.
alert('Hi')
Here alert is an inbuilt function called by browser which opens a alert box.
function callAlert(){
alert('Hi');
}
Here callAlert is a custom function which calls the inbuilt function alert
In your example, when appending a click event, you have to define the function
document.getElementById("myButton").onclick = alert('Hi!') //alert is
already executed
document.getElementById("myButton").onclick = function (){ alert('Hi!') };
//a function is defined/declared which will be executed when the onclick action is performed
See this post for explanation for why the inline version works.
In short, the browser doesn't just assign alert('Hi!') to onclick but instead wraps it in a function.

Why does my JavaScript automatically execute functions? [duplicate]

This question already has answers here:
Why does click event handler fire immediately upon page load?
(4 answers)
Closed 6 years ago.
var season = "10";
$( document ).ready(function() {
$("#table").hide();
});
$('#searchButton').on("click", showTable(event));
function showTable(event){
$("#table").show();
document.getElementById("td").innerHTML = season;
}
How is it possible, that the function showTable(event) is automatically executed when the page is loaded?
Another problem is, that the click event doesn't work if the button is clicked.
What did I do wrong?
How is it possible, that the function showTable(event) is automatically executed when the page is loaded?
Because you are calling the function: showTable(event). () after a function reference means to execute the function. You are calling showTable and passing the return value (undefined) to .on().
Here is a simplified example:
function foo() {
return 42;
}
function bar(x) {
console.log(x);
}
bar(foo());
This calls the function foo, and passes its return value (42) to bar, which in turn logs the value.
If we'd write bar(foo) instead, we'd pass the function itself and bar could execute the function.
What did I do wrong?
You are calling the function. Pass it to .on instead and let the browser call it:
$('#searchButton').on("click", showTable);
The line:
$('#searchButton').on("click", showTable(event));
Actually executes showTable(event). What you want is:
$('#searchButton').on("click", showTable);
Why?
When you have $('#searchButton').on("click", showTable(event));, what is sent to the .on() is the result of the showTable(event) function execution.
If you use $('#searchButton').on("click", showTable);, what you send as second argument to the .on() function now is a reference to the showTable function, not its result.
By saying showTable(event), you are invoking the function.
What you need to do is this:
$('#searchButton').on("click", function (event) {
showTable(event)
});

onclick firing on page load, need to call function with parameters

Sorry if this may be deemed a slight duplicate, however I couldn't find an answer that helped me understand why myFunc() is firing on page load and not when I click el1 or el2. How can I make the following code behave as expected?
function myFunc(param){
//yadayada
}
el1.onclick = myFunc('string1');
el2.onclick = myFunc('string2');
Thanks.
document.getElementById('el1').onclick = function() { myFunc('string1'); };
document.getElementById('el2').onclick = function() { myFunc('string2'); };
You need to get the elements on the page first and then assign a function to them, otherwise the parser will execute them onload because it thinks that myFunc() is returning a value to be assigned to onclick as opposed to the actual function myFunc().

JavaScript - Calling a function with and without parens [duplicate]

This question already has answers here:
In JavaScript, does it make a difference if I call a function with parentheses?
(5 answers)
Closed 9 years ago.
Take the following code:
HTML
<button id="button>click me</button>
JS - VERSION 1
window.onload = init;
function init() {
console.log('init called');
var button = document.getElementById('button');
button.onclick = buttonClickHandler;
}
function buttonClickHandler() {
console.log('button clicked');
}
vs Same HTML
JS - VERSION 2
window.onload = init();
In both cases, 'init called' appears in the console "immediately", but in the second case, it is followed by an error stating button is null.
There are 2 things at play here. 1) In version 1, it waits for the DOM to load 2) in version 2, it's happening before the DOM is loaded, or so it seems.
My question. Please explain as clearly as possible what is happening in version 1 vs what is happening in version 2. What are the technical terms for what window.onload = init is vs what window.onload = init() is? Also please explain each versions behaviour. Why does 1 wait, but 2 doesn't?
The script needs to go before the button element e.g. in the head: http://jsfiddle.net/XMEjr/1/
Version 1 sets init function to be the one that's called on window.onload event. The function is not invoked on that line; it's just assigned (as a value) to a property.
Version 2 sets the result of init function to be the one that's called on window.onload event. It's the difference that () makes.
Apparently init function is called before onload is fired (to get that result and set it as onload handler). So the function starts, fails to find element by button id (as DOM is not ready yet), so getElementById returns null. Then trying to access onclick property of null stops it with an error.
in the second one you are assigning to onload the result of the call to init :)
It would be equivalent if you do:
window.onload="init()"
In this case you are assigning a String that gets evaluated upon DOM is ready.
If you do
window.onload=init
You are assigning a reference to a function. Then again, when DOM is ready, the function gets called
But if you do:
window.onload=init()
you could do
function init() { alert ("this is called before onload, dom is not ready, button doesnt exist"); return init2; }
function init2() { alert ("this is called on load, dom is ready, button and everything in the body is now created"); }
hope you get the point.
By the way, this case would be useful to do something like this:
window.onload=init()
function init() {
if (IS_IPHONE) return init_iphone;
if (IS_ANDROID) return init_android;
if (IS_WINDOWS) return init_not_supported;
}
so you select which init method to execute onload.

Why is function() needed sometimes in JavaScript?

HTML
<button id='hello'>Click Me!</button>
JavaScript (wrong)
$('#hello').click(alert('Hello, World!'));
JavaScript (correct)
$('#hello').click(function() {
alert('Hello, World!');
}
I'm wondering why the first JS code triggers on the event load instead of click. Can anyone tell me why function() { [code] } is needed for the script to work properly?
In this example, I used jQuery events, but this is not specific to it, for example, I need to use it with setTimeout, too.
The click function expects another function as a parameter.
In the first case you would be passing the result of calling alert('hello world');, which is null.
The second is just a shorthand for:
$('#hello').click(callback);
function callback(){
alert('hello world');
}
Because .click() is a handler. The first argument is a function to assign. But if you actually pass the function with arguments then it will call the function (in this case alert) and then pass it's return value.
Writing $('#hello).click( function() { } )` is basically a short hand for writing:
var myfunction = function() {
// code
};
$('#hello').click( myfunction );
As you can see in the long hand way, it's passed as a reference to the function instead of the function's return value.
Your first example says "evaluate
alert('Hello, World!')
right now, and pass the result as an argument to click. "
The second says "Define a function which will do the alert when I call it, and pass that whole function as an argument to click.
The function() { ... } syntax is how you declare an anonymous function in Javascript. jQuery uses lots of these to specify that some action will be performed later, like when an event occurs. You can think of it as delaying the execution of your function until necessary. Without this syntax, whatever code you place there is evaluated immediately, which is not what you want for an event handler.
You might think, "why isn't JavaScript smart enough to know the difference?" Consider this:
function returnCallback(linkId, data) {
return function(e) {
alert('Clicked on ' + linkId + '. Here is some data: ' + data);
// Maybe do some stuff with e, the event parameter
}
}
$('#some-link').click(returnCallback('some-link', 'some-data'));
$('#other-link').click(returnCallback('other-link', 'different-data'));
This is a contrived example, but it illustrates the power of anonymous functions and closures. This works since returnCallback returns a function.
In the first instance, "JavaScript wrong", you're actually calling alert('Hello, World!') at the point that the script is loaded. Now, the reason you pass the .click function a function is because it can call it at any point. Essentially, you're packing code together to be run (or not run at all) at any point when you put it in a function.
$('#hello').click(alert('Hello, World!')); is attempting to run alert('...') and pass its return value to the .click() function which will not work as expected.
This is because JavaScript evaluates everything and during this process your alert is invoked. You can use anonymous function or you can also use your own custom function as implemented below:
<script language="javascript" type="text/javascript">
$("#mybutton").click(clickFired);
function clickFired() {
alert('click fired');
}
</script>
The parameter required for the .click() function is a Function. Therefore $("#hello").click(function { [code] }); is required. Because there's nothing to return by alert().
The click function here assigns a value to the event handler.
With the first ("wrong") code you're assigning a value of alert('Hello, World!') which is itself a function call, so it's going to be immediately evaluated and hence appear at load.
With the second ("correct") code you're now assigning a new anonymous function which is not executed itself, just instantiated at load. Hence this will work as expected later.
somefunction(alert('hello! world'));
this would mean you want to pass to somefunction the return value of alert("hello! world").
jquery click expects a callback that it should fire upon click on the element. so you put it in a function which does not execute unless someone (here jquery) calls it explicitly.

Categories