Creating a seamless transition effect while toggling classes in CSS and JS

I am looking to create a slideshow that features images with text overlay, and I want to implement next and previous buttons for image navigation. However, I am having trouble getting the opacity transition to work when switching between images by toggling classes. Everything else in the slideshow is functioning correctly, but the transition effect remains elusive. Any help or suggestions would be greatly appreciated! ^^

Below is my current code:

    <section class="featured container section">
        <div class="featured__slides">
          <div class="featured__active featured__item">
            <img class="featured__img" src="/featured/f1.jpg">
          </div>
          <div class="featured__unactive featured__item">
            <img class="featured__img" src="/featured/f2.jpg">
          </div>
        </div>
        
        <div class="featured__arrows">
          <button class="featured__arrow featured__prev">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
              <path fill-rule="evenodd" d="M7.72 12.53a.75.75 0 010-1.06l7.5-7.5a.75.75 0 111.06 1.06L9.31 12l6.97 6.97a.75.75 0 11-1.06 1.06l-7.5-7.5z" clip-rule="evenodd" />
            </svg>          
          </button>

          <button class="featured__arrow featured__next">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
              <path fill-rule="evenodd" d="M16.28 11.47a.75.75 0 010 1.06l-7.5 7.5a.75.75 0 01-1.06-1.06L14.69 12 7.72 5.03a.75.75 0 011.06-1.06l7.5 7.5z" clip-rule="evenodd" />
            </svg>                    
          </button>
        </div>
    </section>
    <style>
    .featured {
        flex-direction: column;
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden;
    
        position: relative;
    }
    
    .featured__item {
        display: none;
        -webkit-transition: all .3s linear 0s;
        transition: all .3s linear 0s;
        opacity: 0;
    }
    
    .featured__active {
        display: block;
        opacity: 1;
    }
    
    .featured__arrows {
        display: flex;
        justify-content: space-between;
        position: absolute;
        left: 0;
        right: 0;
        margin-left: 0.5rem;
        margin-right: 0.5rem;
    }
    
    .featured__arrow {
        height: var(--size-lg);
        width: var(--size-lg);
        color: var(--clr-cyan400);
    }
    </style>
    <script>
    const nextArrow = document.getElementsByClassName("featured__next");
    const prevArrow = document.getElementsByClassName("featured__prev");
    
    var idx = 0;
    var slides = document.getElementsByClassName("featured__slides");
    var slideshowElements = $(slides).children();
    
    $(nextArrow).click(function () { 
        slideshowElements[idx].classList.toggle("featured__active");
        slideshowElements[idx].classList.toggle("featured__unactive");
        if (slideshowElements.length - 1 == idx)
        {
            idx = 0;
        } 
        else
        {
            idx++;
        }
        slideshowElements[idx].classList.toggle("featured__active");
        slideshowElements[idx].classList.toggle("featured__unactive");
    });
    
    $(prevArrow).click(function () { 
        slideshowElements[idx].classList.toggle("featured__active");
        slideshowElements[idx].classList.toggle("featured__unactive");
        if (idx == 0)
        {
            idx = slideshowElements.length - 1;
        } 
        else
        {
            idx--;
        }
        slideshowElements[idx].classList.toggle("featured__active");
        slideshowElements[idx].classList.toggle("featured__unactive");
    });
    </script>

I have also attempted applying the transition effect to the "featured__img" class without success.

Answer №1

It appears that a crucial aspect is missing from your CSS to enable the opacity transition when toggling classes. Let's modify your CSS and JavaScript code to achieve the desired outcome.

To begin, update your CSS classes to incorporate the opacity property:

.featured__item {
  -webkit-transition: all .3s linear 0s;
  transition: all .3s linear 0s;
  opacity: 0; /* Include this line */
}

.featured__item.active {
  opacity: 1; /* Include this line */
}

Your JavaScript code seems fine, but you can streamline it by creating a function to manage the slideshow update logic. Below is the revised version of your JavaScript code:

const nextArrow = $(".featured__next");
const prevArrow = $(".featured__prev");

let idx = 0;
const slides = $(".featured__slides");
const slideshowElements = slides.children();

function updateSlideshow(newIndex) {
  slideshowElements.eq(idx).toggleClass("featured__active");
  slideshowElements.eq(newIndex).toggleClass("featured__active");
  idx = newIndex;
}

nextArrow.click(function () {
  const newIndex = (idx + 1) % slideshowElements.length;
  updateSlideshow(newIndex);
});

prevArrow.click(function () {
  const newIndex = (idx - 1 + slideshowElements.length) % slideshowElements.length;
  updateSlideshow(newIndex);
});

// Set the initial item as active
slideshowElements.eq(idx).toggleClass("featured__active");

For a slightly different approach, you can view a working example at codesandbox.io/s/little-morning-git4i7

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modifying the $scope property on ng-click and redirecting with ui-sref

