Change attribute "src" with fadein effect

Asked

Viewed 206 times

1

I need to change the src attribute of an image with jquery. Everything works perfectly, I just need to apply an effect that I am not able to put. I don’t know if the way I did it’s 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);
})

2 answers

2

Diego, I do not believe it is possible to make a transition effect to the property 'src', 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>

1


Fadein only works on hidden elements.

If the image is visible and you just change src and call fadein, no effect will occur.

In order for it to work properly you need to make sure that the image is hidden, and you can achieve this by inserting the Hide() before fadein:

$("body").on("click","#um", function(){
    $("#slide").attr("src","img/1.png").hide().fadeIn(2000);
})
  • great! That’s what it was all about!

Browser other questions tagged

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