How functions get invoked in this code? - javascript

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.

Related

animation starts before preloading CSS and Images [duplicate]

I wrote a JavaScript class called MyClass in which I've defined a method closeThis
MyClass = function() {
this.closeThis = function() {
document.getElementById("hidePane").style.display = 'none';
}
}
Now, in my html, i'm trying to call that as follows...
<script type="text/javascript">
function callThis() {
var myclassObj = new MyClass();
document.getElementById("closeButton").onclick = myclassObj.closeThis();
}
</script>
The above callThis will be called when I clicked on a button. The problem here is, onclick event on top of clsoeButtion is getting called automatically when page loads. What could be wrong in this?
You're calling the function right away.
When you leave the parentheses on the function reference, what you're basically saying is:
Evaluate the closeThis function and assign the result to onclick
when what you really want to do is assign the function reference to the click handler:
document.getElementById("closeButton").onclick = myclassObj.closeThis;
Leave out the parentheses instead, and you'll bind the closeThis function to the onclick. What this instead says is:
Assign the function closeThis to the click handler.
You are essentially assigning the function to the variable as a first-class object, or a reference to a function.
As an aside, my personal preference is to always use an anonymous function wrapper. Sometimes you need to be able to pass parameters into your function, and this makes sure that you can more easily do so:
document.getElementById("closeButton").onclick =
function() {
myclassObj.closeThis();
};
it should be
document.getElementById("closeButton").onclick = myclassObj.closeThis;
not myclassObj.closeThis();
myclassObj.closeThis() will call the function then assign value to onclick
You need to remove () from it otherwise it gets called immediately because that's how you call a function by suffixing (), so simply remove these braces:
document.getElementById("closeButton").onclick = myclassObj.closeThis;

addEventListner is triggerd before the HTMLElement is clicked

I'm using an addEventListner method on a HTMLElement inside a function that is called on onLoad. However, the method gets executed even before i try the click event in the html page.
function setConfigurationMenu(){
var navConfigure = document.querySelector(".navConfigure");
var navBody = navConfigure.querySelector(".body");
var navTop = navConfigure.querySelector(".top");
navTop.addEventListener("click", alert("jow"));
}
So what's going on here, any ideas?
thx,
This is happening because you are executing the alert function and passing its return value (which is undefined) as parameter to the addEventListener method. You actually need to pass a function to it.
navTop.addEventListener("click", functionToBeTriggered);
As alert expects a parameter that is your text, you might want to wrap it into an anonymous function that calls it. For example:
navTop.addEventListener("click", function() {
alert("jow")
});
This happens because you pass function result instead of function handler, try anonymous function for this:
navTop.addEventListener("click", function() {
alert("jow");
});
In other words in your case you just invoke function, but you need to pass handler for this.

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); });

Function getting called on the load of page

for (var key in obj[i]) {
dataDump[key] = textField.value;
var callback = function(zeKey){
return function(e){
dataDump[zeKey] = e.source.value;
};
}(key);
textField.addEventListener('change', callback);
}
When I load the window, this function gets called automatically, which I don't want and instead I want this to be called only when I do a change.
The main point is calling function(zeKey){...}(key). When you do so, key, which is a string is copied as a parameter (zeKey) to your anonymous function.
The following
var callback = function(zeKey){
return function(e){
dataDump[zeKey] = e.source.value;
};
}(key);
Calls the anonymous function with argument zeKey.
This anonymous function returns another function. This returned function is assigned to the callback.
If 1 what you mean by "the function is getting called" then this is expected behavior.
This entire code should be called only after DOM is ready. Place all these in a function and make sure the function is called only on window.onload or (jQuery's) .ready()
The function returned by the function will be called only during the callback.
Add these code once dom is created. If above code is inside a function, attach to window.load or write these code at the end of page.

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