shashi
shashi

Reputation: 4696

How do I hide a div when it loses its focus?

Basically I am trying to implement a login such as that of the new twitter. When you click on Sign In a div pops up with the fields. Now when I click anywhere outside the div (div losing focus) then the div should disappear.

I have tried the technique mentioned at How to blur the div element?

The code is as follows:

$("body").click(function(evt) {
            
            if (evt.target.id !== 'loginDialog') {
                $("#loginDialog").hide();
            }
        });

The trouble with that is the target.id will not equal to loginDialog even if I click somewhere withing loginDialog say within a child div.

So the above is a good direction to proceed towards, but the solution is incomplete.

What is the best way to achieve this?

Upvotes: 3

Views: 7672

Answers (3)

pestaa
pestaa

Reputation: 4749

If moving your mouse outside is not enough and you want it to disappear only if the user clicks outside of it, here's a snippet that might help you.

$('body').click(function(evt) {
    if($(evt.target).parents('#loginDialog').length==0) {
        $('#loginDialog').hide();
    }
});

Upvotes: 8

S L
S L

Reputation: 14318

Better to use jquery fancybox plugin for iframe http://fancybox.net/ in the various example

[UPDATE]::Sorry for stupid hypothetical code. check the working code

<script type="text/javascript">
    $(function (){
        $(document).click(
            function (e){
                var blur = $('#blur');
                var position = $(blur).position();
                var height = $(blur).height();
                var width = $(blur).width();

                if((e.clientX > position.left && e.clientX < position.left + width) && 
                    (e.clientY > position.top && e.clientY < position.left + height)
                ){
                    alert(e.clientX+' '+e.clientY);

                }
                else{       
                    /*Hide the div*/                    
                        $('#blur').hide();
                    /*Hide the div*/

                }


            }
        )
    })
</script>
<div id="blur">Blur me</div>

Upvotes: 4

Jishnu A P
Jishnu A P

Reputation: 14382

Not such a good practce but might work...

$('body').click(function(){
     $('#loginDialog').hide();     

});
$('#loginDialog').click(function(evt){
    evt.stopPropagation();
});

Upvotes: 1

Related Questions