I'm trying to limit the number of items a user can select to 4.
The items are all image/links, when the user clicks on an image it toggles the selected class and adds the element to an array of selected item values. If the user clicks on a 5th item it should drop the oldest item off the list. User should not be able to select the same item multiple times (filling the list with same item 4 times).
I believe it is the last part that is breaking my code (user can keep clicking on the same item and the array will get filled with the same selection 4 times.
var selectList = [];
$('.selectable').on('click', function () {
$(this).toggleClass('selected');
if ($(this).hasClass('selected')) {
selectList.push(this.dataset.fn);
} else {
var index = selectList.indexOf(this.dataset.fn);
if (index > -1) {selectList.splice(index, 1);}
}
if (selectList.length > 4) {
$('a[data-fn=' + selectList[0] + ']').removeClass('selected');
selectList.shift();
}
});
This breaks if i keep selecting the same image... Has to be an easier way!