There is a menu, there are control buttons next and prev. The idea is this: when you click on a menu item, a certain event is triggered (for example, filtering on the client) + the item itself becomes active. When you click on the next, the event is triggered on the element that immediately follows the active item and this next item becomes active.
When you click on the prev, the event is triggered on the element that is in front of the active item and this previous item becomes active. All this is fixated.

Example here, implementation on jquery: https://codepen.io/Ilinykh/pen/MPGBXK

The problem is as follows:

If you first select an item by clicking on it, and then start clicking on the buttons, then an out of sync occurs and the wrong item is triggered. The example should be clear, please help.

$(function(){ var $nav = $('.list'), $menuLink = $('.list').find('li a'), $currentItem = $menuLink.find('.active'), $prevBtn = $('.prev-btn'), $nextBtn = $('.next-btn'); $menuLink.on('click', function () { $menuLink.removeClass('active'); $(this).addClass('active'); }) $prevBtn.on('click', function (event) { event.preventDefault(); event.stopImmediatePropagation(); $nextBtn.removeClass('active'); $(this).addClass('active'); $currentItem = ($currentItem > 0) ? $currentItem - 1 : $menuLink.length - 1; $menuLink.eq($currentItem).addClass('active'); $menuLink.eq($currentItem).trigger('click'); }) $nextBtn.on('click', function (event) { event.preventDefault(); event.stopImmediatePropagation(); $prevBtn.removeClass('active'); $(this).addClass('active'); $currentItem = ($currentItem + 1 < $menuLink.length) ? $currentItem + 1 : 0; $menuLink.eq($currentItem).addClass('active'); $menuLink.eq($currentItem).trigger('click'); }) }); 
  • If the answer helped you, please accept it. - Axenow

1 answer 1

You just forget to update currentItem when you select something from the menu:

  $menuLink.on('click', function () { $menuLink.removeClass('active'); $(this).addClass('active'); $currentItem = $menuLink.index(this); // Вот этой строчки вам не хватало })