addEventListner is triggerd before the HTMLElement is clicked - javascript

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.

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;

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.

using an argument in a function called by an event (onclick) using JavaScript

I'm trying to create an onclick event using JavaScript. I would like the onclick event to trigger a function. What I'm finding is that if I call the function without an argument or the parenthesis, the function is called when the element is clicked.
But if I try adding an argument to the function, the function is called immediately, before the element is even clicked.
What I've discovered is that if I use an anonymous function, and place the function that I want to be called by the onclick event within the anonymous function, it works!
I don't understand why. There has to be something about the logic that I'm missing.
I'm new to programming, and I would greatly appreciate any help in understanding why I can't simply call a function with an argument from an onclick event.
Thanks
Here is the code I have that works
window.onload = init;
function init() {
var divSelect = document.querySelector(".basic");
divSelect.onclick = function () {addRed(divSelect)};
}
function addRed(el) {
var divClass = el.getAttribute("class");
if (divClass == "basic red") {
el.setAttribute("class", "basic");
}
else {
el.setAttribute("class", "basic red");
}
}
If you're doing divSelect.onclick = addRed(divSelect); what's happening is that it calls addRed(divSelect), and sets the return value of that as the onclick. That's all fine if you actually return the function you want, but in most cases, it's not. That's why you need to wrap it in an anonymous function.
The other option is to use Function.bind():
divSelect.onclick = addRed.bind( // bind a context and pre-fill arguments
divSelect, // the context, can be anything in this case
divSelect); // the pre-filled argument

how to create instances of a function in javascript?

Im trying to add an event listener to a object for example:
this.startLoading = function(){
this.a.addEventListener("complete", this.loadingHandler()); this gives me an error
},
this.loadingHandler = function(){
console.log("im doing something")
}
ERROR: "Uncaught Error: addListener only takes instances of
Function. The listener for event "complete" is "undefined"
However if I put the loadingHandler() function inside the scope it works, for example:
this.startLoading = function(){
var loadingHandler = function(){...}
this.a.addEventListener("complete", loadingHandler()); // this works
},
Im not sure what instances of a function means in that regard?
When you put () after a reference to a function, that means to call the function, and the value of the expression is whatever the function returns.
Your second example, that you say works, actually will not work, and you'll get the same error if the "startLoading" function is called.
Because you probably need to retain the proper context (this), what you probably need is
this.a.addEventListener("complete", this.loadingHandler.bind(this));
The .bind() method returns a function (exactly what addEventListener requires) that in turn will invoke your function such that this has the value requested.

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.

Categories