Table of Contents
Key steps to achieve sliding effect
1. CSS animation definition
2. JavaScript code implementation
3. HTML structure
4. Complete example
Summarize
Home Web Front-end HTML Tutorial Add sliding effects to your HTML/JavaScript slideshows

Add sliding effects to your HTML/JavaScript slideshows

Oct 10, 2025 pm 10:36 PM

Add sliding effects to your HTML/JavaScript slideshows

This article will guide you on how to add slide in and slide out effects using HTML, CSS, and JavaScript. By dynamically switching CSS classes, we can control the animation of the slide so that it slides in smoothly when displayed and exits smoothly when switched, thus improving the user experience. This article will provide detailed code examples and steps to help you easily achieve this effect.

Key steps to achieve sliding effect

The core of realizing the sliding effect of slides is to use CSS animation properties and JavaScript to dynamically add and remove CSS classes. Here are the detailed steps:

1. CSS animation definition

First, you need to define the slide-in and slide-out animations in CSS. Here is an example:

 .slide-in {
  animation: slide-in 0.5s forwards; /* animation duration 0.5 seconds, maintain the final state after the end */
}

.slide-out {
  animation: slide-out 0.5s forwards; /* animation duration 0.5 seconds, maintain the final state after it ends */
}

@keyframes slide-in {
  from {
    transform: translateX(100%); /* Slide in from the right*/
    opacity: 0; /* Initial transparency is 0 */
  }
  to {
    transform: translateX(0%); /* final position*/
    opacity: 1; /* final transparency is 1 */
  }
}

@keyframes slide-out {
  from {
    transform: translateX(0%); /* initial position*/
    opacity: 1; /* Initial transparency is 1 */
  }
  to {
    transform: translateX(-100%); /* Slide out to the left*/
    opacity: 0; /* final transparency is 0 */
  }
}

This CSS code defines two animations: slide-in and slide-out. The slide-in animation slides an element from the right side of the screen to its normal position, while simultaneously changing it from transparent to opaque. The slide-out animation slides the element from its normal position to the left side of the screen and makes it transparent. The forwards keyword ensures that the element retains the final state of the animation after the animation ends.

2. JavaScript code implementation

