Ian Caie
Ian Caie

Reputation: 33

Resizing logo when scrolling

I have used the following code to change the size of the logo when scrolling down the page.

$(document).on('scroll', function() {
  if ($(document).scrollTop() >= 10) {
    $('.logo img').css('width', '50px');
  } else {
    $('.logo img').css('width', '');
  }
});
.nav {
  position: fixed top: 0;
  z-index: 1;
  width: 100%;
}

.nav .logo {
  position: fixed;
  text-align: left;
  z-index: 2;
  top: 0;
  overflow: hidden;
  opacity: .5;
}

.container {
  padding-top: 120px;
  height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">
  <div class="logo">
    <a href="index.html"><img src="http://placehold.it/100x100" alt="" /></a>
  </div>
</div>
<div class="container">
  Lorem ipsum
</div>

I would like the transition to be smooth from large to small.

https://jsfiddle.net/sL89qxcx/

Is there something I can add to achieve a smooth transition?

Upvotes: 3

Views: 350

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The best way to achieve this would be to use CSS transitions, as they are hardware accelerated, and also a better separation of concerns. You can then toggle the animation by adding/removing a class in the JS.

The important part is to add both a width and transition rule to the default state of the .logo img element. You can then amend that width in the added class. Try this:

$(document).on('scroll', function() {
  $('.logo img').toggleClass('small', $(document).scrollTop() >= 10);
});
.nav {
  position: fixed top: 0;
  z-index: 1;
  width: 100%;
}

.nav .logo {
  position: fixed;
  text-align: left;
  z-index: 2;
  top: 0;
  overflow: hidden;
  opacity: .5;
}

.nav .logo img {
  width: 100px;
  transition: width 0.3s;
}

.nav .logo img.small {
  width: 50px;
}

.container {
  padding-top: 120px;
  height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">
  <div class="logo">
    <a href="index.html"><img src="http://placehold.it/100x100" alt="" /></a>
  </div>
</div>
<div class="container">
  Lorem ipsum
</div>

Upvotes: 4

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Some pointers for you:

Avoid setting styles using .css() as a general rule (exceptions apply, of course). Instead, consider defining a class in your CSS, eg. .small-logo {width:8%}, and use .addClass() instead.

This has the convenient side-effect that if the class is already added, it won't be added again.

In turn, this allows you to set transition: width 0.4 ease-in-out; or similar on your logo's styles. This will provide the smooth transition you're asking for.

CSS is fun!

Upvotes: 1

Related Questions