John John - 6 months ago 90
HTML Question

CSS content:url() not working on anything other than chrome. Change the <img> src using JS?

I want to change the logo of my navbar on scroll using css. It already changes color on scroll using the

.affix
class provided by bootstrap.

<a href="#"><img class="limg" src="images/firstlogo.png" /></a>


Only way i found how to do this was:

#custom-nav.affix .limg{
content: url(../images/secondlogo.png);}


which works perfectly on chrome. However it doesnt work on Firefox / IE / Microsoft Edge.

There seems to be a solution using ::before and ::after prefixes but those didnt work for me.

It could be caused by the following JS code which implements the affix class on scroll.

$(window).scroll(function() {
if ($(".navbar").offset().top > 50) {
$('#custom-nav').addClass('affix');
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$('#custom-nav').removeClass('affix');
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});


If so, is there anyway i can change that
<img src"">
using JS when
affix
activates ?

Answer

Just change your image src attribute in scroll callback:

    var startImg = "images/firstlogo.png",
        scrollImg = "images/secondlogo.png",
        $img = $('.limg');

    $(window).scroll(function() {
        if ($(".navbar").offset().top > 50) {
            $('#custom-nav').addClass('affix');
            $(".navbar-fixed-top").addClass("top-nav-collapse");

            // Set scrolling src
            $img.attr('src', scrollImg);
        } else {
            $('#custom-nav').removeClass('affix');
            $(".navbar-fixed-top").removeClass("top-nav-collapse");

            // Set default image src
            $img.attr('src', startImg);
        }
    });

Example with timeout

As mentioned bellow, it may cause some performance problems because of many calls to DOM elements, so heres improved version with timeout and cached DOM vars:

var startImg = "images/firstlogo.png",
  scrollImg = "images/secondlogo.png",
  $navBar = $(".navbar"),
  $customNav = $('#custom-nav'),
  $navBar = $(".navbar-fixed-top"),
  $img = $('.limg'),

  timeout,

  $(window).on('scroll', function() {
    if (timeout) clearTimeout(timeout)
    // Use timeout to not call function immediately
    timeout = setTimeout(function() {
      if ($navBar.offset().top > 50) {
        $customNav.addClass('affix');
        $navBar.addClass("top-nav-collapse");

        // Set scrolling src
        $img.attr('src', scrollImg);
      } else {
        $customNav.removeClass('affix');
        $navBar.removeClass("top-nav-collapse");

        // Set default image src
        $img.attr('src', startImg);
      }
    }, 250)
  });
Comments