How to make onclick event to work only once

前提是你 提交于 2019-11-30 20:22:59

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>
Stefan Miranda

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})
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!