Search code examples
jqueryfocusoutfocusin

Jquery toggle between focus


ok my piece of code looks sth like this:

<div id="left" style="float:left; width:100px; margin-right:10px;">
<input id="first" value="something">
</div>
<div id="right" style="margin-left:20px; float:left; width:200px;">
<input id="second" value="something">
<input id="third" value="something">
<input id="fourth" value="something">
</div>

jquery:

$(function() {

$("#right").focusin(function() {
      $( "#left" ).animate({
        width: "200px"
      }, 500 ); 
      $( "#right" ).animate({
        width: "100px"
      }, 500 );   
});
$("#right").focusout(function() {
      $("#left").animate({
        width: "100px"
      }, 500 ); 
      $("#right").animate({
        width: "200px"
      }, 500 ); 
});

})

but when im clicking between inputs on right div it calls focusin/out, how to prevent this?

DEMO: https://jsfiddle.net/swfzmdfd/


Solution

  • You can use a timer and not do the animation if the activeElement is one of the other inputs

    $(function() {
        $("#right").focusin(function(e) {
            $("#left").stop(true,true).animate({
                width: "200px"
            }, 500);
            $("#right").stop(true,true).animate({
                width: "100px"
            }, 500);
        });
        $("#right").focusout(function() {
        	setTimeout(function() {
            	if ( !($(document.activeElement).closest('#right').length && 
                       $(document.activeElement).is('input'))) {
                    $("#left").animate({
                        width: "100px"
                    }, 500);
                    $("#right").animate({
                        width: "200px"
                    }, 500);
                }
            },100);
        });
    
    })
    input {
        width: 100px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="left" style="float:left; width:100px; margin-right:10px;">
        <input id="first" value="something">
    </div>
    <div id="right" style="margin-left:20px; float:left; width:200px;">
        <input id="second" value="something">
        <input id="third" value="something">
        <input id="fourth" value="something">
    </div>