简体   繁体   中英

How to make an eventlistener not listen until a button gets clicked?

I'm working on this game, with a timer and I have this eventlistener for when the user changes visibility, and it warns the user not to leave the tab. The problem is, it works before the button that starts the game gets clicked. Is there a way in JS to stop an eventlistener from listening, until a button gets clicked? I tried to loop a remove eventlistener and stop the loop function when the button gets clicked, although it didn't work. Thanks.

<!--This is the button that I want to start the eventlistener-->
<button onclick="start1game()" id="startgame">Continue</button>
<script>
document.addEventListener("visibilitychange", function() {
  alert('Please do not leave while playing the game.');
});
</script>

Without seeing the start1game() function declaration I can't be sure, but if you move the

document.addEventListener("visibilitychange", function() {
  alert('Please do not leave while playing the game.');
});

inside your start1game() function declaration (as the first line), then the listener will not be activated until the button is pressed. If this doesn't solve your problem I recommend editing your question to include more of the code, but bear in mind we need the minimal amount of code necessary to understand the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM