sasidhar sasidhar - 4 months ago 36
jQuery Question

Focus out event not working as expected in jquery

Here is the JavaScript I am using:

<script type="text/javascript">

$(document).ready(function(){
var left_pos= document.getElementById('login_button').offsetLeft;
var top_pos= document.getElementById('login_button').offsetTop+5;
document.getElementById('login_box_pane').style.left=left_pos;
document.getElementById('login_box_pane').style.top=top_pos;
$("#login_button").click(function(){$("#login_box_pane").slideToggle(1200);});
$("#login_box_pane").focusout(function(){$("#login_box_pane").slideUp(1200);});
});
</script>


here is the html i am using.

<a id="login_button">login</a>
<div id="login_box_pane" >
Username: <input type="text"/>
Password:<input type="password"/>
</div>


Here is the CSS I am using:

#login_box_pane
{
display:none;
background-color:#FFBE7D;
z-index:50;
width:180px;
height:130px;
position:absolute;
}


The functionality I want is, whenever the "login" is clicked then there should appear a small box just below that asks for username and other details and it should disappear when ever the "login" is clicked again or anywhere else on the page, that is a focus out.... but it isn't working that way. I even tried mouseout and other events but tough luck. What's wrong with the code?

Is there any other way of achieving this?

Answer
$(document).click(function(e) {
  if(($(e.target).attr('id') == 'login_button')){
    $('#login_box_pane').slideToggle(1200);
  }
  else if(!($(e.target).parents('#login_box_pane').length>0)){
    $('#login_box_pane').slideUp(1200);
  }
});

This seems to address my problem correctly.

Comments