Why is function() needed sometimes in JavaScript? - 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.

Related

Function stored to a variable not running when called

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! 👍

Calling jQuery event handler on click : anonymous vs named function behaviour

Playing around with the .on('click', ) event and I get differing behaviour based on whether I supply an anonymous vs named function (the named function doesn't work). Is this a syntax error?
<div id="myID"> abc </div>
<script>
$("#myID").on('click',function(e){
console.log(e.type);
}); //works
function handle(e){
console.log(e.type);
}
$("#myID").on('click',handle(e)); //doesn't work
</script>
You need to replace
$("#myID").on('click',handle(e));
with
$("#myID").on('click',handle);
When you call a function, it is executed immediately. This happens when you do
$("#myID").on('click',handle(e));
You call the function, passing an event e which does not exist yet. What you want instead is giving jQuery a function that it should call when the user clicks on the element with the id myID.
This is possible in JavaScript because it has first-class functions. This means that if you create a function like this:
function handle(e){
console.log(e.type);
}
then you get a reference to the function that you just created. This reference is stored in a variable named handle. You could achieve the same if you do:
var handle = function (e) { // create a function and store a reference to it in a variable
console.log(e.type);
};
The function takes an argument e. This doesn't exist yet, it has to exist in the moment you call the function:
handle(e); // ReferenceError: e is not defined
You can pass the reference to that function to jQuery, which then calls your function when the user clicks the element. At that point, e still doesn't exist, because it will contain information about the event, which hasn't occured yet. It will look like this:
$("#myID").on('click', handle); // pass a reference to the handle function to jQuery
Now, handle doesn't get called, because you only pass a reference to the function. You could say that you pass the function as an argument to another (jQuery) function. This is called a callback function.
Edit
Note that all functions that were created above take e as their argument. The argument doesn't have to exist in the very moment you create the function. However, when you (or jQuery) call the function, you have to provide an argument so that the function can do its job.
It's the same with an unnamed function: you create the function, but the argument does not exist yet. When you (or jQuery) call the function, you have to provide an argument.
This means there is no essential difference. The only difference is that one function has a name, the other one doesn't. You could even do this:
$("#myID").on('click', function handle (e) { // pass a reference to the function, but do not call it
console.log(e.type);
});
... which has the same effect as:
$("#myID").on('click', function (e) { // pass a reference to the function, but do not call it
console.log(e.type);
});
... except that in the first example, you keep a reference to the function that you created in a variable called "handle". In the second example, you lose the reference to the function, and only jQuery will be able to use your function.
Edit end
Another example for that would be:
var testFunction = function (arg) {
console.log('My argument is:', arg);
};
var executeTwoTimes = function (callback) { // accept a callback function as the first argument
callback('foo'); // execute the callback function
callback('foo');
};
executeTwoTimes(testFunction); // pass a reference to testFunction
// or:
executeTwoTimes(function (a) { // pass a reference to an anonymous function
console.log(a + ' bar');
});
I hope I could make things clearer for you.

Why can't we pass parameter in eventListener's listener function?

function myFunc(parameter1) {
//function definition
}
document.getElementById("some Id").addEventListener("click", myFunc(myparameter));
Why is it that I cant pass a parameter to myFunc() function inside the eventListener? I know I can use this way -
document.getElementById("some Id").addEventListener("click", function() {
myFunc(myparameter);
});
But why can't I do it directly ?
PS- I want to know whether the rules prescribed by W3C are to be followed directly (and I shouldn't ask this question) or is there a reason behind every rule ?
myFunc(myparameter) executes the function right now, not when the event is triggered. You want to pass a function which executes myFunc and passes the parameter when called, i.e. when the event is triggered. The most straight forward way to do that is this:
.addEventListener('click', function () { myFunc(myparameter); })
The perhaps less obvious way is Function.prototype.bind:
.addEventListener('click', myFunc.bind(null, myparameter))
You have a problem in your code. The myFunc(myparameter) executes right way. You need to call your custom function using this way:
document.getElementById("some Id").addEventListener("click", function () {
myFunc(myparameter);
});

How functions get invoked in this code?

I can't understand the order of execution takes place here:
<script>
$(function(){
function f(id){
document.body.innerHTML += "<p>executing handler for div " + id + "</p>";
}
document.getElementById("div1").onclick = function(){
f("1");
}
document.getElementById("div2").onclick = function(){
f("2");
}
document.getElementById("div3").onclick = function(){
f("3");
}
});
</script>
What I want to know is how the 'function' and 'f' are called? Is it like when someone click on 'div' then function gets invoked? If it is so, why the function is on the right side of "=" operator?
When someone clicks on div1 the onclick method triggers function f with a passed value of 1. Ditto when div2/3 are clicked on, f is called with those values.
All f does is change the content of the page to show a message.
I'm not sure why this is using document.body.innerHTML though, I would normally expect to see a div that shows a message, such as document.getElementById('message').innerHTML.
I have a feeling (without checking) that document.body.innerHTML will change the whole content of the page to the value that f outputs. I doubt that is the desired result.
Explained in comments, line by line:
<script>
// this is a jQuery shorthand for $(document).ready. That means, that this function is executed automatically, when the DOM is ready
$(function(){
// declaration of a function that will be executed when it's called from somewhere. 'id' is an argument that can be passed
function f(id){
document.body.innerHTML += "<p>executing handler for div " + id + "</p>";
}
// 'onclick' is an event handler. When you click the div container with the id 'div1', then the function, set after '=', gets executed
document.getElementById("div1").onclick = function(){
// call the function that you declared above with the argument "1"
f("1");
}
document.getElementById("div2").onclick = function(){
f("2");
}
document.getElementById("div3").onclick = function(){
f("3");
}
});
</script>
If I'm understanding you correctly based on your question of "why the function is on the right side of = operator?", your question really related to = function(){ in the following code.
document.getElementById("div1").onclick = function(){
f("1");
}
What this code is doing is assigning an anonymous function to the onclick property of the div1 element.
When a user clicks on the div1 element, this anonymous function is executed. Within the anonymous function, a call is made to the function f passing the string "1".
The reason the anonymous function is needed is because if you were to exclude this and simply have this:
document.getElementById("div1").onclick = f("1");
Rather than calling the f function when the element is clicked, you would immediately call the f function and set the returned value (undefined) to the onclick property. By wrapping it in an anonymous function, you get the desired effect of calling f with the given parameter when the element is clicked.
According to what you have asked
$(function(){
});
gets executed on load of a page
if you want to call function f() you need to call as
$(function(){
f();
});
$(function(){...} is the jQuery function for document.ready. This function is executed as soon as all of the DOM is ready. It is a feature of jQuery. You don't call it explicitly - jQuery handles that for you.
The f() function is attached to the click handlers (onclick) that are defined for the three div elements. When they are clicked, they trigger the f() function.
The function is on the right side of an assignment because what the code is actually saying is replace the default onclick function with the one defined.

function called on page load not jquery .click

This function gets called on page load, not when .somebutton is clicked. I'm not sure why. I want to be able to pass the variables so that I may use this function in multiple places with different values. Thank you very much.
var i = "this be i";
var u = "this be u";
function dosomething (var1, var2){
console.log(var1 + " and " + var2);
}
$(".somebutton").click(dosomething(i,u));
You are passing value returned by dosomething(i,u) to click handler. This is why it ise executing without clicking, it is happening as soon as you call your function (that is: dosomething(i,u)). You need to wrap your function call inside anonymous function:
$(".somebutton").click(function() { dosomething(i,u); } );
You can only pass a function by reference using the method in your example (ie. without parameters). The reason your function works on load is because it is immediately invoked due to the trailing () brackets.
If you need to pass parameters you need to wrap it in an anonymous function, like this:
// on click:
$(".somebutton").click(function() {
dosomething(i, u);
});
// on page load:
dosomething(i, u);
In JavaScript doing
$(".somebutton").click(dosomething(i,u));
will not assign the function to your click event, but will rather call the function and assign whatever result the function returns. You need to reference your function instead :
$(".somebutton").click(dosomething);
If you need to pass variables to your function, then you need to wrap the said function inside another anonymous one :
$(".somebutton").click(function() { dosomething(i, u); });

Categories