How to make at the same section 3 texts and images horizontal slider by using gsap
Creating a horizontal slider with three texts and images using GSAP (GreenSock Animation Platform) can be achieved by utilizing GSAP's animation capabilities along with some HTML and CSS for layout. Below is a simple example to help you get started.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Horizontal Slider</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="slider-container">
<div class="slider">
<div class="slide">
<img src="image1.jpg" alt="Image 1">
<p>Text for Image 1</p>
</div>
<div class="slide">
<img src="image2.jpg" alt="Image 2">
<p>Text for Image 2</p>
</div>
<div class="slide">
<img src="image3.jpg" alt="Image 3">
<p>Text for Image 3</p>
</div>
</div>
</div>
<button id="prev">Previous</button>
<button id="next">Next</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/gsap.min.js"></script>
<script src="script.js"></script>
</body>
</html>body {
font-family: Arial, sans-serif;
}
.slider-container {
overflow: hidden;
width: 100%;
position: relative;
}
.slider {
display: flex;
transition: transform 0.5s ease;
}
.slide {
min-width: 100%; /* Each slide takes full width */
box-sizing: border-box;
text-align: center;
}
img {
max-width: 100%;
height: auto;
}const slides = document.querySelectorAll('.slide');
const slider = document.querySelector('.slider');
const prevButton = document.getElementById('prev');
const nextButton = document.getElementById('next');
let currentIndex = 0;
function updateSlider() {
const offset = -currentIndex * 100; // Move the slider based on the current index
gsap.to(slider, { x: `${offset}%`, duration: 0.5 });
}
nextButton.addEventListener('click', () => {
currentIndex = (currentIndex + 1) % slides.length; // Loop back to the first slide
updateSlider();
});
prevButton.addEventListener('click', () => {
currentIndex = (currentIndex - 1 + slides.length) % slides.length; // Loop to the last slide
updateSlider();
});-
HTML Structure: The HTML consists of a container for the slider and individual slides that contain an image and text.
-
CSS Styles: The CSS styles ensure that the slides are displayed in a horizontal row using
flexbox. Each slide takes up the full width of the container. -
JavaScript Logic: The JavaScript uses GSAP to animate the slider. When the "Next" or "Previous" buttons are clicked, the
currentIndexis updated, and the slider is moved accordingly using GSAP'stomethod.
- Make sure to replace
image1.jpg,image2.jpg, andimage3.jpgwith the actual paths to your images. - You can customize the styles and animations as needed to fit your design requirements.
- Ensure that GSAP is properly included in your project, either via CDN or by installing it through npm if you're using a build system.