Unable to get all the sliders working

so basically, i want to make a page with multiple sliders. this code works for one slider but stops working if i have more than one. below is the html i have. I want to reuse the javascript at the bottom for all the sliders but every time i call a function that changes the current_class so i can reset the sliders (ie post2, post3) to just show the first picture, all the pictures for all the slides show. I was originally going to use an onclick function to see which slider the viewer was looking at so that the current_class could be changed accordingly.

	<div class = "slide">
		<img src="./1.jpg">
	</div> 
	<div class = "slide">
		<img src="./3.jpg">
	</div>

</div>

<br>


<div class = "post post2">
	<div class = "left_arrow"> </div>
	<div class = "right_arrow"></div>

	<div class = "slide">
		<img src="./1.jpg">
	</div> 
	<div class = "slide">
		<img src="./3.jpg">
	</div>

</div>

below is the javascript

    let current_class = 'post1';
	let slider_images = document.querySelectorAll('.' + current_class + ' .slide');
	let arrow_left = document.querySelector('.' + current_class + ' .left_arrow');
	let arrow_right = document.querySelector('.' + current_class + ' .right_arrow');
	let current = 0; // current slide

	function reset() {
		for(let i = 0; i < slider_images.length; i++) {
			slider_images[i].style.display = 'none';
		}
	}

	// initialization of the slide
	function start_slide() {
		reset();	
		slider_images[0].style.display = 'block';
	}

	// is called when the left arrow is clicked
	function slide_left() {
		reset();
		slider_images[current - 1].style.display = 'block';
		current--;
	}

	// is called when the right arrow is clicked
	function slide_right() {
		reset();
		slider_images[current + 1].style.display = 'block';
		current++;
	}

	arrow_left.addEventListener('click', function() {
		if (current === 0) {
			current = slider_images.length;
		}
		slide_left();
		
	});

	arrow_right.addEventListener('click', function() {
		if (current === slider_images.length - 1) {
			current = -1;
		}
		slide_right	();	
	});

	start_slide();

So, let’s think that through. What do you think you need to add to make the code flexible?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.