Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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("http://www.w3schools.com");
    }
</script>
</body>
</html>
like image 283
Alex Avatar asked Aug 05 '16 04:08

Alex


People also ask

Does Onclick only work once?

JavaScript onclick function only works once (very simple code)

How do you make a button click only once in jquery?

You can use jquery . one() This will ensure that the click event happens only once.

What's the difference between onclick ={ () => function ()} and onclick function?

The difference is the first one has the parentheses and the second one doesn't.


1 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>
like image 53
Gerardo Furtado Avatar answered Oct 07 '22 23:10

Gerardo Furtado