Creating an automatic carousel: JavaScript implementation guide
This article aims to help developers build an automatic carousel chart to solve the problem of manual switching and automatic playback. We'll provide complete HTML, CSS and JavaScript code examples and explain the implementation in detail to ensure that even JavaScript newbies can master it easily. The focus is on understanding how JavaScript controls the automatic switching and manual control logic of the carousel, and how to optimize CSS styles to achieve a smooth transition effect.
HTML structure
The HTML structure of the carousel mainly includes the following parts:
- Container slider-banners : Contains all elements of the entire carousel.
- Left and right arrow buttons slider-button_left and slider-button_right : used to switch pictures manually.
- Image container sliderbox : Contains all carousel images.
- Image element sliderbox_image : Each element contains an image.
- Indicator buttons slider-selectors_buttons : Used to indicate the currently displayed image and allow the user to jump directly to a specific image.
<div class="slider-banners"> <button class="slider-button_left" style="left: 30px;"><i class="fa-solid fa-angle-left" style="font-size: 30px; color: #ffffff;"></i></button> <div class="sliderbox"> <div class="sliderbox_image active"><img src="/static/imghw/default1.png" data-src="img/Slider/BannerStore1.jpg" class="lazy" alt="Creating an automatic carousel: JavaScript implementation guide" ></div> <div class="sliderbox_image"><img src="/static/imghw/default1.png" data-src="img/Slider/BannerStore2.jpg" class="lazy" alt="Creating an automatic carousel: JavaScript implementation guide" ></div> <div class="sliderbox_image"><img src="/static/imghw/default1.png" data-src="img/Slider/BannerStore3.jpg" class="lazy" alt="Creating an automatic carousel: JavaScript implementation guide" ></div> <div class="sliderbox_image"><img src="/static/imghw/default1.png" data-src="img/Slider/BannerStore4.jpg" class="lazy" alt="Creating an automatic carousel: JavaScript implementation guide" ></div> <div class="sliderbox_image"><img src="/static/imghw/default1.png" data-src="img/Slider/BannerStore5.jpg" class="lazy" alt="Creating an automatic carousel: JavaScript implementation guide" ></div> <div class="sliderbox_image"><img src="/static/imghw/default1.png" data-src="img/Slider/BannerStore6.jpg" class="lazy" alt="Creating an automatic carousel: JavaScript implementation guide" ></div> <div class="sliderbox_image"><img src="/static/imghw/default1.png" data-src="img/Slider/BannerStore7.jpg" class="lazy" alt="Creating an automatic carousel: JavaScript implementation guide" ></div> <div class="sliderbox_image"><img src="/static/imghw/default1.png" data-src="img/Slider/BannerStore8.jpg" class="lazy" alt="Creating an automatic carousel: JavaScript implementation guide" ></div> </div> <button class="slider-button_right" style="right: 30px;"><i class="fa-solid fa-angle-right" style="font-size: 30px; color: #ffffff;"></i></button> <ul class="slider-selectors_buttons"> <li class="active"> <li> <li> <li> <li> <li> <li> <li> </ul> </div> <script src="https://kit.fontawesome.com/6b2cfcf1a5.js" crossorigin="anonymous"></script>
CSS styles
CSS styles are mainly used to control the layout, appearance and animation effects of carousels. Here are some key CSS styles:
- .sliderbox: Set position: relative and overflow: hidden to ensure that the image is hidden when it exceeds the container.
- .sliderbox_image: Use position: absolute to stack all images together, and control the display and hiding of images through opacity.
- .sliderbox_image.active: Set opacity: 1 and position: relative to display the current image.
- .sliderbox_image.inactive: used to display the previous image (opacity: 1) when switching, and then remove this class through JavaScript.
- .slider-selectors_buttons: Layout and style for indicator buttons.
* { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: "Times New Roman", Times, serif; background-color: #4d4d4d; margin: 0; padding: 0; } .slider-banners { display: flex; justify-content: center; height: auto; width: 100%; position: relative; } .sliderbox { position: relative; height: 380px; width: 100%; text-align: center; overflow: hidden; } .sliderbox_image { position: absolute; display: flex; align-items: center; justify-content: center; height: auto; width: 100%; opacity: 0; } .sliderbox_image.inactive { opacity: 1; } .sliderbox_image.active { opacity: 1; position: relative; } .slider_image img { width: 100%; height: auto; text-align: center; } .slider-button_left, .slider-button_right { position: absolute; display: block; padding: 8px; background-color: #66323129; align-self: center; border: none; border-radius: 5px; transition: 0.4s ease; z-index: 1000; cursor: pointer; } .slider-button_left:hover, .slider-button_right:hover { background-color: #663231f0; transform: translateX(2px); padding: 10px; } .slider-selectors_buttons { display: flex; width: 100%; position: absolute; list-style: none; bottom: -30px; justify-content: space-evenly; } .slider-selectors_buttons li { width: 15px; height: 15px; border-radius: 50%; border: 1px solid black; } .slider-selectors_buttons li.active { background-color: black; } .dissable-s { width: 20px; height: 20px; border-radius: 50%; margin: 15px 5px; cursor: pointer; background-color: #66323129; border-color: #000000a0; } .dissable-s:hover { background-color: #663231f0; border-color: #000000cb; } .active-s { width: 20px; height: 20px; border-radius: 50%; margin: 15px 5px; cursor: pointer; background-color: #f47b3e; border-color: #000000cb; }
JavaScript implementation
The JavaScript code is responsible for realizing the automatic playback, manual switching and indicator button linkage of the carousel.
- Get DOM elements : First, get all the DOM elements that need to be operated, including containers, pictures, buttons and indicators.
- Initialization : Set the initial state, such as the currently displayed image index.
- Autoplay : Use the setTimeout function to switch pictures regularly.
- Manual switching : Add event listeners for the left and right arrow buttons to switch to the previous or next picture when clicked.
- Indicator Button : Add an event listener for each indicator button and switch to the corresponding image when clicked.
- Picture switching function playSlide(slide) : This function is the core and is responsible for updating the display state of the picture and the activation state of the indicator button.
let sliderBanners = document.querySelector(".slider-banners"), dots = document.querySelectorAll(".slider-selectors_buttons li"), sliderContent = document.querySelectorAll(".slider-banners .sliderbox_image"), leftArrow = document.querySelector(".slider-button_left"), rightArrow = document.querySelector(".slider-button_right"), sliderSpeed = 4500, currentSlide = 0, currentActive = 0, sliderTimer; window.onload = function() { function playSlide(slide) { for (let i = 0; i sliderContent.length - 1) { slide = currentSlide = 0; } if (currentActive != currentSlide) { sliderContent[currentActive].classList.add("inactive"); } sliderContent[slide].classList.add("active"); dots[slide].classList.add("active"); currentActive = currentSlide; clearTimeout(sliderTimer); sliderTimer = setTimeout(function() { playSlide((currentSlide = 1)); }, sliderSpeed); } leftArrow.addEventListener("click", () => { playSlide((currentSlide -= 1)); }); rightArrow.addEventListener("click", () => { playSlide((currentSlide = 1)); }); for (let j = 0; j { playSlide((currentSlide = dots.indexOf(this))); }); } playSlide(currentSlide); };
Things to note
- Image path : Make sure the image path is correct, otherwise the carousel will not be able to display the image.
- CSS styles : CSS styles are crucial to the appearance and animation of the carousel, so adjust as needed.
- JavaScript code : JavaScript code is the core of the carousel and needs to be carefully checked to see if the logic is correct.
- Performance optimization : If the carousel contains a large number of images, you can consider using techniques such as lazy loading of images to optimize performance.
Summarize
With this tutorial, you should be able to create a basic automatic carousel. You can further expand and optimize the functions and styles of the carousel according to your own needs. For example, you can add transition animations, customize indicator styles, support touch sliding, etc. Remember, understanding HTML structure, CSS styles, and JavaScript logic are the foundation for building any web application.
The above is the detailed content of Creating an automatic carousel: JavaScript implementation guide. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

