Change picture when descending page

0

How do I change the image's SRC (with JQuery) when I scroll down the page and the scroll is greater than 10?

Change the

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

by

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

And then he comes back to

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

When the scroll is less than 10.

    
asked by anonymous 28.04.2017 / 13:43

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 seuElemento has to be replaced with the element you want to add the image, in case I suggest you put an id in your img and use the getElementById() method passing the id that has been assigned.

    
28.04.2017 / 13:58