I am quite new at jQuery (in fact, new to JS too) and I am trying to add a fade in effect to a JS function which I wrote to change images in a photo gallery when the "thumbnail" of another image is selected. Code is:
//For HTML - the "thumbs" area:
<img id="g1" class="thg" onclick="trocafoto(this.id)" src="fotos/sopa.jpg">
<img id="g2"class="thg" onclick="trocafoto(this.id)" src="fotos/salmao.jpg">//and so on
//The place where pictures are displayed:
<img class="portif" id="alvo" src="fotos/sopa.jpg">
//The JS Function itself:
function trocafoto(id) {
var x = document.getElementById(id).src ;
document.getElementById("alvo").src = x;
}
I'd like to add a jQuery Fade Out effect for the previous image displayed, and the Fade In for the last selected image once the function is fired. But I am not finding a way to mix the JQuery Code with the plain JS... How could I call only the jQuery function without need to target it to the same element again?
Thanks in advance for any help.
Try this:
var $alvo = $('#alvo');
$('.thg').on('click', function(){
var clickedImgSrc = $(this).attr('src');
// first hide alvo
$alvo.fadeOut( "slow", function() {
// fadeOut Animation is complete.
// Add the new src to alvo and fadeIn
$(this).attr('src', clickedImgSrc).fadeIn();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="g1" class="thg" src="fotos/sopa.jpg">
<img id="g2" class="thg" src="fotos/salmao.jpg">
<img class="portif" id="alvo" src="fotos/sopa.jpg">