Search code examples
jqueryeventsinputevent-bubblingstoppropagation

jQuery stop event bubbling on input blur method?


I'm having a problem with jQuery and hoping for your help. I've been searching for a long time for a solution, but came up with nothing.

I have a input field, and when I click (focus) on it, some div, with a specific ID appears in DOM, and when I click somewhere else ( blur ), that div hides.

What i need to do, is when i click on that specific div, to stay it visible and not hide.

So how can I do that?

Thank you and sorry for my bad english.

$(function(){

    $('input').focus(function() {
        $('#visible-block').show();
    });

    $('input').blur(function() {
        $('#visible-block').hide();
    });

});

I have a little demo for that: http://jsfiddle.net/uJ8nW/


Solution

  • Simply check if your are hover the div when losing focus on your input before hiding it:

    $('input').blur(function() {
        if(!$('#visible-block').is(":hover"))
            $('#visible-block').hide();
    });
    

    jsfiddle

    Edit: After reading the comments, here is the new solution without the need for the blur function:

    $(function(){
    
        $('input').focus(function() {
            $('#visible-block').show();
        });
    
        $('#visible-block').blur(function() {
             $('#visible-block').hide();
        });
    
        $('html').click(function() {
            //Hide the menus if visible
            $('#visible-block').hide();
        });
    
         $('input').click(function(event){
            event.stopPropagation();
        });
    
        $('#visible-block').click(function(event){
            event.stopPropagation();
        });
    
    });
    

    Here is the update jsfiddle