Image Slider with Jquery

Asked

Viewed 915 times

2

I created a small image gallery using this structure:

<div class="slider">
<div class="dest">
    <img src="http://www.imagebrowse.com/wp-content/uploads/2013/08/astonishing-aristic-mobile-background-wallpaper-background.jpg" alt="suites-slider-dest">
</div>
<div class="navbar">
    <img src="http://www.imagebrowse.com/wp-content/uploads/2013/08/marvellous-water-drops-background-2013.jpg">
    <img src="http://www.imagebrowse.com/wp-content/uploads/2013/08/marvelous-beautiful-autum-tree-wallpaper-background.jpg">
</div>

With the CSS:

img
{
    max-width: 100%;
}

.slider
{
    display: inline-block;
    padding: 75px 0;
}

.dest img
{
    border: 5px solid #fff;
    box-shadow: rgba(0,0,0,0.5) 0 0 15px;
    float: left;
    margin-right: 15px;
    width: 70%;
}

.navbar
{
    float: left;
    margin-left: 10px;
    width: 17%;
}

.navbar img:first-child
{
    margin-top: 0 !important;
}

.navbar img
{
    border: 5px solid #fff;
    box-shadow: rgba(0,0,0,0.5) 0 0 15px;
    cursor: pointer;
    display: block;
    margin-top: 15px;
    opacity: 0.5;
}

.navbar img:hover
{
    opacity: 1;
}

And the Jquery:

$(".navbar img").click(function()
{
    var dest = $(".dest img").attr('src');
    var icon = $(this).attr('src');

    $(this).removeAttr('src');
    $(this).attr('src', dest);
    $(".dest img").removeAttr('src');
    $(".dest img").attr('src',icon);
});

The code is functional but I need the image transition inside the div with the "dest" class to be smooth. How can I do this?

Code

2 answers

2


Solution with Fadein effect / Fadeout

In order to give an effect to the image exchange, you need to make a small change to the CSS so that the image styles go to the element that surrounds it, because when you fade/fadeOut the image is no longer present during that effect and breaks the layout.

Example in Jsfiddle

CSS Modified

.dest {
    border: 5px solid #fff;
    box-shadow: rgba(0,0,0,0.5) 0 0 15px;
    float: left;
    margin-right: 15px;
    width: 70%;
}
.dest img{
    min-width:100%;
    float:left;
}

jQuery with use of the fadein() and fadeOut()

// pré-carregar imagens
var preloadImages = [];
$('.slider img').each(function() {
    preloadImages.push($(this).attr('src'));
});
$.each(preloadImages, function () {
    $('<img/>').attr('src', this);
});



// Evento click para trocar imagem
$(".navbar img").click(function() {

    var $mini  = $(this),
        $dest  = $(".dest img"),
        oldSrc = $dest.attr('src');

    // envolvemos o código da troca da imagem pelo método fadeout
    $dest.fadeOut( "slow", function() {
        $dest.on('load', function() {
            $dest.fadeIn("slow");  // acabamos tudo, apresentamos com fadeIn
        }).attr('src', $mini.attr('src'));
        $mini.attr('src', oldSrc);
    });
});

Note: See "Original Answer" for the rest of the code explanation.


Original Response

Using Javascript and jQuery my solution is to pre-load the slider images so that when they are changed from the thumbnail to the large image and vice versa there are no faults:

Example in Jsfiddle

Preload

// matriz vazia para guardar os caminhos das imagens
var preloadImages = [];

// por cada imagem encontrada dentro da estrutura do slider
$('.slider img').each(function() {

    // guardar o caminho na matriz
    preloadImages.push($(this).attr('src'));
});

// por cada entrada na matriz, carregar a imagem com novo objecto do DOM
$.each(preloadImages, function () {
    $('<img/>').attr('src', this);
});

Exchange images

Your code works, but I’m leaving a suggestion to optimize it:

// Evento click para trocar imagem
$(".navbar img").click(function() {

    var $this  = $(this),           // coloca em cache o elemento chave
        $dest  = $(".dest img"),    // coloca em cache o elemento dest
        oldSrc = $dest.attr('src'); // guarda a imagem antiga

    // anexa evento que espera pelo carregamento da imagem
    $dest.on('load', function() {

        // troca o caminho na tag "img" da miniatura,
        // para apontar para a  imagem que estava em ponto grande
        $this.attr('src', oldSrc);

    }).attr('src', $this.attr('src')); // troca a imagem grande pela miniatura
                                       // tem que ser feito após anexado o evento "load"
});
  • Still the transition is not smooth. How could it achieve this effect?

  • @Joãopaulosaragossa Work out what you mean by soft! Want a visual effect? Like Fade and appear softly?

  • Exactly, as if it were a fade out/fade in. I tried to incorporate these functions into the code but did not succeed.

  • Okay, I’ll change the answer, but I have to fix your HTML.

  • @Joãopaulosaragossa I updated the answer with a version containing the effects.

  • For some bizarre reason the effects are not happening when I integrate the code on my page, I suspect it must be something in CSS, which already counts 629 lines. Anyway your code is functional so I’ll flag the question as answered.

Show 1 more comment

0

You are changing the images by the attribute src tag <img />. I’ve used this type of technique but I recommend using another.

Display all the slider images on the page, so you won’t have any loading problems. Work with displays on images, for example, you can display all the elements on the page, the image in focus should always be with display: block, or display: inline-block, while the others are with display: none, so you don’t need to change the attribute src, but show and hide the images.

Regarding the smooth effect, you can make this scheme using the functions .fadeIn() and .fadeOut() jQuery.

Another tip: this type of slider exists in lots on the internet, follows the link of one I use when it does not require much particularity: http://bxslider.com/.

This slider is excellent. I noticed that you are using a thumbnail of the image as a slider pager, and Bxslider makes this possible, take a look at the documentation and options. It has some pretty cool effects and it’s not too heavy.

  • Thanks for the tip bxslider, although I want to do mine from scratch. If nothing works I will use it!

  • João, if you haven’t got the desired effect, try doing what I told you, load all the images in your html, and then work with the displays using jquery’s fadein() and fadeOut(), it’s very easy! Good luck there, man! ;D

  • Another thing, this system of working with the displays is much better, as you will not need to reload an image every transition.

  • This is one of the websites made by the agency where I work, I made this banner there, take a look, maybe help you: http://www.giftpalace.com.br/

Browser other questions tagged

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