Swap image while scrolling down page

Asked

Viewed 513 times

0

How to change the image’s SRC (With Jquery) when scrolling down the page and the scroll is larger than 10?

Change the

<img src="imagem_1.png" alt="Meu site">

for

<img src="imagem_2.png" alt="Meu site">

And then he goes back to

<img src="imagem_1.png" alt="Meu site">

when the scroll is less than 10.

1 answer

3


With jquery

$(window).scroll(function () {
    //console.log($(document).scrollTop());
    if ($(document).scrollTop() >= 10) {
        $('img').attr('src', 'imagem_2.png');
    } else {
        $('img').attr('src', 'imagem_1.png');
    }
}); 

With JS pure

var onScrollHandler = function() {
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  if (scrollTop >= 10) {
     seuElemento.src = "imagem2.png"
  }else{
     seuElemento.src = "imagem1.png"
  }
};
object.addEventListener ("scroll", onScrollHandler);

*Note that with javascript the seuElemento has to be replaced by the element you want to add the image, in case I suggest you to put an id in your img and use the method getElementById() passing the id that was assigned.

Browser other questions tagged

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