jQuery - :focus Triggering When Switching Windows/Tabs

295 views Asked by At

I am attempting to have a search bar that upon :focus, an animation is triggered within itself. The animation is being called within the jQuery.

For better clarification, the search bar can accessed by clicking here.

The issue I am having, is caused when clicking off the browser or into a different browser tab. If the search bar is selected(:focus), then the animation is triggered again and causes the search bar (and it's positioning) to become thrown off from it's original placement. This also occurs if you were to right click on the search bar for any reason.

A portion of the jQuery:

var search = $('.searchField');
var searchButton = $('.searchSubmit');
var searchWidth = $('.searchField').innerWidth();
var searchButtonWidth = $('.searchSubmit').innerWidth();

search.on('focus', function() {
    search.animate({ right: '+='+searchButtonWidth }, 800);
    searchButton.animate({ left: '+='+searchWidth }, 800);
});
search.on('focusout', function() {
    search.animate({ right: '-='+searchButtonWidth }, 800);
    searchButton.animate({ left: '-='+searchWidth }, 800);
});
1

There are 1 answers

1
Walter On BEST ANSWER

It seems as if there is a conflict between jQuery animate and the css transitions. If you remove all the transition tags in the css it works as expected. You could use absolute values instead of relative += or -= offsets:

search.on('focus', function() {
    search.animate({ left: 0 }, 800);
    searchButton.animate({ left: searchWidth }, 800);  
}).on('focusout', function() {
    search.animate({ left: searchButtonWidth }, 800);
    searchButton.animate({ left: 0 }, 800);
});

You would need to set the parent element style to position: relative;

You could also try this plugin: http://playground.benbarnett.net/jquery-animate-enhanced/