0

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!

3
  • Your code is working fine here jsfiddle.net/bortao/o16sacyL Commented Apr 29, 2020 at 20:05
  • Maybe you are using jquery ui selectable but with your code you just don't need it Commented Apr 29, 2020 at 20:07
  • 3
    jQuery is forbidden in 2020 and beyond! Commented Apr 29, 2020 at 20:25

1 Answer 1

1

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)
    }
  })
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.