Jquery toggle between focus

760 Views Asked by At

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/

2

There are 2 best solutions below

2
adeneo On BEST ANSWER

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>

1
Saa_keetin On

when you click on lets say third id after clicking on second id , basically both events get triggered, focusin in and focusout for elements under id right. that is why.

If you want to avoid that you can add click instead/

$("#right").click(function() {

// do this 
});
$("#left").click(function() {
 // do this 
});