0

I am wondering how should I hide a drop down list by clicking on anywhere in page, I want same function like select field (<select></select>) do, if we open any select field and then click anywhere in page it pop back.

Let me know if my question is not clear.

Thanks.

472084
  • 17,666
  • 10
  • 63
  • 81
Dheeraj Agrawal
  • 2,347
  • 11
  • 46
  • 63

2 Answers2

1
var mouse_is_inside = false;

$(document).ready(function()
{
    $('.form_content').hover(function(){ 
        mouse_is_inside=true; 
    }, function(){ 
        mouse_is_inside=false; 
    });

    $("body").mouseup(function(){ 
        if(! mouse_is_inside) $('.form_wrapper').hide();
    });
});

Stolen from Use jQuery to hide a DIV when the user clicks outside of it

Community
  • 1
  • 1
472084
  • 17,666
  • 10
  • 63
  • 81
  • Keep in mind that now every mousup triggers the event handler, which may slow down the UI if used extensivly. It would be better to bind and unbind the handler! – Sgoettschkes Feb 20 '12 at 10:24
  • @Boo thanks for the comment, sorry but can you tell me how should I bind & unbind the handler? It will be really helpful if you explain this by using above example. – Dheeraj Agrawal Feb 20 '12 at 10:32
0

If you want to use bind and unbind, you would simply bind the event handler when you show the content and unbind it when you hide it, because if it's hidden there is no need to hide it with the mouse.

So, you would do something like:

$('#fakeSelect').click(function(){
    if($(this).is(":visible")){
        $('body').unbind('mousedown', mouseFunction);
    } else {
        $('body').uind('mousedown', mouseFunction);
    }
});

MouseFunktion would be something like:

var mouseFunction = function(event){
    if($(event.target).closest('#fakeSelect').length > 0){
        return;
    }
    $('#fakeSelect').hide();
}

The if statement checks if the click was inside the fakeSelect, in which case you don't want to do anything (either the click event takes care or you want to implement something like to check which element was clicked.

I did a jsfiddle to illustrate the whole point: http://jsfiddle.net/Sgoettschkes/vrnjw/2/

Sgoettschkes
  • 13,141
  • 5
  • 60
  • 78