Rishi Mehta
Rishi Mehta

Reputation: 303

"Click" event not getting triggered due to "blur"

To reproduce the issue, use the fiddle at [1] and follow these steps:

  1. Click on text box

  2. Input some value in it

  3. After value input, click of the "click me" button. Please Note, don't click anywhere else on the browser

  4. You would see the "button click" event not getting triggered.

The HTML code looks like this,

   <div class="wrapper">
    <input type="text" id="input"/>
    <div class="error">There is an error </div>
    </div>
    <button type="button" id="button">Click Me</button>
    <div id="log">Logs</div>

The JavaScript code for the same is:

$(function () {
   $("input,button").on("click focus blur mousedown mouseup", function (e) {
     $("#log").append($("<div/>").html(e.target.id + " " + e.type))
     var self = this     
     if (self.id === "input" && e.type=="blur") {
       $(self).trigger("exit")
     }      
   })
   $(".wrapper").on("exit", function () {         
      $(this).find(".error").hide()
      $(this).find(".error").text("")
   })
})

The issue is reproducible in "Chrome" and "firefox". Is this a know bug in "Chrome" or anyone who have faced any similar issue ?

Ideally, the click event on button has to be triggered but somehow it doesn't ? I am not able to understand the cause or a possible fix.

I don't want to use the setTimeout() to defer the "blur" event execution

[1] https://jsfiddle.net/cg1j70vb/1/

Upvotes: 8

Views: 1136

Answers (2)

rachmatsasongko
rachmatsasongko

Reputation: 186

I think its because the hide() function of your error message.

I tried to remove it and just replace the error message and it works. Demo

Upvotes: 0

Sandeep Nayak
Sandeep Nayak

Reputation: 4757

This is happening since on blur of the input you are removing the error text. That shifts the button up (possibly DOM re-paint) and hence misses the click

I removed the error message and it works fine.

$(function() {
  $("input,button").on("click focus blur mousedown mouseup", function(e) {
    $("#log").append($("<div/>").html(e.target.id + " " + e.type))
    if (this.id === "input" && e.type == "blur") {
      $(this).trigger("exit")
    }
  })
  $(".wrapper").on("exit", function() {
    $(this).find(".error").hide()
    $(this).find(".error").text("")
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <input type="text" id="input" />

</div>
<button type="button" id="button">Click Me</button>
<div id="log">Logs</div>

Upvotes: 3

Related Questions