I'm using jquery 1.8.2, have 2 input fields and would like a way to detect whether each one has focus, or neither have focus.
Any help would be greatly appreciated, thanks.
Edit:
I've updated the jsfiddle to be closer to what I want so there isn't confusion. The problem here is I have 2 input fields which are tied together. I want to grow one and shrink the other when the one is focused, and I want to reset both to their original widths if neither is focused. I could get heavy handed with some global variables that update on focus and keep track of whether both are in or out of focus but I wanted to see if a jquery solution existed first. Here is the updated jsfiddle with a button to toggle the reset animation so you can see how it hops at the moment:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<input class="searchy-search input1" />
<input class="searchy-search input2" />
<p>who has focus?</p>
<div class="focus-who jquery-focus"></div>
<button class="out-focus">toggle focus out</button>
$(document).ready(function() {
$('.focus-who').html('init');
$('.input1').val('some long string of text');
$('.input2').val('some long string of text');
$('.searchy-search').focusin(function() {
var $shrinkSelector;
if($(this).hasClass('input1')) {
$shrinkSelector = $('.input2');
} else if($(this).hasClass('input2')) {
$shrinkSelector = $('.input1');
}
var initWidth = 100;
var inputVal = $(this).val();
var inputLength = inputVal.length;
if(inputLength > 16) {
var offset = ((inputLength - 16) * 6);
var growWidth = initWidth + offset;
var shrinkWidth = initWidth - offset;
var aniTime = 200;
$(this).animate({width: growWidth + 'px'}, aniTime);
$shrinkSelector.animate({width: shrinkWidth + 'px'}, aniTime);
}
});
var outFocus = false;
$('.out-focus').click(function() {
outFocus = !outFocus;
});
$('.searchy-search').focusout(function() {
if(outFocus) {
$('.searchy-search').animate({width: '130px'}, 200);
}
});
});
another edit:
looks like this might just be my best option. If anyone has any other ideas that would be great, but for now I think I'll just have to go with this.
Detect which form input has focus using JavaScript or jQuery