Problem arising from animation not commencing at expected starting point

Creating a feature on an app that involves breathing exercises using CSS animations. The challenge I'm facing is ensuring the words "exhale" and "inhale" appear synchronously with the animation of a circle shrinking and enlarging. However, the animation doesn't always start from the same point, causing display issues.

function toggleDropdown() {
  var dropdownContent = document.getElementById("dropdown-content");
  dropdownContent.classList.toggle("show");
}

var timer;

// More JavaScript code...

body {
  background: #005eb8;
  margin: 0;
  padding: 0;
  // More CSS styles...
}
<div class="container">
  <h1>Breathing Exercises</h1>
  
  // More HTML code...
  
</div>

Despite trying various approaches to resetting the animation for each exercise selection, I have not yet found a successful solution.

Answer №1

To achieve this effect, you can use CSS transitions along with manipulating a custom property for the transition time duration and adding or removing classes dynamically.

Answer №2

One approach would be to utilize the animationiteration event and update your text content accordingly.

const circle = document.querySelector(".circle");

const inhale = () => {
  circle.innerHTML = "Inhale";
};
const exhale = () => {
  circle.innerHTML = "Exhale";
};

const animate = () => {
  inhale();
  circle.style.animationPlayState = "running";
  circle.addEventListener("animationiteration", (ev) => {
    if (ev.elapsedTime %4 === 0) {
      inhale();
    } else {
      exhale();
    }
  }, false);
};

document.getElementById('animate').addEventListener('click', animate);
.circle-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  margin-bottom: 20px;
}

.circle {
  width: 200px;
  height: 200px;
  background-color: #4BC0C0;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 24px;
  font-weight: bold;
  animation-name: breathe;
  animation-timing-function: ease-in-out;
  animation-iteration-count: infinite;
  animation-direction: alternate;
  animation-duration: 2s;
  animation-play-state: paused;
  animation-fill-mode: forwards;
  margin-bottom: 5px;
}

.circle span {
  margin: 33% auto;
  display: inline-block;
  visibility: hidden;
}

@keyframes breathe {
  0% {
    transform: scale(1);
  }
  100% {
    transform: scale(1.25);
  }
}
<div class="circle-wrapper">

    <div class="circle"></div>

</div>


<button id="animate">animate</button>

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

The printing code is not able to interpret the CSS

Having trouble with this script not reading the style properly when printing, can anyone assist in identifying the issue? <script type="text/javascript"> $(function () { $("#btnPrint").click(function () { var contents = $( ...

Having trouble dynamically adding elements to the Semantic-UI Accordion component

I have a challenge involving inserting dynamic content into a Semantic-UI Accordion. My goal is to display JSON data as an Accordion in the HTML. Below is the script and HTML I am using for this purpose: <script language='javascript'> ...

What is the reason for the additional line being generated?

Can anyone explain why there is an extra line being produced here? I came across another question where it was mentioned that this issue is not due to CSS but rather caused by HTML. Why is that? This is completely new to me, and I'm curious as to wh ...

Is the callback still triggered even after the off function is called?

Can someone help me with a scenario where despite calling the off on a reference, the callbacks are still being triggered repeatedly? var ref = new Firebase('https://example.firebaseio.com/123456'); for (var n = 0; n < 1024; ++n) { ref.pus ...

AngularJS SmartyUI position not dynamically updating on SmartyStreets plugin

In my angularJS application, I am utilizing SmartyStreets' LiveAddress for address validation and autofilling two fields in a form. After the user submits the form, a message (either success or failure) is displayed in a div above the form. However, t ...

When using Jest, it is not possible to match 'undefined' using 'expect.any(Object)' or 'expect.anything()'

Looking to test the following module. import * as apiUtils from './apiUtils'; export function awardPoints(pointsAwarding) { return apiUtils.callApiService("POST", "points", pointsAwarding); } This is the test in question. it("should call ap ...

Does Node.js support backward compatibility?

There is a common belief that Node.js is backwards compatible, meaning scripts running in Node.js N should also work in Node.js N+1. I have been unable to find any documentation confirming this assumption. Is there another way to verify compatibility aside ...

There was an error in the syntax: JSON parsing error, an unrecognized token '<'

Having trouble with a syntax error: JSON parse error due to an unrecognized token '<'. One page is functioning properly with the same code, while another is displaying this error. I am unable to identify my mistake. Front-end code: const getd ...

Perform simple arithmetic operations between a number and a string using Angular within an HTML context

I'm stuck trying to find a straightforward solution to this problem. The array of objects I have contains two values: team.seed: number, team.placement: string In the team.placement, there are simple strings like 7 to indicate 7th place or something ...

Enhance user interactivity by incorporating dynamic checkboxes, radio buttons, checkbox groups, and radio button groups using Ext

Hello to all the amazing folks at Stack Overflow! I've tried searching for a solution to this issue on Stack Overflow, but I couldn't find anything helpful. Here is my model: Ext.define('soru', { extend: 'Ext.data.Model' ...

Invoke a function within the redux reducer

The code within my reducer is structured as follows: import {ADD_FILTER, REMOVE_FILTER} from "../../../../actions/types"; const removeFilter = (state, name) => { return state.filter(f => f.name !== name); }; export default function addRemoveFi ...

Creating HTML content in a new window with Vue.js - a step by step guide

Recently, I encountered a problem with jsPDF regarding Unicode support in table generation. To work around this issue, I decided to utilize the browser's print feature instead. I achieved this by creating a new HTML document with the table and display ...

Adding jQuery and other libraries to Typescript for optimal functionality

After spending days researching and struggling, I am reaching out here for clarification on the process of importing a library in Typescript. I used to just add the script tag and everything would work fine. Now that I am working on building a MEAN-Stack ...

PHP - Issue with AJAX Login Functionality

I have been developing an AJAX login system and encountering an issue where it does not send any response back unless I use exit("error here") in the script. However, my goal is to return a JSON response instead. The form structure: <div id="account" ...

Is there a way to access the content of a drop-down menu in JavaScript besides using ".value"?

Trying to create a table with rows that change dynamically but columns that are fixed. There's a drop-down menu whose content is based on an xml file. When I use .value to access the current content of my drop-down menu, it works fine in Firefox but n ...

The error message "TypeError: (0, _style.default) is not a function" occurred when using jest along with material

My current configuration looks like this: // .jestrc.json ... "moduleNameMapper": { "style$": "<rootDir>/tests/mock.ts" } // mock.ts export default {} This setup is typically used to exclude assets from jest to pre ...

What is the optimal arrangement for constructors or classes in JavaScript code?

Constructors, being objects that are stored as copies, appear to behave similarly to variables in terms of their placement within the code. Unlike functions, constructors cannot be placed "anywhere" and must instead be positioned above the area where they ...

Insert some text into the div element. Create a new line

I'm looking to make a specific text on my webpage trigger a new line when displayed in a div. I've been struggling to figure out how to accomplish this: var original= "the text @n to change"; var changed = original.replace(/@n /g, '\ ...

Leverage socket.io in various routes within a node.js application

In my Node.js application, I have various routes defined in the router.js file. Now, I want to implement socket.io in every route to enable real-time communication between my Node.js and React.js applications. However, the structure of my Node.js applicati ...

Stop the upload progress in Angular 6 by unsubscribing from the upload observable, without halting the actual

When attempting to cancel an upload by unsubscribing, the unsubscribe action only stops the progress of the upload from being displayed, but the actual upload process continues and files are still uploaded to the server. This issue is present in the upload ...