I am attempting to do something that seems pretty simple, but I’m not sure if it as performant as it could be. I’m looking to cycle through a set of elements and toggle a class to only show a single item at a time, looping back to the first item at the end.
$ (document).ready(() => { const toggleButton = $ ('.btn-toggle'); toggleButton.on('click', function toggleButtonClick() { const currentItem = $ (this).parent('.itemtoggle') .find('li:not(.d-none)').toggleClass('d-none'); let nextItem = currentItem.next(); if (nextItem.length === 0) { nextItem = currentItem.parent('.items').find('li'); } nextItem.first().toggleClass('d-none'); }) .parent('.itemtoggle') .find('li') .toggleClass('d-none') .first() .toggleClass('d-none'); });
Full code example on Codepen
Right now it is written using jQuery. Is there a better way to do this, in jQuery, Vanilla JS, or other?