addEventListener(click,...) firing immediately
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)
});
Event Listener Callback Fires Immediately When Set Inside The Callback of Another Event Listener. ReactJS
When you click on the input, few events occur such as mousedown
, mouseup
, focus
click
. (fyi - click happens when a mousedown and mouseup event occur on the same element). In chrome, focus handler is executed first and then the click handler is executed (if the handlers exist).
Now, in your code when you click on the input, focusHandler
is executed where a click handler is attached to the window
. By the time the js engine finishes the execution of focusHandler
, there is a click handler registered already. So as soon as focusHandler
is executed, the js engine realises that 'ah, there is a clickHandler that I need to execute it. Let me do it' . Hence your clickHandler fires immediately.
You can test it by attaching event handler in a setTimeout. In below code, js engine has no clickHandler to execute after focusHandler
execution is finished. So click handler won't fire immediately.
const focusHandler = e => {
console.log("onFocus");
e.stopPropagation();
setTimeout(() => window.addEventListener("click", clickHandler), 1000);
};
Why does addEventListener fire before the event if at all?
The root of your problem is here:
button.addEventListener("click", addTextNode(button.innerHTML))
You're executing the function rather than passing it to the event listener. Instead, pass the function by reference, then get the innerHTML inside the function.
function addTextNode() {
var newtext = document.createTextNode(this.innerHTML),
p1 = document.getElementById("p1");
p1.appendChild(newtext);
}
var btns = document.getElementsByTagName("button");
for(i = 0; i < btns.length; i++){
var button = btns[i];
button.addEventListener("click", addTextNode);
}
http://jsfiddle.net/bn85J/
AddEventListener fires automatically upon assignment
Add e.stopPropagation()
at the end of your box
function :
function box(e) {
var pop = document.getElementById("mspop");
pop.style.display = "block";
document.addEventListener("click", clik);
e.stopPropagation();
}
See this fiddle : http://jsfiddle.net/vfyzgv1t/
What is happening is that when you click on your li
element, the click is then transmitted to the container, and so on up to the window (the so-called event bubbling), and as you have added a event listener on the document (which is between your li
and the window), it is being triggered.
The solution proposed here, e.stopPropagation
stops the propagation so that the click on the document is not triggered.
UPDATE : Another way is to delayed shortly the adding of the new eventListener : http://jsfiddle.net/vfyzgv1t/1/ :
function box(e) {
var pop = document.getElementById("mspop");
pop.style.display = "block";
setTimeout(function() {
document.addEventListener("click", clik);
}, 10);
}
Javascript click event listener fires only once
After many more hours, I've finally figured it out. The problem was essentially the highly dynamic content of the new Twitter website. After submitting a tweet, the Tweet
button gets indeed removed and added again. In needed to do a serious of changes:
Use a
MutationObserver
to keep track of any changes. Every time there's a change, call theinitialize()
function. To avoid too many calls, I do this in case of certain changes (unnecessary detail here)Change the
addSubmitNewTweetClickHandler()
method so that the event listener first gets removed in order to avoid duplicate listeners (please note that I use objects hence the use ofthis
compared to my original question)addSubmitNewTweetClickHandler : function() {
let that = this;
let buttonSubmitTweet = document.querySelector("div[data-testid='tweetButtonInline']");
buttonSubmitTweet.removeEventListener('click', this.handleSubmitNewTweetClick );
this.handleSubmitNewTweetClick = this.handleSubmitNewTweetClick.bind(this)
buttonSubmitTweet.addEventListener('click', this.handleSubmitNewTweetClick );
},This change required to create the reference function
handleSubmitNewTweetClick
Overall, it's still not a perfect solution since I call initialize()
many unnecessary time. However, I failed to reliably identify when the Tweet
button was added to the document. When I used the MutationObserver
none of the added nodes had the attribute data-testid
which I need to identify the correct button. I have node idea why this attribute was not there. Maybe the attribute is added some times after added to button, but even with an additional MutationObserver
looking for attribute changes I could detect this.
Anyway, it works now and it's only for a prototype.
javascript click event handler fires without clicking
You are directly calling it.
document.getElementById("main_btn").addEventListener("click", hideId("main");
You should do that in a callback.
document.getElementById("main_btn").addEventListener("click", function (){
hideId("main");
});
addEventListener calls the function without me even asking it to
Quoting Ian's answer:
Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is
undefined
...because all the function does isalert
and doesn't return anything). Either call the function in an anonymous function (like your first example) or alter the function to return a function.
function message_me(m_text){
alert(m_text)
}
second.addEventListener('click',
function() {
message_me('shazam');
}
);
Here's an updated fiddle.
When I call .addEventListener(click, myFunction(i), false); It runs my function on the call and not on the click
addEventListener needs to assign the function variable. In your code you are calling the function immediately using (). To fix it you can remove them.
classname[selected].addEventListener("click", formating, false);
To pass argument to your function you can either wrap it in an anonymous function and call it or use bind (source):
classname[selected].addEventListener('click', formating.bind(null, event, arg1, ... ));
Prevent Event Listener firing event multiple times
useEffect(() => {
var foo1 = (e) => {
if (e.code === "ArrowUp") {
if (props.selectInterval - 1 >= 0) {
props.setSelectInterval(props.selectInterval - 1);
}
}
if (e.code === "ArrowDown") {
if (props.selectInterval + 1 < props.row.length) {
props.setSelectInterval(props.selectInterval + 1);
}
}
};
document.addEventListener("keyup", foo1);
return () => {
document.removeEventListener("keyup", foo1);
};
}, [props.selectInterval]);
well this works for me! thanks to both contributors above!
Related Topics
Difference Between Client-Side and Server-side Programming
Download File Using an Ajax Request
How to Call PHP Functions by JavaScript
Execute PHP Function With Onclick
JavaScript Does Not Fire After Appending
"Mixed Content Blocked" When Running an Http Ajax Operation in an Https Page
Pass JavaScript Variable to PHP Via Ajax
Encrypt With PHP, Decrypt With JavaScript (Cryptojs)
How to Refresh Page on Back Button Click
Determine Timezone from Latitude/Longitude Without Using Web Services Like Geonames.Org
Displaying Pdf from Arraybuffer
Do Dom Tree Elements With Ids Become Global Properties
Three.Js Ray Intersect Fails by Adding Div
How to Use Mechanize to Process JavaScript
Jsfiddle Code Not Working in My Own Page