Add a carousel to my page using TailwindCSS and Flowbite. I also added a toggle switch element that basically allows me to cycle between the two items in the carousel (checked = slide 2, unchecked = slide 1).
This works - where I got stuck was trying to set it to "Slide 2" on load based on the stored value of that toggle in localStorage.
I have verified that my localStorage values are being saved/retrieved correctly (as "yes" and "no" strings). I then tried setting the carousel to slide 1 ("no" value) or slide 2 ("yes" value) on load, but no matter what I tried, it always showed slide 1.
I tried the "slideTo()" and "next()" methods but neither seem to work (they work in the change event but not in my loading function).
No errors in the console. Like I said, the switch works fine after the page loads and cycles between slides correctly, it just doesn't set the correct slide when the page loads (so the slide displayed doesn't match the exact settings of the switch). p>
Flowbite carousel documentation: https://flowbite.com/docs/components/carousel/
This is my code:
window.addEventListener('load', function () { show_loader("service-suspended-container"); // Sidebar Toggle Defaults and Handler const exclude_suspended_toggle = document.getElementById('exclude-suspended-toggle'); // Determine which slide to display based on user's preference var starting_item = 0; if (('metrics-exclude-suspended' in localStorage) && localStorage.getItem('metrics-exclude-suspended') === 'yes') { starting_item = 1; } const carousel_items = [ { position: 0, el: document.getElementById('carousel-item-1') }, { position: 1, el: document.getElementById('carousel-item-2') } ]; const options = { defaultPosition: starting_item } // Carousel object for controlling slide var carousel = new Carousel(carousel_items, options); // Ecclude suspended toggle handler exclude_suspended_toggle.addEventListener('change', (event) => { console.log("Event fired"); if (event.currentTarget.checked) { // Make toggle checked console.log("Toggle now checked"); localStorage.setItem('metrics-exclude-suspended', 'yes'); carousel.slideTo(1); } else { // Uncheck toggle console.log("Toggle now unchecked"); localStorage.setItem('metrics-exclude-suspended', 'no'); carousel.slideTo(0); } }); // Determine default check state of toggle and slide from user's preferences if (('metrics-exclude-suspended' in localStorage) && localStorage.getItem('metrics-exclude-suspended') === 'yes') { console.log("enabled from storage..."); // Make toggle checked exclude_suspended_toggle.checked = true; carousel.slideTo(1); } else { console.log("disabled from storage..."); // Uncheck toggle exclude_suspended_toggle.checked = false; carousel.slideTo(0); } });
You are programmatically changing the selected property, which does not trigger the change event. Since the change event is not fired, the event listener is not called.
A way to trigger a change event:
So in your code it would become: