How to Create a Responsive jQuery Slider?

Estimated read time 2 min read

Here’s an example of how to create a Responsive jQuery Slider:

HTML code:

<!DOCTYPE html>
<html>
<head>
	<title>Responsive jQuery Slider</title>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<style>
		.slider {
			position:relative;
			width:100%;
			height:400px;
			overflow:hidden;
		}
		
		.slider img {
			position:absolute;
			top:0;
			left:0;
			width:100%;
			height:auto;
			opacity:0;
			transition:opacity 0.5s;
		}
		
		.slider img.active {
			opacity:1;
		}
		
		.slider-nav {
			position:absolute;
			bottom:20px;
			left:50%;
			transform:translateX(-50%);
			z-index:1;
		}
		
		.slider-nav button {
			display:inline-block;
			margin-right:10px;
			background-color:#eee;
			border:none;
			padding:10px 20px;
			color:#333;
			font-size:16px;
			cursor:pointer;
			transition:background-color 0.5s;
		}
		
		.slider-nav button.active {
			background-color:#333;
			color:#fff;
		}
		
		@media (max-width: 768px) {
			.slider {
				height:250px;
			}
			
			.slider-nav {
				bottom:10px;
			}
			
			.slider-nav button {
				padding:5px 10px;
				font-size:12px;
			}
		}
	</style>
</head>
<body>
	<div class="slider">
		<img src="image1.jpg" alt="Image 1" class="active">
		<img src="image2.jpg" alt="Image 2">
		<img src="image3.jpg" alt="Image 3">
		<img src="image4.jpg" alt="Image 4">
		<img src="image5.jpg" alt="Image 5">
		
		<div class="slider-nav">
			<button class="active">1</button>
			<button>2</button>
			<button>3</button>
			<button>4</button>
			<button>5</button>
		</div>
	</div>
	
	<script>
		$(document).ready(function(){
			var slideCount = $(".slider img").length;
			var currentIndex = 0;
			
			function showSlide(index){
				$(".slider img.active").removeClass("active").animate({opacity:0}, 500);
				$(".slider img").eq(index).addClass("active").animate({opacity:1}, 500);
				$(".slider-nav button.active").removeClass("active");
				$(".slider-nav button").eq(index).addClass("active");
			}
			
			$(".slider-nav button").click(function(){
				currentIndex = $(this).index();
				showSlide(currentIndex);
			});
			
			setInterval(function(){
				currentIndex++;
				if(currentIndex == slideCount){
					currentIndex = 0;
				}
				showSlide(currentIndex);
			}, 5000);
		});
	</script>
</body>
</html>

In this example, we have a div element with the class “slider” that contains five img elements. We also have a div element with the class “slider-nav” that contains five button elements to navigate between the slides.

We also have a script tag where we add our jQuery code. In

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply