How to make onclick event to work only once

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(""); } </script> </body> </html> 
4

6 Answers

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>
2

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(""); 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(""); document.body.removeEventListener('click', myFunction); } isBodyClicked = true; } </script> </body> </html> 
2

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}) 

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(""); } } }() 
<script type="text/javascript"> function load() { document.body.removeEventListener('click', load) window.open(' '_blank') } window.onload = function() { document.body.addEventListener('click', load) } </script> 

This is JQuery code.

We can use bind() unbind() / on() off() as below to avoid multiple click.

OR

We can use one() function to happen click only once.

$(document).ready(function () { $('body').bind('click', function () { alert('button clicked'); $(this).unbind('click'); }); }); 

OR

$(document).ready(function () { $('body').one('click', function () { alert('button clicked'); }); }); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like