Tadas
Tadas

Reputation: 95

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.

Upvotes: 0

Views: 47

Answers (2)

LOTUSMS
LOTUSMS

Reputation: 10280

You need to employ the use of media queries. Like this:

@media (max-width:1500px){
   .nav{
      width: 100%;
      margin:0 auto;
   }
}

In my demo I used 1200px as my breaking point to test it because my laptop doesn't go to far out past the 1500px, but you'll get the idea. Just change the 1200px breakpoint to 1500px.

p.s. Get familiar with Bootstrap. You can do these things much easier with the help of a responsive framework

See Demo HERE

Upvotes: 0

mwl
mwl

Reputation: 1488

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/

Upvotes: 1

Related Questions