jQuery + html ID

Asked

Viewed 19 times

1

I have two images, I want them to change when:

  1. User hovers over it, implemented with CSS, works well.
  2. If the user does not mouse the img, when scrolling the page the img changes, I implemented a jquery and I am having difficulties because the code changes all the img of the page, and I want you to change a specific img.

In html:

<a href="#">
  <img src="assets/images/sujo.svg" class="defaultPic" alt="Carro Sujo">
  <img src="assets/images/limpo.svg" class="altPic" alt="Carro Limpo">
</a>

Scritpt I’m trying to use:

$(window).scroll(function () {
    //console.log($(document).scrollTop());
    if ($(document).scrollTop() >= 10) {
        $('img').attr('src', 'assets/images/limpo.svg');
    } else {
        $('img').attr('src', 'assets/images/sujo.svg');
    }
}); 
  • Know where you can find your error? in the attr selector, create an id for each <img> and add the id of the images in the selector, example: $('#imagem1'). attr('src', 'Assets/images/limpo.svg');

1 answer

1


Face caught by classe, since you are already using a class in the image you select for it and not for the tag img that picks up all the tags imgs

Notice that now the dial is picking by the class '.defaultPic' and not by the tag <img>

  $(window).scroll(function () {
      //console.log($(document).scrollTop());
      if ($(document).scrollTop() >= 10) {
          $('.defaultPic').attr('src', 'https://www.placecage.com/100/101');
      } else {
          $('.defaultPic').attr('src', 'https://www.placecage.com/100/100');
      }
  }); 
body {
  height: 150vh;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  
<a href="#">
  <img src="https://www.placecage.com/100/100" class="defaultPic" alt="Carro Sujo">
  <img src="https://www.placecage.com/105/100" class="altPic" alt="Carro Limpo">
</a>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.