Mastering the art of transitioning between DIV elements

I am looking to implement a rotating three-card display on click, and have come up with the following code:

$('.box1').click(function(){
    $('.box1').toggleClass('removeanimate');
    $(this).toggleClass('go');
    $('.box2').removeClass('go');
});

$('.box2').click(function(){
    $(this).toggleClass('go');
    $('.box3').removeClass('go')
});

$('.box3').click(function(){
    $(this).toggleClass('go');
    $('.box1').toggleClass('go');
    $('.box2').toggleClass('go');
});
.wrapper{
    position:static;
}

.box{
    width:200px;
    height:100px;
    position:absolute;
    margin:5px;
    cursor:pointer;
    overflow:hidden;
    text-align: center;
    line-height: 100px;
}

.box1 {
    z-index:2;
}
.box2{
    z-index:1;
}
.box3{
    z-index:0;
}

.go{
    height:0;
    width:0;
}

.box:nth-child(1) {
    background: green;
}
.box:nth-child(2) {
    background: red;
}
.box:nth-child(3) {
    background: orange;
}
.removeanimate: {
  transform: scale(0.7);
  transform-origin: left;
  background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
    <div class="box box1"><h2>I'm block 1</h2></div>
    <div class="box box2"><h2>I'm block 2</h2></div>
    <div class="box box3"><h2>I'm block 3</h2></div>
</div>

Now, I have the following questions regarding this implementation:

1- It seems that the animation between cards using .removeanimate is not working properly. How can this be resolved?

2- I am concerned about scalability in the script part. Adding more boxes manually for the onclick function is not ideal. Is there a better way to handle this without disrupting the rotation behavior?

Answer №1

1 - When using keyframes, ensure to set up the animation in your keyframes CSS rule and then specify the name of your keyframes animation within a class with the `animation-name` property.

Learn more about CSS3 animations here.

2 - My recommendation is to iterate through elements with the "card" class and add class names and z-index using `each()` + index.

For handling click events, extract the digit from the class name (e.g., box0) using regex, retrieve the next element's digit (e.g., box1), apply the keyframes animation class, hide the current box, and display the next one.

I have provided detailed comments throughout my code.

// Count all boxes
var getNumberOfBox = $(".box").length;

// Initialize boxes
initBox(getNumberOfBox);

// Handle click event on box
$(".box").click(function() {
    // Check if current box is animated
    if (!$(this).is(':animated')) {
      // Check if next box exists
      if ($(this).next("div.box:first").length) {
        // Get digit from class name (e.g., box1)
        var boxNum = $(this).attr('class').match(/\d+$/)[0];
        // Get digit of next card
        var getNextBoxNum = $(this).next("div.box:first").attr('class').match(/\d+$/)[0];

        // Ensure variables are defined
        if (typeof boxNum !== "undefined" && typeof getNextBoxNum !== "undefined") {
          // Add keyframes animation class and fadeOut current box
          $(".box" + boxNum).addClass("removeanimate").fadeOut(700, function() {
            // Remove keyframes class name
            $(".box" + boxNum).removeClass("removeanimate");
            // Show next card
            $(".box" + getNextBoxNum).fadeIn();
          });
        }
      } else {
        // Restart the loop
        $(".box:visible").fadeOut(250, function() {
          $(".box:first").fadeIn(250, function() {
            $(".box").removeClass("removeanimate").css("display", "block");
          });
        });
      }
    }
});

function initBox(boxCount) {
  // Iterate through all elements with "box" class
  $(".box").each(function(index) {
    // Add class name and z-index using each() and element index
    $(this).addClass("box" + index).css("z-index", boxCount - index);
  });
}
.wrapper{
    position: static;
}

.box{
    background: #333;
    width: 200px;
    height: 100px;
    position: absolute;
    margin: 5px;
    cursor: pointer;
    overflow: hidden;
    text-align: center;
    line-height: 100px;
}

.box:nth-child(1) {
    background: green;
}
.box:nth-child(2) {
    background: red;
}
.box:nth-child(3) {
    background: orange;
}
.box:nth-child(4) {
    background: purple;
}
.box:nth-child(5) {
    background: teal;
}


/* Add keyframes name to a class with "animation-name" for animation */
.removeanimate {
  animation-duration: 1s;
  animation-name: scaleAnim;
}

/* Set custom animation */
@keyframes scaleAnim {
  to {  
    transform: scale(0.7);
    transform-origin: left;
    background-color: pink;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
    <div class="box"><h2>I'm block 1</h2></div>
    <div class="box"><h2>I'm block 2</h2></div>
    <div class="box"><h2>I'm block 3</h2></div>
    <div class="box"><h2>I'm block 4</h2></div>
    <div class="box"><h2>I'm block 5</h2></div>
</div>

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

Trouble accessing state when React child calls parent method

Within my project, I am working with 3 components that are nested as follows: App->GameList->GameItem The App (parent) component has a method that is triggered by the onClick event within the GameItem (child) component Upon clicking the GameItem co ...

Having issues with the onSubmit event not being triggered for a react + material-ui form

I am currently using the mui box react component with the form set to the component property and an onSubmit attribute pointing to the submit handler I want to invoke. There is a submit button located at the bottom of the form. However, every time I click ...

What could be causing the issue of React not showing the messages of "hello" or "goodbye"?

I have a page with a single button that is supposed to display either "hello world" or "goodbye world" when clicked. However, I am facing issues as the messages are not showing up as expected. Below is a screenshot of what the menu items look like when ca ...

Tips for creating a clickable A href link in the menu bar that triggers an accordion to open in the body when clicked - html

Is there a way to open the first accordion when clicking on the "open 1st accordion" link, and do the same for the second link? The accordions themselves work perfectly fine, I just need a way to trigger them from outside their scope by clicking on links i ...

Determine the type and size of files prior to uploading

Similar Question: How can jQuery limit file types for upload? I have an inquiry. I am planning to use Ajax to submit a form that may include file uploads. Can you advise me on how to determine the selected file type and size before uploading? I under ...

How can I extract the return value of a JSON object and store it in a variable?

I am attempting to develop a dynamic chart by utilizing data retrieved from a function housed inside a JSON object. The JSON object is fetched through the Relayr Javascript API, and looks like this: relayr.devices().getDeviceData({ token: tok ...

Tips on how to showcase a picture with the focus on the center by enlarging it within

We have a long frame on the page, with an aspect ratio of about 3.5:1 width to height. However, most of the photos being displayed are in a 4:3 ratio, which is larger and not a proper fit for the frame. The customer really wants the long frame and has no ...

Find similarities between two JavaScript arrays using unique identifiers

Seeking a more efficient and streamlined approach in javascript to compare two arrays and generate a third one. We have the following two arrays : var array1 = [ [{ id: 1, enabled: false }], [{ id: 2, enabled: true, }], [{ ...

What is causing me to repeatedly encounter the 403 forbidden error?

I keep encountering a 403 forbidden error and I am unable to retrieve my JSON data at all. Here is an excerpt from my HTML source: <html> <head> <meta name="keywords" content="jquery,ui,easy,easyui,web"> <meta name="descriptio ...

Issue: The module could not be located within the project or in any of the directories, including node_modules

Error: It seems we're having trouble resolving the module navigation/stack-routes from MainTabs.tsx file in gymzoo project directory. The path navigation/stack-routes could not be located within the project or node_modules directory. Greetings! I&apo ...

Aligning an element in the middle of an image vertically

Trying to vertically center a div inside an image element has been challenging. While there are many ways to achieve vertical centering in general, this specific case presents unique difficulties. To accomplish this, the following minimum code is needed: ...

Modify CSS class if user is using Internet Explorer version 10 or above

I am attempting to modify the CSS of 2 ASP controls using jQuery specifically for users accessing the site with Internet Explorer 10 or 11. This adjustment is necessary because IE10 onwards, conditional comments are no longer supported. My approach to achi ...

I possess an array containing objects of different lengths depending on the chosen city. How can I pinpoint the element that contains an object with a specific property?

My dilemma arises from the fact that the length of an array depends on the selected city, making it impossible to select elements using an index. In this scenario, I need to devise a method to choose elements based on the value of one of their properties. ...

Disable a href link using Jquery after it has been clicked, then re-enable it after a

There are several <a target="_blank"> links on my website that trigger API calls. I want to prevent users from double clicking on these buttons. This is what I have tried: .disable { pointer-events: none; } $(document).ready(function(e) { ...

How to Override package.json Scripts in NPM

Is it possible to modify package.json scripts without changing the original file? I need to customize the memory allocation for a specific step, but altering the package.json will affect everyone. For example, our current script is: "script": { "dev": ...

Hosting services and content management system for a website built with Twitter Bootstrap

Embarking on a new venture to create a website for a Custom Home Building company, I am eager to learn and grow in web development. Although I have some programming experience, please bear with me as I ask my newbie questions. I have been searching high a ...

How is it possible to access a variable in a function that hasn't been declared until later?

While working on a Dialog component, I had an unexpected realization. export const alert = (content: string) => { const buttons = [<button onClick={()=>closeModal()}>ok</button>] // seems alright // const buttons = [<button onCli ...

Change the right border style for the second and third ToggleButtons in the ToggleButtonGroup

I've been working on this for a few hours now and I can't seem to get it right. Currently, I'm using Mui v5 and trying to style the ToggleButtons to look like regular MUI buttons. So far, I was able to achieve this transformation: https:/ ...

What sets the target property of the mousewheel event apart from other events like click, mousedown, and touchstart?

The mousewheel event's target property reveals the DOM element currently being hovered over when using the mousewheel or gesture-capable touchpad. In my experience (specifically in Safari 6, I will verify this in other browsers later), the target ret ...

Encountering cross-domain error when attempting Google Maps API GET request

I have been working on a JavaScript function that utilizes the Google Maps places API to retrieve information. Here is the function I have written: function makeCall(url) { var data = $.ajax({ type: "GET", url: url, async: f ...