Next, you need to use JavaScript code to control the switching of the slides, and add and remove the corresponding CSS classes when switching. Here is an example:

 function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");

  if (n > slides. length) {
    slideIndex = 1;
  }
  if (n <p> This JavaScript code first fetches all slide elements. It then finds the currently displayed slide (slideToHide) and the upcoming slide (slideToShow). For the slide that needs to be hidden, it adds the slide-out class and listens to the animationend event to hide the element after the animation ends. For the slide to be displayed, it adds the slide-in class and displays it.</p><p> <strong>Key points:</strong></p>
  • animationend event: Use the animationend event to ensure that the element is hidden only after the slide-out animation is completed to avoid the abrupt feeling of the element disappearing when the animation is not completed.
  • Class removal: Before adding new classes, make sure to remove old classes to prevent style conflicts.
  • Event listener removal: Remove the event listener in the animationend event handler to prevent the event from being triggered repeatedly.

3. HTML structure

The HTML structure needs to contain a slide element with the mySlides class, and a container element to wrap all slides. For example:

 <div class="slideshow-container">
  <div class="mySlides">
    <img src="/static/imghw/default1.png" data-src="image1.jpg" class="lazy" alt="Image 1">
  </div>
  <div class="mySlides">
    <img src="/static/imghw/default1.png" data-src="image2.jpg" class="lazy" alt="Image 2">
  </div>
  <div class="mySlides">
    <img src="/static/imghw/default1.png" data-src="image3.jpg" class="lazy" alt="Image 3">
  </div>
</div>

4. Complete example

By combining the above CSS, JavaScript and HTML code, you can create a slideshow with a sliding effect. Here's a complete example:

 


  <title>Slideshow with sliding effect</title>
  <style>
    /* CSS code*/
    .slide-in {
      animation: slide-in 0.5s forwards;
    }

    .slide-out {
      animation: slide-out 0.5s forwards;
    }

    @keyframes slide-in {
      from {
        transform: translateX(100%);
        opacity: 0;
      }
      to {
        transform: translateX(0%);
        opacity: 1;
      }
    }

    @keyframes slide-out {
      from {
        transform: translateX(0%);
        opacity: 1;
      }
      to {
        transform: translateX(-100%);
        opacity: 0;
      }
    }

    .mySlides {
      display: none; /*Hide all slides in initial state*/
    }

    .slideshow-container {
      position: relative;
      width: 500px;
      height: 300px;
      overflow: hidden; /* Make sure the animation is displayed within the container*/
    }

    .slideshow-container img {
      width: 100%;
      height: 100%;
      object-fit: cover; /* Make sure the image fills the entire container*/
    }
  </style>



  <div class="slideshow-container">
    <div class="mySlides">
      <img src="https://via.placeholder.com/500x300/FF0000/FFFFFF?text=Image%201" alt="Image 1">
    </div>
    <div class="mySlides">
      <img src="https://via.placeholder.com/500x300/00FF00/FFFFFF?text=Image%202" alt="Image 2">
    </div>
    <div class="mySlides">
      <img src="https://via.placeholder.com/500x300/0000FF/FFFFFF?text=Image%203" alt="Image 3">
    </div>
  </div>

  <script>
    // JavaScript code var slideIndex = 0;

    function plusSlides(n) {
        showSlides(slideIndex = n);
    }

    function currentSlide(n) {
        showSlides(slideIndex = n);
    }

    function showSlides(n) {
      var i;
      var slides = document.getElementsByClassName("mySlides");

      if (n > slides. length) {
        slideIndex = 1;
      }
      if (n < 1) {
        slideIndex = slides.length;
      }

      // Find the currently displayed slide and the slide that will be displayed soon var slideToShow = slides[slideIndex - 1];
      var slideToHide = null;
      for (i = 0; i < slides.length; i ) {
        if (slides[i].style.display === "block") {
          slideToHide = slides[i];
          break;
        }
      }

      // If there are slides that need to be hidden, add the slide-out class if (slideToHide) {
        slideToHide.classList.add("slide-out");
        slideToHide.classList.remove("slide-in"); // Make sure to remove the slide-in class // Hide the element after the animation ends slideToHide.addEventListener("animationend", function() {
          slideToHide.style.display = "none";
          slideToHide.removeEventListener("animationend", arguments.callee); // Remove the event listener to prevent repeated triggering});
      } else if(slideToShow){ //If there is no currently displayed slide, directly display the next slideToShow.style.display = "block";
      }

      //Show new slide and add slide-in class if (slideToShow) {
        slideToShow.classList.add("slide-in");
        slideToShow.classList.remove("slide-out"); // Make sure to remove the slide-out class slideToShow.style.display = "block";
      }
    }

    // Automatically play the slideshow setInterval(function() {
      plusSlides(1);
    }, 3000); // Switch slides every 3 seconds // Initialize to display the first slide showSlides(1);
  </script>


Things to note:

  • Be sure to replace the image links in the sample code with your own.
  • The duration and easing function of the CSS animation can be adjusted as needed to get the best visual effect.
  • For a better user experience, you can add previous and next buttons to allow users to switch slides manually.

Summarize

Through the introduction of this article, you have mastered how to use HTML, CSS and JavaScript to add sliding effects to slides. This effect can significantly improve the user experience and make the slideshow more lively and interesting. Hope this article is helpful to you!

The above is the detailed content of Add sliding effects to your HTML/JavaScript slideshows. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

CSS tips: precisely hide specific text content without affecting parent elements CSS tips: precisely hide specific text content without affecting parent elements Sep 16, 2025 pm 10:54 PM

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.

How to create a hyperlink to an email address in html? How to create a hyperlink to an email address in html? Sep 16, 2025 am 02:24 AM

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

Capture mousedown events with parent element containing cross-domain iframes: Principles and limitations Capture mousedown events with parent element containing cross-domain iframes: Principles and limitations Sep 20, 2025 pm 11:00 PM

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.

JavaScript external function call difficulty analysis: script location and naming specification JavaScript external function call difficulty analysis: script location and naming specification Sep 20, 2025 pm 10:09 PM

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.

How to add a tooltip on hover in html? How to add a tooltip on hover in html? Sep 18, 2025 am 01:16 AM

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

How to make text wrap around an image in html? How to make text wrap around an image in html? Sep 21, 2025 am 04:02 AM

UseCSSfloatpropertytowraptextaroundanimage:floatleftfortextontheright,floatrightfortextontheleft,addmarginforspacing,andclearfloatstopreventlayoutissues.

How to set the lang attribute in HTML How to set the lang attribute in HTML Sep 21, 2025 am 02:34 AM

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

Implement vertical stacking of elements in Bootstrap Flexbox layout: from side to layer Implement vertical stacking of elements in Bootstrap Flexbox layout: from side to layer Sep 21, 2025 pm 10:42 PM

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.

See all articles