JQuery css call function

I am trying to expand my search bar with jQuery. I also want to hide the navigation links.

I have jQuery code similar to this one. This code works great when focusing.

$(".searchBox input").focus(function(){ $("#navlinks").css('display','none'); $(this).css({'width':'200px','-moz-transition':'width 0.5s ease-out','-webkit-transition':'width 0.5s ease-out','transition':'width 0.5s ease-out'}); }); $(".searchBox input").focus(function(){ $(this).css({'width':'100px','-moz-transition':'width 0.5s ease-out','-webkit-transition':'width 0.5s ease-out','transition':'width 0.5s ease-out'}); $("#navlinks").css('display','block'); }); 

The second function also works fine except it display the content before animation complete.

So I want $("#navlinks").css('display','block'); was displayed only after the animation was completed.

Can anyone tell me how?

thanks

+4
source share
4 answers

Since you know how long your animation takes, why not use setTimeout () after changing the CSS? As far as I can see, your animation takes about 0.5 seconds. You can easily complete your “callback” at the end of your animation by specifying the same number of times in milliseconds.

  $(".searchBox input").focus(function(){ $(this).css({'width':'100px','-moz-transition':'width 0.5s ease-out','-webkit-transition':'width 0.5s ease-out','transition':'width 0.5s ease-out'}); setTimeout( function() { $("#navlinks").css('display','block'); }, 500); }); 
+7
source

.css () does not have a callback function, but .animate (). Just set the time to 0 and use the animation.

 $(".searchBox input").on('focus',function(){ $(this).animate({width:100,mozTransition:'width 500ms ease-out',webkitTransition:'width 500ms ease-out',transition:'width 500ms ease-out'},0,function(){ $("#navlinks") .delay(500) .css({display:'block'}); }); }); 

Edit: Enabled the delay that is required. (Thanks eicto)

+11
source

I would recommend using .animate() as

 $(".searchBox input").focus(function(){ $(this).animate({ 'width': '100px' }, 500, function() { $("#navlinks").css('display', 'block'); }); }); 

This will work in all browsers, and the navlinks command will be insured to start after the animation is complete. Note: 500 is the number of milliseconds that the animation takes so that you can adjust accordingly.

Here is the .animate() documentation: http://api.jquery.com/animate/

+1
source

transitionend described here , try the following:

CSS

 #test { width: 100px; border: 1px solid black; -webkit-transition: all 1s; -moz-transition all 1s; transition all 1s; } #test.wide { width: 200px; } 

JS:

 var test = $('#test'); test.bind('transitionend webkitTransitionEnd oTransitionEnd', function () { $('body').append('<div>END!</div>'); }) $('button').click(function () { test.toggleClass('wide'); }); 

Demo

-1
source

All Articles