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>
JavaScript onclick function only works once (very simple code)
You can use jquery . one() This will ensure that the click event happens only once.
The difference is the first one has the parentheses and the second one doesn't.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With