CSS animations are malfunctioning and not cycling correctly

I have developed two animations with distinct classes that should enable and disable fullscreen when a button is pressed, executing the first animation on the initial press and the second animation on subsequent presses of the same button.

CSS Enabling fullscreen through animation and disabling it through reverse animation

    #mv {
        width: 100%;
        height: 57%;
    }

    .animate {
        animation: fullscreen 0.5s;
        animation-fill-mode: forwards;
    }

    @keyframes fullscreen {
        from {
            height: 57%;
        }

        to {
            height: 100%;
        }
    }


    .animatereverse {
        animation: fullscreenreverse 0.5s;
        animation-fill-mode: forwards;
    }

    @keyframes fullscreenreverse {
        from {
            height: 100%;
        }

        to {
            height: 57%;
        }
    }

TS/JS I utilized a flag to signal whether the interface is in fullscreen mode or not

      var fullscreen = false;
      //console.log(" fullscreen now false ");
        document.getElementById('fllbtn').addEventListener("click", function () {          
          if(fullscreen == false){     
            //console.log(" fullscreen is false ");
            fullscreen = true;
            //console.log(" fullscreen now true ");
            document.getElementById("mv").classList.toggle("animate");
          }else{
            //console.log(" fullscreen is true ");
            fullscreen = false;
            //console.log(" fullscreen now false ");
            document.getElementById("mv").classList.toggle("animatereverse");
          }
        })

The issue is described as follows:

BEGIN
*non-fullscreen interface
*I click the fullscreen button
*animation triggers, interface becomes fullscreen
*I click the fullscreen button again
*animation plays, interface returns to non-fullscreen state
*I click the fullscreen button once more
*animation does not trigger, interface remains unchanged
*I click the fullscreen button another time
*animation still does not work, interface stays the same
END

You could view it as a loop, repeating the process twice, transitioning back and forth like this.

Answer №1

toggle('classname') will either add the specified class if it's not already present, or remove it if it is already there.
In practical terms, here is what happens:

  1. Click on fullscreen for the first time
  2. The toggle function is triggered; adds the .animate class to the element with id #mv
  3. Click on fullscreen for the second time
  4. On this iteration, the .animatereverse class is added to the #mv element
  5. At this point, #mv has both classes: .animate and .animatereverse
  6. Click on fullscreen for the third time
  7. The function executes again, triggering a toggle action for the .animate class. This leads to the removal of the .animate class from #mv. Now, #mv only retains the .animatereverse class. As a result, no new animation is displayed

Instead of using toggle, consider explicitly adding and removing the desired classes as shown in the code snippet below:

var fullscreen = false;

document.getElementById('fllbtn').addEventListener("click", function() {
  fullscreen = !fullscreen;
  if (fullscreen) {
    document.getElementById("mv").classList.remove("animatereverse");
    document.getElementById("mv").classList.add("animate");
  } else {
    document.getElementById("mv").classList.add("animatereverse");
    document.getElementById("mv").classList.remove("animate");
  }

})
#mv {
  width: 100%;
  height: 57%;
  padding: 2rem;
  background-color: salmon;
}

.animate {
  animation: fullscreen 0.5s;
  animation-fill-mode: forwards;
}

@keyframes fullscreen {
  from {
    height: 57%;
  }
  to {
    height: 100%;
  }
}

.animatereverse {
  animation: fullscreenreverse 0.5s;
  animation-fill-mode: forwards;
}

@keyframes fullscreenreverse {
  from {
    height: 100%;
  }
  to {
    height: 57%;
  }
}

.wrapper {
  position: relative;
  height: 150px;
  width: 300px;
}
<button id="fllbtn">fullscreen</button>
<div class="wrapper">
  <div id="mv">
    i'm mv
  </div>
</div>

Answer №2

Here is a more efficient approach that involves using CSS transitions:

Styling in CSS

#mv {
    width: 100%;
    height: 57%;
    transition: height 0.5s ease;
}

#mv.fullscreen {
    height: 100%;
}

Handling in TS/JS

document.getElementById('fllbtn').addEventListener("click", function () {
    document.getElementById("mv").classList.toggle("fullscreen");
})

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

When there is no data in the request body, ExpressJS will display it as empty

A big part of my tech stack includes a website with an express server up and running. The website allows users to insert their username and password. Upon clicking the login button, the server receives a request with the username and password packed as a J ...

The jQuery code continues to loop endlessly

My current script includes a fadeIn effect on a div when the user scrolls 200px from the top, along with custom circle animations. While it works, I admit it's not the most elegant solution as I had to piece together different scripts to make it funct ...

Exploring the Bounds of Mongodb's $within Query

