Reputation: 321
I'm currently recording all the mouse clicks on my html file. I have two functions for that. The first one is a general listener and records all the mouse clicks. The second one is for clicks on the html elements like buttons. The code for these two mouse events is below. When I click on a button the second function records this event. However when I click a second time on the same button right afterwards, the first function records it. In that case, I can't see on the log, that the click was on a button. How can I modify my code, so that even several consequent clicks on the button will be recorded by the respective function?
//general mouse click listener
document.addEventListener('click', showClickCoords, true);
function showMovementCoords(event) {
trackedData.push("Date.now() +" "+
event.clientX.toString()+"_"+event.clientY.toString());
}
//listener for html elements
document.getElementById("clickOnMe").addEventListener("focus", function(event) {focusFunction(event);});
function focusFunction(event) {
trackedData.push(Date.now()+" " +event.target.id );
}
Upvotes: 0
Views: 1371
Reputation: 7295
The problem is that you are using a focus
listener. That means that whenever you focus the button it will trigger that listener, so if you have already clicked it once, you will have to focus something else and then focus that button again. To fix the behavior you should just use a click
listener instead.
var trackedData = [];
document.addEventListener('click', showMovementCoords, true);
function showMovementCoords(event) {
trackedData.push("Date.now() +" + event.clientX.toString() + "_" + event.clientY.toString());
console.log(trackedData);
}
document.getElementById("clickOnMe").addEventListener("click", function(event) {
focusFunction(event);
console.log(trackedData);
});
function focusFunction(event) {
trackedData.push(Date.now() + " " + event.target.id);
}
<button id="clickOnMe">Click on me</button>
Upvotes: 3