Question: 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 wich 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 funcion 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.

Answer: 
Try this:

```js
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();
  });

});
```

```html
<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">
```
If you're using **thumbnails** than probably you do have **higher resolution images** too.  

That's good for faster page loading! So in that case store the higher quality image path inside a `data-*` attribute like:

```js
var $alvo = $("#alvo"); // The larger target image

$(".thg").on("click", function(){
  // First, make sure the HQ image is loaded from the server
  var img = new Image();
  $(img).on("load", function(){
      // Than assign it to #alvo
      $alvo.hide().prop("src", img.src).fadeIn();
  });
  // getting the path from data attribute of the clicked thumbnail
  img.src = this.dataset.hq;
});
```

```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img class="thg" src="//placehold.it/60x60/cf5" data-hq="//placehold.it/400x200/cf5">
<img class="thg" src="//placehold.it/60x60/f5c" data-hq="//placehold.it/400x200/f5c">
<br>
<img id="alvo" src="//placehold.it/400x200/cf5">
```

If you don't want the loading image delay than you could preload in a loop all the HQ images, but that defies the purpose of faster page load. A remedy could be adding a loading spinner when a thumbnail is clicked.