Toggle between two images

I have a navbar which has a transparant background when the site/a page opens. and transforms to a backround color when the next section reaches the top op the viewport:

var $window = $(window)
var $nav = $('nav')
var introTop = $('.services').offset().top

$window.scroll(function () {
  var scrollTop = $window.scrollTop()
  $nav.toggleClass('scrolled', scrollTop > introTop)
})

In the navbar i use a image for the navbar-brand:

<a class="navbar-brand" href="/">
    <img src="/img/logo_white.png" alt="logo" class="img-fluid">
</a>

This image should change to logo_grey.png at the same time that the background animation takes place. How would I do that?

Thank you in advance

Hi @donboe, I wouldn’t change the image itself as this would cause a new request each time the image gets toggled; instead, just toggle the visibility like so:

.logo-grey {
  display: none;
}

.scrolled .logo-white {
  display: none;
}

.scrolled .logo-grey {
  display: inline;
}
<a class="navbar-brand" href="/">
  <img src="/img/logo_white.png" alt="logo" class="img-fluid logo-white">
  <img src="/img/logo_grey.png" alt="logo" class="img-fluid logo-grey">
</a>
1 Like

Or, one could use image sprites. No call for anything, no retrieving anything, just swap areas of a single image.

Just a thot.

V/r,

^ _ ^

@m3g4p0p Thank you for the reply. Could that be something with a fadeIn? And how would that look like in JS? And how should I do that in combination with the above function (yours :slight_smile: )

As the .navbar-brand is inside the nav element, there are no JS adjustments necessary – you can use that .scrolled class to toggle other styles as well (and yes I recognised those lines). :-)

As for the fade effect, this can be achieved by absolutely positioning one image over the other and changing the opacity with a transition:

.navbar-brand {
  position: relative;
}

.logo-white,
.logo-grey {
  transition: opacity .2s ease;
}

.logo-white {
  opacity: 1;
}

.logo-grey {
  position: absolute;
  left: 0;
  opacity: 0
}

.scrolled .logo-white {
  opacity: 0;
}

.scrolled .logo-grey {
  opacity: 1
}

(This assumes both logos have the same size – otherwise you might need to position both absolutely and apply fixed dimensions to the container element.)

2 Likes

@m3g4p0p. Works great. :slight_smile: Thanx a lot

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.