java
java

Reputation: 35

Changing an image using jQuery

I cannot figure out why this image is not changing. I'll provide the relevant HTML, CSS, and jQuery below.

HTML

<nav id="desktop-nav">
  <div class="logo">
    <a href="#"></a>
  </div>
  <div> ... </div> 
  ...

CSS

nav#desktop-nav .logo a {
  display: block;
  width: 50px;
  height: 50px;
  background-image: url("../path/to/image-logo-white.png");
  background-size: 50px 50px;
}

jQuery

$(document).ready(function(){
  $(window).scroll(function(){
    if($(window).scrollTop() > $(window).height()) {
      $("nav#desktop-nav .logo a").attr("src", "../path/to/image-logo.png");
    }
})

NOTE: I have tested this function, and it does work (I changed the color of text):

$("#desktop-nav #main-nav .main-nav-center .main-nav-list li a").css({"color":"black"});

Help me out here, what am I doing wrong?

Upvotes: 1

Views: 48

Answers (1)

Vin&#237;cius Fagundes
Vin&#237;cius Fagundes

Reputation: 2041

a doesn't has src attribute. So it wont work:

 $("nav#desktop-nav .logo a").attr("src", "../path/to/image-logo.png");

To solve this, the fast way I see:

CSS

nav#desktop-nav .logo a {
  display: block;
  width: 50px;
  height: 50px;
  background-image: url("../path/to/image-logo-white.png");
  background-size: 50px 50px;
}

nav#desktop-nav .logo a.another-logo {
    /* OVERRING ANOTHER LOGO HERE*/
   background-image: url("../path/to/image-logo.png");
}

jQuery

$(document).ready(function(){
  $(window).scroll(function(){
    if($(window).scrollTop() > $(window).height()) {
      $("nav#desktop-nav .logo a").addClass('another-logo');
    }
    else {
       $("nav#desktop-nav .logo a").removeClass('another-logo');
    }
})

Upvotes: 1

Related Questions