Change "src" attribute with fadeIn effect

1

I need to change the src attribute of an image with jquery. Everything works perfectly, I only need to apply an effect that I can not put. I do not know if the way I did it is the exact way to get the result I want.

html

<img id="slide" src="img/img.png"/>
<a id="um">um</a>
<a id="dois">dois</a>
<a id="tres">três</a>

jquery

$("body").on("click","#um", function(){
    $("#slide").attr("src","img/1.png").fadeIn(2000);
})

$("body").on("click","#dois", function(){
    $("#slide").attr("src","img/2.png").fadeIn(2000);
})

$("body").on("click","#tres", function(){
    $("#slide").attr("src","img/3.png").fadeIn(2000);
})
    
asked by anonymous 15.12.2015 / 15:35

2 answers

1

FadeIn only works on hidden elements.

If the image is visible and you just change src and call fadeIn, there will be no effect.

To work correctly you need to make sure the image is hidden, and you can do this by entering hide () before fadeIn:

$("body").on("click","#um", function(){
    $("#slide").attr("src","img/1.png").hide().fadeIn(2000);
})
    
15.12.2015 / 16:17
2

Diego, I do not believe it's possible to make a transition effect for the 'src' property, the most that is possible is using a background-image.

var imagens = document.querySelectorAll("[data-img]");

[].forEach.call(imagens, function (imagem, indice) {
  var atual = 0;
  var lista = imagem.dataset.img.split(',').map(function (img) { return img.trim(); });
  imagem.classList.add(lista[atual]);
  imagem.addEventListener("click", function () {
    var proximo = atual + 1 < lista.length ? atual + 1 : 0;    
    imagem.classList.toggle(lista[atual]);
    imagem.classList.toggle(lista[proximo]);
    atual = proximo;
  });
})
[data-img] {
  background-size:     cover;
  background-position: center center;
  width: 256px;
  height: 256px;
  transition-property: 'background-image';
  transition-timing-function: linear;
  transition-duration: 1s;
  
  float: left;
  margin: 5px;
  border-radius: 5px;
  box-shadow: 0px 0px 10px black;
}

.img-verao {
  background-image: url('http://cdn.flaticon.com/png/256/63341.png');
}

.img-primavera {
  background-image: url('http://cdn.flaticon.com/png/256/70696.png');
}

.img-inverno {
  background-image: url('http://cdn.flaticon.com/png/256/63341.png');
}

.img-outono {
  background-image: url('http://cdn.flaticon.com/png/256/2130.png');
}
<div data-img="img-verao, img-primavera, img-inverno, img-outono"></div>
<div data-img="img-verao, img-primavera, img-inverno, img-outono"></div>
<div data-img="img-verao, img-primavera, img-inverno, img-outono"></div>
<div data-img="img-verao, img-primavera, img-inverno, img-outono"></div>
    
15.12.2015 / 16:33