Reputation: 241
How do I get the jQuery listed below to animate properly?
var search = $('.searchField');
var searchButton = $('.searchSubmit');
search.on('focus', function() {
search.animate({
'right':'auto',
'left':'0'
}, 600);
searchButton.animate({
'right':'0',
'left':'auto'
}, 600);
});
search.on('focusout', function() {
search.animate({
'right':'0',
'left':'auto'
}, 600);
searchButton.animate({
'right':'auto',
'left':'0'
}, 600);
});
Ideally, I would like the searchButton
to go from left to right, on :focus
, switching places with search
. I am using animate in attempt to have the two elements "slide" into their new positioning, rather than having the elements jump from one side to the next.
Currently, the searchButton
doesn't go to the right on :focus
, and the search
element jumps to positioning left, rather than having a "slide" effect.
For the live jsFiddle, click here.
Upvotes: 2
Views: 90
Reputation: 1309
I actually believe @dfsq answer is better, to do it in CSS. But I wanted to fix the original code and to give other people using your question the choice of approach.
DEMO: JSFiddle
JS
var search = $('.searchField');
var searchButton = $('.searchSubmit');
var searchWidth = $('.searchField').innerWidth();
var searchButtonWidth = $('.searchSubmit').innerWidth();
var searchContainer = searchWidth + searchButtonWidth;
$('#search').css({ width: searchContainer });
search.on('focus', function() {
search.animate({
'right':'auto',
'left':'-10'
}, 400);
searchButton.animate({
'right':'0',
'left':'400'
}, 400);
});
search.on('focusout', function() {
search.animate({
'right':'0',
'left':'50'
}, 400);
searchButton.animate({
'right':'auto',
'left':'0'
}, 400);
});
searchButton.mouseover(function() {
$('.searchIcon').css('opacity', '0.5');
});
searchButton.mouseout(function() {
$('.searchIcon').css('opacity', '1');
});
search.bind('keypress', function(event) {
if (event.keyCode == 13) {
searchButton.click();
};
});
searchButton.click(function() {
search.val('');
});
Upvotes: 2
Reputation: 41
I used marginRight/marginLeft to animate them vs. using right/left positioning.
I like that you're using right/left positioning, but for this case, it's easier to use margin-left. If you use right/left positioning, you will also have to update your css.
Another option is to set a class with javascript and use css transitions for animating (like you did with the opacity).
search.on('focus', function() {
search.animate({
marginRight: "50"
}, 600);
searchButton.animate({
marginLeft: "450"
}, 600);
});
search.on('focusout', function() {
search.animate({
marginRight: "0"
}, 600);
searchButton.animate({
marginLeft: "0"
}, 600);
});
Upvotes: 2
Reputation: 193261
I think it makes sense to use simple CSS transition:
.searchField {
/* ... */
top: 0;
right: 0;
transition: all .6s ease;
&:focus {
/* ... */
right: 50px;
&+.searchSubmit {
left: 100%;
margin-left: -50px;
}
}
}
Also remove </input>
, input elements are self-closing tags: <input />
.
Upvotes: 3