This tutorial details how to use CSS to accurately hide specific text content in HTML pages to avoid the problem of the entire parent element being hidden due to improper selectors. By adding exclusive CSS classes to the wrapping elements of the target text and using the display: none; attribute, developers can achieve refined control of page elements, ensuring that only the required parts are hidden, thereby optimizing page layout and user experience.

Usemailto:inhreftocreateemaillinks.Startwithforbasiclinks,add?subject=and&body=forpre-filledcontent,andincludemultipleaddressesorcc=,bcc=foradvancedoptions.

This article explores two common problems when calling external JavaScript functions in HTML: improper script loading time causes DOM elements to be unready, and function naming may conflict with browser built-in events or keywords. The article provides detailed solutions, including tweaking script reference locations and following good function naming specifications to ensure JavaScript code is executed correctly.

UsethetitleattributeforsimpletooltipsorCSSforcustom-styledones.1.Addtitle="text"toanyelementfordefaulttooltips.2.Forstyledtooltips,wraptheelementinacontainer,use.tooltipand.tooltiptextclasseswithCSSpositioning,pseudo-elements,andvisibilityc

Setthelangattributeinthehtmltagtospecifypagelanguage,e.g.,forEnglish;2.UseISOcodeslike"es"forSpanishor"fr"forFrench;3.Includeregionalvariantswithcountrycodeslike"en-US"or"zh-CN";4.Applylangtospecificelementswhe

UseCSSfloatpropertytowraptextaroundanimage:floatleftfortextontheright,floatrightfortextontheleft,addmarginforspacing,andclearfloatstopreventlayoutissues.

This article explores the challenge of capturing mousedown events on parent divs containing cross-domain iframes. The core problem is that browser security policies (same-origin policy) prevent direct DOM event listening on cross-domain iframe content. This type of event capture cannot be achieved unless the iframe source domain name is controlled and CORS is configured. The article will explain these security mechanisms in detail and their limitations on event interactions and provide possible alternatives.

When using Bootstrap for web page layout, developers often encounter the problem of elements being displayed side by side rather than stacked vertically by default, especially when the parent container applies Flexbox layout. This article will explore this common layout challenge in depth and provide a solution: by adjusting the flex-direction attribute of the Flex container to column, using Bootstrap's flex-column tool class to achieve the correct vertical arrangement of H1 tags and content blocks such as forms, ensuring that the page structure meets expectations.
