简体   繁体   中英

Stop onclick event, once onblur event got active

I have one text field and one button, I just want to ignore onclick event on button, when onblur events got activated. I tried a few methods but didn't work for me.

<!DOCTYPE html>
<html>
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction(event)"> 
<button onclick="calldiv(event)">Click</button>
<script>
function myFunction(event) {
 // event.preventDefault();
 //   event.stopPropagation();
 // event.stopImmediatePropagation();
console.log("blur");
}
function calldiv(event) {
 console.log("div");
}
</script>
</body>
</html>

Result...

1st time button got clicked:-blur

2nd time button got clicked:-div

an easy way to solve it is to make an if statement inside calldiv function

<body>
  Enter your name: <input type="text" id="fname" onblur="myFunction(event)" />
  <button id="button" onclick="calldiv(event)">Click</button>
  <script>
    let blured = false;
    function calldiv(event) {
      console.log(blured);
      if (!blured) {
        console.log("div");
      } else {
        blured = false;
      }
    }
    const currentButton = document.getElementById("button");

    function myFunction(event) {
      console.log("blur");
      blured = true;
    }
  </script>
</body>


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM