I am applying a series of list-items a background-image from an array of images.
I have created an array of images 'artifacts' :
var artifacts = [
'/img/artifacts/artifact-1.svg',
'/img/artifacts/artifact-2.svg',
'/img/artifacts/artifact-3.svg',
'/img/artifacts/artifact-4.svg',
'/img/artifacts/artifact-5.svg',
'/img/artifacts/artifact-6.svg',
'/img/artifacts/artifact-7.svg'
];
HTML markup looks like this.
<ul class="slick-dots">
<li>1</li>
<li>2</li>
<li class="slick-active">3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
There is a 'selected' set of images for the hover/selected colour.
var artifactHover = [
'/img/artifacts/artifact-1-hover.svg',
'/img/artifacts/artifact-2-hover.svg',
'/img/artifacts/artifact-3-hover.svg',
'/img/artifacts/artifact-4-hover.svg',
'/img/artifacts/artifact-5-hover.svg',
'/img/artifacts/artifact-6-hover.svg',
'/img/artifacts/artifact-7-hover.svg'
];
And here is my JavaScript this far:
$('.slick-dots li').css('background-image', function(i) {
return 'url("' + artifacts[i % artifacts.length] + '")';
});
$('.slick-dots .slick-active').css('background-image', function(i) {
return 'url("' + artifactHover[i % artifactHover.length] + '")';
});
$('.slick-dots li button').click(function() {
$('.slick-dots li').css('background-image', function(i) {
return 'url("' + artifacts[i % artifacts.length] + '")';
});
var index = $(this).parent().index();
$(this).parent().css('background-image', function(i) {
return 'url("' + artifactHover[index] + '")';
});
});
So when user clicks a list item, it pulls the appropriate image from the array based off the element that was clicked.
If there are more list-items than there are images then it will just start over and start from the beginning again. My issue is matching the current selected list-item with the appropriate hover image. By using the index() for the artifact-hover, if I select a list item that is larger than the amount in the array of images it places a blank image in instead of restarting from the beginning of list.
artifactHover[index%artifactHover.length]?2 % 3 = 2or7 % 3 = 1.7 / 3 = 2but we have 1 remaining.%is used to get the remainder after integer division.Suppose you have 5 images, and 7lielements. For firstli->first image, secondli-> second image,...for5thli->5thimage, for6thimage it will be ->6%5which equals to1. So for6th'li' -> first image, and7th liwill be7%5image which means2. Hope this helps.