I am completely baffled by this situation. Here is the current status: https://i.sstatic.net/PJdb6.png Upon reaching this page, the following appears in the console: https://i.sstatic.net/aIJqd.png When I click on "lorem2", which has an ng-click funct ...

Quadruple Equidistant Table Containers

I am struggling to achieve the desired outcome of having four evenly spaced <table> cells on my webpage. Despite setting specific widths for each cell, I am facing some challenges. Below is an example where one of the cells appears larger than the r ...

Despite waiting for all promises to resolve, why is the final console.log not displaying the complete data?

Edit Why is my final console.log not triggering after everything is resolved, even with the then statements in place? I'm experiencing a strange bug where the expected structure is not being printed. Despite adding several console.log statements, I ...

Using Typescript to collapse the Bootstrap navbar through programming

I've managed to make Bootstrap's navbar collapse successfully using the data-toggle and data-target attributes on each li element. If you're interested, here is a SO answer that explains a way to achieve this without modifying every single ...

It appears that Apexcharts is not compatible with React/Next.js

Issue Encountering a crash in my Next.js/React/Node application whenever I utilize import Chart from "react-apexcharts" in any file. Upon attempting to access the app, an error message is displayed: Server Error ReferenceError: window is not ...

What is the correct way to end this jQuery statement?

I've been working on this for about 6 hours now. I ran it through multiple Lint tools and various other online tests, but I just can't seem to get the statement below to close properly. There's a persistent error showing up on the last line ...

Achieving a full-width navigation element allows for other elements to be positioned below it, rather than directly beside it

Apologies for my not-so-great English. To better understand my issue, please refer to this fiddle and this fiddle. Focus on the <nav></nav> section. If there are only a few elements in the menu, the next block <section></section> ...

What is the best way to transform Adobe XD designs into HTML and CSS with Vue.js?

I am looking to create a single page application with vue.js and came across this helpful reference at . A colleague has created a prototype using Adobe XD, and now my task is to transform it into HTML/CSS while making it functional and connecting it to an ...

Troubles arise when utilizing getChannelData to configure socket.io in web audio,

I'm facing a problem where my connection gets disconnected as soon as I execute the code source.buffer.getChannelData(0).set(audio);. This issue occurs when I transcode an audio file and send the audio buffer to the client using socket.io for playback ...

Submitting a Form with Ajax and JQuery in .NET

Thanks to the help of balexandre and rtiq, I have successfully figured out the flow. My .ashx file is being called, indicating that a portion of the code is functioning correctly, although an error is being alerted. However, when I trace the .NET, the vari ...

Formulate a Generic Type using an Enum

I'm currently working on a project that involves creating a generic Type using enums. Enum export enum OverviewSections { ALL = 'all', SCORE = 'score_breakdown', PERFORMANCE = 'performance_over_time', ENGAGEMENT ...

Setting up additional requirements in a subfolder within play.js

Seeking assistance with an issue in play.js on Sandbox. Attempting to install a dependency but my package.json is not located in the root folder; it's stored within a folder named frontend. How can I install them when the package.json is inside that f ...

Module child-process not found

Why is it that when I try to run "require('child-process')" in the node shell, I receive an error saying "Cannot find module 'child-process'"? It seems like "child-process" should be a default library in Node. Any insights on what could ...

Utilizing Mustache templates to extract JSON data from Contentful

I am attempting to retrieve data from Contentful (in JSON format) and populate it into a Mustache template. The code below successfully retrieves the data, but does not apply it to a template: client.getEntries() .then((response) => { $('.res ...

How can JSON be managed on the client side?

Can data from a JSON file be managed without needing it to be served via http:// or https://? Can it be referenced like a JS file or CSS file in an HTML page? ...

What is the most efficient method to extract information from a jQuery script in web.py?

Seeking a tutorial for jQuery + web.py has been fruitless. As a result, I have a straightforward question regarding the POST method. This is my jQuery script: <script> jQuery('#continue').click(function() { var command = jQu ...

Methods for extracting the date value from a Material UI datepicker?

As a newcomer to React, I am currently working on creating a form that includes a Date picker for scheduling appointments. Since booking appointments in the past is not allowed, I need to disable the days before today in the calendar for the date picker. ...

jQuery now enables the number field to accept not only one period but multiple periods

I need to update a number field in a form to accept multiple periods, specifically for entering software version numbers. Currently, the code I am using only allows for one period to be entered, resulting in an error when two periods are added to the fie ...

Is there a way to convert an array of objects with 2 elements into 2 separate arrays?

I am looking to split a single array containing objects with 2 elements into two separate arrays. After making an axios call, I received the following array: chartdata: Array [4] [{"total":3,"month":9}, {"total":5,"m ...

When the server reloads, an error occurs stating 'CodeMirror' is not defined when using CodeMirror with Vuejs/Nuxtjs

I've integrated CodeMirror into one of the textarea elements in my Nuxtjs/Vuejs application. I want to format the textarea to resemble XML. While the CodeMirror functions correctly at times, I encounter an error when reloading the page: Test.vue 33:1 ...