Tadas Tadas - 5 months ago 7x
Javascript Question

Animating margin via jquery

So, I'm trying to make smooth nav bar animation when page is being resized.
This is how it should look like when page is 1500+px width and less then 1500px.

this is 1500px+ width

this is less then 1500px width

this is the jquery code I'm using to animate that transition:

$(window).on('resize', function(){
if($(this).width() <= 1500){
$('#visas').animate({'margin-left':'0%', 'margin-right':'0%'});
if($(this).width() >1500){
$('#visas').animate({'margin-left':'20%', 'margin-right':'20%'});

When I'm resizing page to less then 1500px animation happens sometimes, but when I'm trying to resize page to more then 1500px margin doesn't change.

mwl mwl

Instead of doing it in jQuery use CSS with transitions and media queries:

#visas {
  height: 50px;
  background: #bada55;
  margin: 0%;
  transition: margin .5s ease;

@media (min-width: 500px) {
  #visas {
    margin: 0 20%;

jsFiddle: https://jsfiddle.net/ukwybf9g/