Create Slider using jquery

Creating a slider using jQuery involves several steps, including setting up the HTML structure, styling with CSS, and adding the functionality with jQuery. Here’s a basic example to get you started:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Slider</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="slider">
<div class="slides">
<div class="slide">Slide 1</div>
<div class="slide">Slide 2</div>
<div class="slide">Slide 3</div>
</div>
<button class="prev">Previous</button>
<button class="next">Next</button>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</body>
</html>
/* style.css */
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}

.slider {
position: relative;
width: 300px;
overflow: hidden;
}

.slides {
display: flex;
transition: transform 0.5s ease-in-out;
}

.slide {
min-width: 100%;
box-sizing: border-box;
padding: 20px;
background-color: #fff;
border: 1px solid #ccc;
}

button.prev, button.next {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: rgba(0, 0, 0, 0.5);
color: white;
border: none;
padding: 10px;
cursor: pointer;
}

button.prev {
left: 10px;
}

button.next {
right: 10px;
}
// script.js
$(document).ready(function() {
let currentSlide = 0;
const slides = $('.slide');
const totalSlides = slides.length;

function showSlide(index) {
if (index < 0) {
currentSlide = totalSlides - 1;
} else if (index >= totalSlides) {
currentSlide = 0;
} else {
currentSlide = index;
}
const newLeft = -currentSlide * 100 + '%';
$('.slides').css('transform', 'translateX(' + newLeft + ')');
}

$('.next').click(function() {
showSlide(currentSlide + 1);
});

$('.prev').click(function() {
showSlide(currentSlide - 1);
});

showSlide(currentSlide);
});

 

 

 

 

Leave a Reply