Reputation: 679
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!
Upvotes: 0
Views: 48
Reputation:
html
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
js
const list = [];
const maxLen = 4
document.querySelectorAll('.item').forEach(el => {
const klass = 'selected';
el.addEventListener('click', e => {
const classes = el.classList;
classes.toggle(klass);
if (!classes.contains(klass)) {
// item is unselected
// remove item
list.splice(list.indexOf(el), 1);
} else {
if (list.length >= maxLen) {
// remove oldest item
const removed = list.shift();
removed.classList.remove(klass);
}
// add new item
list.push(el)
}
})
})
Upvotes: 1