Hi I'm new to javascript. here is my code. what I want to do is when someone click anywhere in the page. A new window will open, but I want this to happen only once, so when someone click again on body, the function should not run. Any advice? No jquery please
<!DOCTYPE html>
<html>
<body onclick="myFunction()>
<script>
function myFunction() {
window.open("http://www.w3schools.com");
}
</script>
</body>
</html>
A short solution:
<body onclick="myFunction(); this.onclick=null;">
Check it:
<button onclick="myFunction(); this.onclick=null;">This button works only once</button>
<button onclick="myFunction()">This button works always</button>
<script>
function myFunction() {
console.log("hello");
}
</script>
</body>
There are couple of ways to do it.
1.Add event listener to body in the script and then remove once clicked.
<!DOCTYPE html>
<html>
<body>
<script>
document.body.addEventListener('click', myFunction);
function myFunction() {
window.open("http://www.w3schools.com");
document.body.removeEventListener('click', myFunction);
}
</script>
</body>
</html>
2.Have a flag to check if the function was already called.
<!DOCTYPE html>
<html>
<body onclick="myFunction()">
<script>
var isBodyClicked = false;
function myFunction() {
if(isBodyClicked === false){
window.open("http://www.w3schools.com");
document.body.removeEventListener('click', myFunction);
}
isBodyClicked = true;
}
</script>
</body>
</html>
The below uses an IIFE to create a closure holding the boolean variable and avoid populating global name space, explicitly attach a function to global object window
and check if it's the first time the function is fired
function(){
var firstTime = true;
window.myFunction = function() {
if (firstTime){
firstTime = false;
window.open("http://www.w3schools.com");
}
}
}()
<script type="text/javascript">
function load() {
document.body.removeEventListener('click', load)
window.open('https://google.com/', '_blank')
}
window.onload = function() {
document.body.addEventListener('click', load)
}
</script>
Using "once" in the "options" parameter for the addEventListener
method is unironically enough a great way of using a function once.
function myFunction(){
console.log("hey")
}
document.body.addEventListener("click", myFunction,{once:true})
来源:https://stackoverflow.com/questions/38781349/how-to-make-onclick-event-to-work-only-once