patternjavascriptMinor
Slick Slider – change contents based on current slide data-index
Viewed 0 times
slidecontentssliderbasedcurrentindexslickdatachange
Problem
I wrote the following code for Slick Slider, which changes the content below based on the current slide data-index. I just wonder if there is a more efficient way to do it?
http://codepen.io/pjmtokyo/pen/JYyjew
http://codepen.io/pjmtokyo/pen/JYyjew
$('.slider').on('afterChange', function(event, slick, currentSlide, nextSlide){
var elSlide = $(slick.$slides[currentSlide]);
var dataIndex = elSlide.data('index');
$('.content').each(function(){
if ($(this).data('id') == dataIndex) {
$(this).show();
} else {
$(this).hide();
}
});
});Solution
I would combine the two lines where you get the
I also noticed that looking up
dataIndex, rename that to dataId to be consistent with the HTML element, and replace the loop by hiding everything, and then showing the correct element by finding it with a jQuery selector:$('.slider').on('afterChange', function(event, slick, currentSlide, nextSlide){
var dataId = $(slick.$slides[currentSlide]).data('index');
$('.content').hide();
$('.content[data-id=' + dataId + ']').show();
});I also noticed that looking up
dataId is superfluous, since it is simply the value of currentSlide plus one. So you could also make this change and retain the same behavior:$('.slider').on('afterChange', function(event, slick, currentSlide, nextSlide){
$('.content').hide();
$('.content[data-id=' + (currentSlide + 1) + ']').show();
});Code Snippets
$('.slider').on('afterChange', function(event, slick, currentSlide, nextSlide){
var dataId = $(slick.$slides[currentSlide]).data('index');
$('.content').hide();
$('.content[data-id=' + dataId + ']').show();
});$('.slider').on('afterChange', function(event, slick, currentSlide, nextSlide){
$('.content').hide();
$('.content[data-id=' + (currentSlide + 1) + ']').show();
});Context
StackExchange Code Review Q#107195, answer score: 9
Revisions (0)
No revisions yet.