Search code examples
jqueryevent-handlinglistenerjquery-events

jQuery one event prevents other event from being fired


I'm unsure about what I am overlooking. If my design is just bad or if there is a smart way of solving this.

Given:
1 input field
1 hidden button

Logic:
If the input field is focused, the hidden button gets shown.
If the input field is unfocused, the button gets hidden.
If the button is clicked, some function is called, and then the button gets hidden.

The problem is that when the button is clicked, the input field gets unfocused just before, so the unfocus listener fires first and somehow the button-click listener never fires.

Why is this? Why aren't both listeners triggered?

Current code structure:

$(someinputfield).focus(function(){
    show button
}
$(someinputfield).focusout(function(){
    hide button
}
$(somebutton).click(function(){
    deliver();
    hide button
}

deliver(); never gets executed!

Edit:
Here the real code:

      $("#input1").focus(function(){
          $("#submit1").delay(600).queue(function(next){
              $(this).css('display', 'block');
              next();
          });
      });
      $("#input1").focusout(function(){
          $("#submit1").hide();
      });
      $("#submit1").click(function(){
          deliver();
          setTimeout(function(){
              $(this).hide();
          }, 2000);
      });

Solution

  • Use input instead of button for the button.

    that way the input will remain focus when you click on the button, but not outside.

    Your selector for the .focus() event will have to include both the input and it's button, in my example below I have simply selected ALL inputs. You will need to change this.

    $(function(){
    
        $('input').focus(function(){
            $('.button').show();
        });
    
        $('input').blur(function(){
            $('.button').hide();
        });
    
        $('.button').click(function(){
            alert("clicked");
        });
    
    });
    

    JSFiddle here http://jsfiddle.net/Panomosh/2cjmggqe/2/