Home > Enterprise >  JavaScript button click not executing fast enough
JavaScript button click not executing fast enough

Time:01-24

Look following example. Click on reset button, you will get console log 1 so you can confirm its working.

When you click search field, it will expand, making buttons float to new line (including reset button). Now if you try to click reset button while its in new line, the transition which closes search field will execute faster than the click on the reset button. Not a major problem but intriguing. Is this expected behavior?

document.querySelector(".reset").addEventListener("click", function(e) {
  console.log(1)
});
.wrap {
  max-width: 700px;
}

.a {
  padding: 10px 50px;
  background: #ccc;
  display: inline-flex;
}

.filter {
  width: 50px;
  transition: all 0.1s;
}

.filter:focus {
  width: 250px;
}
<div >
  <input type="search" >
  <div >button 1</div>
  <div >button 2 </div>
  <div >button 3</div>
  <div >reset</div>
</div>

CodePudding user response:

I think the issue is that the blur event is firing before the click event occurs, to remedy this you can use the mousedown event which fires before blur:

document.querySelector(".reset").addEventListener("mousedown", function(e) {
  console.log(1)
});

CodePudding user response:

onclick requires the events onmousedown and onmouseup to be concurrent.

In your case, they are separated by the focusout event, and so onclick doesn't fire.

https://w3c.github.io/uievents/#click

Depending upon the environment configuration, the click event MAY be dispatched if one or more of the event types mouseover, mousemove, and mouseout occur between the press and release of the pointing device button.

  •  Tags:  
  • Related