This question already has answers here:
addEventListener calls the function without me even asking it to
(5 answers)
Closed 4 years ago.
I'm trying to create some appropriately-placed instructional tooltips that users click through to understand how the site interface works. Each tooltip has a "next" link that toggles the visibility of the previous and next tooltips by modifying the classes (and hence, css).
Here's some simplified code that is supposed to do this:
function displayTooltip(t){
//...some code to determine the tooltip IDs "next" and "previous"
document.getElementById(previous).className = "tooltip invisibleTooltip";
document.getElementById(next).className = "tooltip";
}
document.getElementById("tooltip-link1").addEventListener("click", displayTooltip(2));
displayTooltip is called immediately (and correctly toggles the class) when I paste this code into the console (or on page load). If I replace displayTooltip with an alert(), it fires when I click, as anticipated. What am I doing wrong?
When you are binding event you are calling the function document.getElementById("tooltip-link1").addEventListener("click",displayTooltip(2));
You need to pass reference to the function.
Change to below
document.getElementById("tooltip-link1").addEventListener("click", function(){
displayTooltip(2)
});
When you write functionName followed by (), it will call function. If you wish to assign function to a handler, you should do
document.getElementById("tooltip-link1").addEventListener("click", displayTooltip);
Now if you wish to pass parameter to this function, you can either wrap it inside a function like
document.getElementById("tooltip-link1")
.addEventListener("click", function(){displayTooltip(2)});
Or you can use .bind()
document.getElementById("tooltip-link1")
.addEventListener("click", displayTooltip.bind(this, 2));
You need to call this method as a callback. Since you are calling it as displayTooltip(2) you are ultimately calling the function at that line.
What you need to do is to bind a callback rather than calling at that line.
Something like
.addEventListener('event', function()
{ displayTooltip(2) }
Hope this be of some help
Happy Learning
Related
This question already has answers here:
addEventListener calls the function without me even asking it to
(5 answers)
Closed 4 years ago.
I'm trying to create some appropriately-placed instructional tooltips that users click through to understand how the site interface works. Each tooltip has a "next" link that toggles the visibility of the previous and next tooltips by modifying the classes (and hence, css).
Here's some simplified code that is supposed to do this:
function displayTooltip(t){
//...some code to determine the tooltip IDs "next" and "previous"
document.getElementById(previous).className = "tooltip invisibleTooltip";
document.getElementById(next).className = "tooltip";
}
document.getElementById("tooltip-link1").addEventListener("click", displayTooltip(2));
displayTooltip is called immediately (and correctly toggles the class) when I paste this code into the console (or on page load). If I replace displayTooltip with an alert(), it fires when I click, as anticipated. What am I doing wrong?
When you are binding event you are calling the function document.getElementById("tooltip-link1").addEventListener("click",displayTooltip(2));
You need to pass reference to the function.
Change to below
document.getElementById("tooltip-link1").addEventListener("click", function(){
displayTooltip(2)
});
When you write functionName followed by (), it will call function. If you wish to assign function to a handler, you should do
document.getElementById("tooltip-link1").addEventListener("click", displayTooltip);
Now if you wish to pass parameter to this function, you can either wrap it inside a function like
document.getElementById("tooltip-link1")
.addEventListener("click", function(){displayTooltip(2)});
Or you can use .bind()
document.getElementById("tooltip-link1")
.addEventListener("click", displayTooltip.bind(this, 2));
You need to call this method as a callback. Since you are calling it as displayTooltip(2) you are ultimately calling the function at that line.
What you need to do is to bind a callback rather than calling at that line.
Something like
.addEventListener('event', function()
{ displayTooltip(2) }
Hope this be of some help
Happy Learning
Here's a function where it suppose to work when I click a "button
but surprisingly it immediately invoked without calling!
const show_card = (shopping_card_checkout) => {
console.log("ali el-deeb");
};
document.querySelector('.fa-shopping-cart').addEventListener('click', show_card()) ;
If I tried to redo the code after the event listener it says reference error as I called the function before declaration.
Help a beginner.
Saw your post request in JS FB group and thought I'd answer here.
First you need to use document.ready or make sure that all js is loaded as last cause else the element might not yet exist. This is not th cause of your problem btw. The problem I explain as last but some advice. You use a class and querySelector, querySelector will fetch the first element in the document and if you want all elements returned you need querySelectorAll and this is not unique or would you like to bind the same action and functionality to many elements? So better would be to use the unique id of an element and use something like:
const myElement = document.getElementById("idName");
myElement.addEventListener("click", myFynction);
const myFunction = () => console.log("Clicked");
The real cause of your issue
You bind the function to the click event and bind it with () behind it and that triggers the execution cause now you don't bind the function but the result of the bound function, you can't pass parameters like that to a bound event. You will need to fetch them inside the function cause only event and a callback can be triggered.
So your working code is:
const show_card = (shopping_card_checkout) => console.log("ali el-deeb");
document.querySelector('.fa-shopping-cart').addEventListener('click', show_card);
And if only one return or one statement inside an arrow function there is no need for the curly brackets and no need to use return since it will automatically return the result of the oneliner.
This question already has answers here:
addEventListener calls the function without me even asking it to
(5 answers)
Closed 4 years ago.
I'm trying to create some appropriately-placed instructional tooltips that users click through to understand how the site interface works. Each tooltip has a "next" link that toggles the visibility of the previous and next tooltips by modifying the classes (and hence, css).
Here's some simplified code that is supposed to do this:
function displayTooltip(t){
//...some code to determine the tooltip IDs "next" and "previous"
document.getElementById(previous).className = "tooltip invisibleTooltip";
document.getElementById(next).className = "tooltip";
}
document.getElementById("tooltip-link1").addEventListener("click", displayTooltip(2));
displayTooltip is called immediately (and correctly toggles the class) when I paste this code into the console (or on page load). If I replace displayTooltip with an alert(), it fires when I click, as anticipated. What am I doing wrong?
When you are binding event you are calling the function document.getElementById("tooltip-link1").addEventListener("click",displayTooltip(2));
You need to pass reference to the function.
Change to below
document.getElementById("tooltip-link1").addEventListener("click", function(){
displayTooltip(2)
});
When you write functionName followed by (), it will call function. If you wish to assign function to a handler, you should do
document.getElementById("tooltip-link1").addEventListener("click", displayTooltip);
Now if you wish to pass parameter to this function, you can either wrap it inside a function like
document.getElementById("tooltip-link1")
.addEventListener("click", function(){displayTooltip(2)});
Or you can use .bind()
document.getElementById("tooltip-link1")
.addEventListener("click", displayTooltip.bind(this, 2));
You need to call this method as a callback. Since you are calling it as displayTooltip(2) you are ultimately calling the function at that line.
What you need to do is to bind a callback rather than calling at that line.
Something like
.addEventListener('event', function()
{ displayTooltip(2) }
Hope this be of some help
Happy Learning
I am a beginner in javascript. and have no experience in programming, at all.
So I'd like you to be generous to beginner.
And here is my question.
I'm trying to code javascript unobtrusively.
So I put in all of my js codes into external js file. for example : test.js
and deleted these codes. to do unobtrusive js coding. for example :
and I tried to use these 2 methods :
variable.onclick=test(arg1, arg2);
variable.addEventListener('click',test(arg1, arg2),true);
but these triggers didn't work.
to put it delicately, function test(arg1, arg2) worked right after dom loding finished. regardless of activating 'click' trigger.
So I spent several hours solving this problem, and finally got a solution. this is it.
variable.onclick = function(){
variable.addEventListener('click',test('arg1','arg2'),true);
}
I wanna know why first two methods didn't work, and why that solution works well.
I solved the problem, but don't know why, and how...
In JavaScript, when you reference a function by name and follow that reference by a parenthesized list of arguments, that means that you want to call the function, right then and there. Thus a statement like
variable.onclick=test(arg1, arg2);
will assign to the "onclick" property the value obtained by calling the "test" function. In other words that statement means
Please call the function "test" passing it "arg1" and "arg2", and assign whatever it returns to the "onclick" property of the object referenced by "variable".
An event handler must be a function, however, and your "test" handler probably returns either nothing, or something that's not a function. So it didn't work.
Your solution, however, is also incorrect. You're successfully assigning a function to the handler property, but your function is itself installing another event handler. There's no reason to do that here, and in general setting up event handlers from within other event handlers is a suspicious practice. All you need is:
variable.onclick = function() { test(arg1, arg2); };
variable.onclick requires a function declaration by design. In your case you could have just done
variable.onclick = function(){
test(arg1,arg2);
};
The way you did it won't work because you're not giving the click handler any instructions. The corrections I have made say that when the variable (the one with the click handler attached) is clicked trigger this function that will in turn trigger the test function.
Same thing goes for the second one
variable.addEventListener('click', function(){
test(arg1,arg2);
});
This works again because you are saying when this variable is clicked run the function that will trigger the test function.
Basically you are trying to assign the result of running a function, the test function as a task for the click handler to run. This won't work except maybe your test function returns a function that contains code that you want to run when the click event is triggered. Hope this helps.
I dont understand javascript syntax well,my question:
How jquery define click function for get parameter inside anonymous function?
The Case:
$("a").click(function(event) {
alert(event.type);
});
in C the function should be defined:
void click(fn,event){
}
in javascript its looks to me that she defined as- (but where defined event?):
click (fn){
}
please explain to me the jquery syntax of click function code source here.
Thanks,
Yosef
If you just want to find out where the event object is passed to your handler, that would be line 2568 of the jQuery-1.5.2 redistributable source code (or line 438 of the actual, un-contatenated source file):
var ret = handleObj.handler.apply( this, args );
In the above line of code, handler is your anonymous function and args is an array whose first element is the event object. jQuery uses the apply method of the JavaScript Function object to invoke the handler and pass in the arguments
The jQuery source code is quite complex when it comes to full sequence of adding and handling events so, unless you want a line-by-line explanation of hundreds of lines of code, I suggest you rephrase your question to a smaller scope (e.g. You could create a toy demonstration of the scenario you want to understand).
Perhaps this will help?
dosomething(function(message) {
alert(message);
});
function dosomething(fn) {
fn("Hello!");
}
The first part of the jQuery is the selector $("a") which selects and returns object(s) selected from the DOM. In this case, it will return a list of all anchor tag objects on the page.
Then, you are chaining the .click() method to that, jQuery attaches an event listener to all of the anchor tags. When the event listener is attached, it is more or less the equivalent of doing
<a href='..' onclick='someFunction(event)'>some link</a>
...which passes the event object to the function.
For example, compare to this:
<a onclick='blah(event)'>click</a>
<script type='text/javascript'>
function blah(e) {
alert (e.type);
}
</script>
If I click on it, I will see "click" in the alert. In principle, jQuery is doing the same thing.