开发者

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开发者_如何学JAVA 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?


Here is your answer:

$(document).click(function(e) {
    if($(e.target).attr('id') == 'login_button')
       $("#login_box_pane").slideToggle(1200);
    else
       $("#login_box_pane").slideUp(1200);
});

Note:

  1. e.target return the on which element the click event happen
  2. $(e.target).attr('id') == 'login_button' is checking the id of clicking element and if the id is login_button's, then 'login_box_pane' slideToggle happen else it will hide

Here is another code snippet:

$("#login_button").click(function(){ 
    $("#login_box_pane").slideToggle(1200).children('input:first').focus();// here I `foucs()` on first input box of the login panel
    return false;
});
$("#login_box_pane").focusout(function(){
    $("#login_box_pane").slideUp(1200);
});

Modified version of your code:

("#login_button").click(function(){ 
    $("#login_box_pane").slideToggle(1200,function(){
        $('input:first',this).focus();// Here I just make focus() on input that is your `#login_boz_pane`
    });
    return false;
});
$("#login_box_pane").focusout(function(e){
    $(this).slideUp(1200);
});


$(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