Reputation: 45
I am trying to achieve the following functionality: Once user has clicked on a button, I want to add click event listener to window element to alert a message (say).
Consider the below snippet for this purpose:
<button id="b1">click</button>
<script>
document.querySelector("#b1").addEventListener('click', () => {
window.addEventListener("click", () => {
alert("hello");
});
})
</script>
But, unfortunately, the above code also alerts message when the user initially clicks on button (which I don't want). Any idea on how I can achieve the functionality?
Upvotes: 0
Views: 3891
Reputation: 802
It would be better to add the window click event listener and have a flag to determine if the alert should appear.
The problem with the method you are using is every time a user clicks the button you add a new event listener to the window. This will then stack up and fire multiple times for each click of the document.
To stop the button click from passing through to the document and also triggering the window event listener you can use the event stopPropagation()
method as demonstrated below.
let hasButtonBeenClicked = false;
window.addEventListener("click", () => {
if(hasButtonBeenClicked) {
alert("hello");
hasButtonBeenClicked = false;
}
});
document.querySelector("#b1").addEventListener('click', (e) => {
e.stopPropagation()
hasButtonBeenClicked = true;
})
<button id="b1">click</button>
Upvotes: 1