Chrish Chrish - 2 months ago 21
Javascript Question

Go to slide based on data attribute in Slick Slider

Some slides in my slick slider have data attributes such as this:

data-artwork="unique-id"
. What I'm trying to do is when you
hover
over a menu item it will
slickGoTo
a slide based on the data-attribute.

The menu items have matching data-attributes like this:

<ul class="project-feed">
<li data-artwork="unique-id">
<a href="#">Example</a>
</li>
</ul>


and I'm using Javascript to add those data-attributes to a variable, like so:

$('.project-feed li').hover(function() {
var artworkId = $(this).data('artwork'); // 'unique-id'
});


My question is how can I then use slick slider to go to the relative slide? Ex: If I hover over a menu item with
data-artwork="test"
then it will go to the slide with the same
data-artwork
value.

For extra credit: How can I then resume the slider from where it left off?

Answer

This works:

    var resumeIndex;
    $('.project-feed li').hover(function() {
        resumeIndex = $slider.slick("getSlick").currentSlide;
        var artworkId = $(this).data('artwork');
        var artIndex = $slider.find('[data-artwork="' + artworkId + '"]').data('slick-index');
        $slider.slick('slickPause').slick('slickGoTo', artIndex);
        console.log(resumeIndex);
    }, function() {
        $slider.slick('slickGoTo', 0).slick('slickPlay');
    });

But it's unpredictable. If you hover through the menu too quickly it behaves badly and gets confused.

Edit:

Adding a delay onto the hover (in) helped smooth out the functionality:

    var randomSlide;
    var timeout;

    $('.project-feed li').hover(function() {
        var artworkId = $(this).data('artwork');
        var artIndex = $slider.find('[data-artwork="' + artworkId + '"]').data('slick-index');
        var totalSlides = $('.slick-slide:not(.slick-cloned)').length;
        randomSlide = Math.floor((Math.random() * totalSlides) + 1);

        timeout = setTimeout(function() {
            $slider.slick('slickPause').slick('slickGoTo', artIndex);
        }, 500);

    }, function() {
        clearTimeout(timeout);
        $slider.slick('slickGoTo', randomSlide).slick('slickPlay');
    });
Comments