I'm currently working on a geospatial query in mongodb using the $within operator. I have a collection entry with a location field containing: location: { bounds: { south_west: { lat: XX.XXXXXX, lng: XX.XXXXX }, north_east: { lat: XX.XXXXXX ...

NavigateToTop/BackToTheBeginning

I'm facing a challenge with a page layout that involves two vertical div's - one for the menu on the left and another for loading content on the right. My goal is to utilize the .scrollintoview() function on the menu div so that when a link is cl ...

Tips for concealing the URL in the address bar while using `<a href>` links

I have a variety of documents saved in a folder within an ASP MVC 5 project. Instead of directly linking to the document with an HTML tag, I am utilizing the following ng-href: <a ng-href="~/download/document/{{vm.document}}"></a> By using th ...

JavaScript can intelligently extract and categorize an array of objects based on their properties

In essence, I aim to develop a versatile function "organize" that can transform the following data structure: [ { name: 'band1', type: 'concert', subtype: 'rock' }, { name: 'band2', type: 'concert' ...

Create a layout where a flexbox container is nested under another div and achieve the desired positioning

<style> .container{ display: flex; gap: 5px; flex-direction: row; justify-content: space-around; flex-wrap: wrap; overflow:auto; } .container .one{ background-color: blue; ...

$q: standard reject handler

I am looking for a way to ensure that when clients do not specify a reject handler in the 'then' function, a default one is automatically triggered. For example, let's say the default action is alert(1) In this scenario, calling mypromise. ...

Angular component classes now use the updated RXJS 6.X syntax, rendering the previously used observable deprecated

Here is the component method I am using: if (id !== undefined && id != null && id !== 0) { this.dataService.getTransactionById(id).subscribe( (tr: ITransactionResponse) => { ...

Creating a Burger Navigation Menu with CSS and HTML using Image Overlapping

I'm encountering an issue with the new website I created for my local Church. I followed a tutorial on building a burger menu using just HTML and CSS, which you can view here. The problem arises when I attempt to place an image below the navigation m ...

Can mathematical calculations be performed using css3?

My dilemma involves a parent element and a child element set up in the following manner: <parent element> <...> <...> <child element></child element> </...> <...> &l ...

An error is encountered with the getToken function in the Edge Runtime when using dynamic code evaluation methods such as 'eval', 'new Function', or 'WebAssembly.compile'

Working on a project that utilizes NextAuth.JS for authentication and Redux-Saga as the state manager. To enable refresh token rotation, I have created the following set of functions: get-token.ts: import { UUID } from 'crypto'; import jwt from ...

My date function in Node JS is throwing an error, can someone please help me troubleshoot?

I encountered an error with new date(); while working with node js and express npm plugin. I built a variable date but faced some compilation errors. This is my code .js var update_time = new Date(); update_time.formatDate("y/m/d"); When I run ...

Vue's bidirectional data binding presents a challenge when attempting to update the parent component from a child component

I have the following components: Parent Component: <template> <v-container> <v-row class="text-center"> <v-col cols="12" class="parent"> <p>I am the Parent component</p> ...

Designing exquisite button navigation

Hey everyone, I'm currently working on creating a circular button navigation for my website. I want to have 4 buttons, each with a different color, and I want them to glow when the user hovers over them. So far, this is what I have in my HTML: HTML: ...

unable to retrieve controls generated from AJAX response

My web development stack includes ASP.NET C# with AJAX Professional (http://www.ajaxpro.info) 1) I am working on a scenario where I have a div container that holds a Panel control which should contain a dynamically generated DropDownList done in the codeb ...

Switching CommonJS modules to an ESM syntax for better compatibility

I'm currently facing a challenge in grasping the process of importing CommonJS modules into an ESM syntax. Specifically, I am working with the library url-metadata. This library provides a top-level export as a callable function, which deviates from t ...

Tips for populating a textfield with data from a <select> dropdown using javascript

Is there a way to populate a textfield with data automatically based on information provided in the tab, utilizing JavaScript? Additionally, is it possible to prevent the filled data from being edited? The textfield should be able to dynamically fill data ...

Encountered a problem when trying to add an onclick event to dynamically created HTML: Uncaught SyntaxError: Unexpected identifier was

Utilizing ajax to fetch results from the code behind, I am dynamically creating divs upon receiving those results. The process works smoothly without any issues. Now, my objective is to attach an onclick event to each div that triggers a specific method w ...

Encountering an issue while trying to utilize Vuex in Vue with TypeScript

I recently utilized npm to install both vue (2.4.2) and vuex (2.3.1). However, when attempting to compile the following code snippet, I encountered the following error: https://i.stack.imgur.com/0ZKgE.png Store.ts import Vue from 'vue'; import ...