Animating with CSS3 triggered by JavaScript

Can you help me with an issue I'm having? When attempting to rotate the blue square using a function, it only works once. After that, the page needs to be reloaded in order for the rotation function to work again. Additionally, after rotating 120 degrees with one click, the square resets itself back to its starting position.

I need assistance with two things:

  1. Fix the rotation function so it can be clicked multiple times without resetting.
  2. Prevent the square from automatically resetting its position.

I have created a fiddle with the code: https://jsfiddle.net/kv7may8t/2/

document.getElementById('button1').addEventListener('click', function() {
    document.getElementById('blue').classList.add('rotateright');
});

Summary of the function: Click on button1 to activate the function that adds the "rotateright" class to the blue square, causing it to rotate by 120 degrees.

Answer №1

Solution for the initial problem is to remove a specific class:

var bluediv = document.getElementById('blue')

bluediv.addEventListener("animationend", function() {
bluediv.classList.remove('rotateright');
      bluediv.classList.remove('rotateleft');
});

View the updated Fiddle. (Clicking the rotation function multiple times no longer causes issues)

Additionally, for the second issue (apply in right only):

Implement:

animation-iteration-count: forwards;

Check the modified version in the updated Fiddle here. (Prevents the square from resetting its position)

Answer №2

Your solution is almost there, just a small tweak needed! The issue lies in the implementation of the transform classes. To solve this problem, simply remove the class before adding it again. You can check out an example on this fiddle.

document.getElementById('button1').addEventListener('click', function() {
    document.getElementById('blue').classList.remove('rotateright');
    setTimeout(function(){
        document.getElementById('blue').classList.add('rotateright');    
    },100)
});

document.getElementById('button2').addEventListener('click', function() {
    document.getElementById('blue').classList.remove('rotateleft');
    setTimeout(function(){
        document.getElementById('blue').classList.add('rotateleft');        
    },100)
});

document.getElementById('button3').addEventListener('click', function() {
    document.getElementById('red').classList.add('animate');
});

document.getElementById('button4').addEventListener('click', function() {
    document.getElementById('red').classList.remove('animate');
});

Remember to use setTimeout after removing the class to allow time for the transition to take effect.

Answer №3

Give this a try:

    document.getElementById('button1').addEventListener('click', function() {
   var angle += 90;
   var duration = 2;
   document.getElementById('square').style.WebkitTransitionDuration= duration + "s";
   document.getElementById('square').style.transform = "rotate(" +angle + "deg)";
});

You can customize the angle and duration as needed.

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

Rendering with Next.js script

Within my Next.js project, there is a script implemented to render a widget. The code for this script looks like: <a className="e-widget no-button xdga generic-loader" href="https://example" rel="no ...

Gradually fade with JavaScript

My JavaScript code below is used to recursively reload a specific DIV with the results of a data query. The issue I'm facing is that each time the DIV, identified by id="outPut", is reloaded, all the data fades in and out due to the fadeTo function. ...

Rearrange object based on several criteria - JavaScript

var numbers = { "value": [{ "num1": 1, "num2": 10 }, { "num1": 15, "num2": 13 }, { "num1": 26, "num2": 24 }, { "num1": 6, "num2": 25 }, { "num1": 15, "num2": 20 ...

Creating Vertical Text and Div Blocks using CSS

Trying to set up different color section blocks with vertical text on my website's dashboard page. Similar to this example in JSfiddle: http://jsfiddle.net/afpn2y19/4/ <div id="outer"> <div id="inner"> //Feeling lost - ho ...

Tips for optimizing search functionality in Angular to prevent loading all data at once

An exploration for information within vast datasets is triggered by AngularJS when the input contains more than 3 characters. var app = angular.module('test_table', []); app.controller('main_control',function($scope, $http){ $scope ...

Flipping numbers in Arabic font using PDF kit

Currently, I am utilizing the pdfkit library in my Node.js application for PDF generation. However, I encountered an issue while attempting to incorporate Arabic text. The problem lies in the fact that it consistently rearranges the numbers within Arabic t ...

Trouble accessing webpage on Apple devices

I recently created a website using Django and Bootstrap 5. Everything seems to be working perfectly as intended, except for when it is viewed on older iPhone models such as 6 or 7. The gifs and pictures that are dynamically fetched from the DjangoDB do not ...

Performing a JSON POST Request: Steps for sending a POST request with JSON data format

I need to send the following data: { "contactsync": { "rev":4, "contacts":[ { "fields": [ { "value": { ...

Steps for adding a navbar that slides horizontally and overlaps other links on a webpage

I am attempting to design a sliding navigation menu using JQuery. The concept involves having multiple main sections, each with several subsections. When a user hovers over a section, the subsections will expand horizontally. If another section is current ...

Navigating the battleground between native and HTML5 mobile applications

As an experienced iOS developer with knowledge in Windows Phone and Android, I have observed the increasing popularity of HTML5 web-apps over native apps. This shift towards HTML5 development frustrates me, as a strong argument can be made for native app d ...

I'm having trouble managing state properly in Safari because of issues with the useState hook

Encountering Safari compatibility issues when updating a component's state. Though aware of Safari's stricter mode compared to Chrome, the bug persists. The problem arises with the inputs: https://i.sstatic.net/WSOJr.png Whenever an option is ...

Arranging the placement of the dropdown menu

I am struggling with positioning the items in my dropdown menu. The functionality itself is working perfectly, but the issue arises when it comes to aligning the dropped down items. Initially, I positioned them based on a smaller screen size, but when view ...

Error message encountered: ReferenceError - The subcommand specified in Discord.js Slash Command function is undefined

I have been experimenting with subcommands in a slash command for a discord bot. I plan to have several similar subcommands, so I wanted to create a function that can be called within .addSubCommand, but it seems like it's not functioning correctly. ...

What is the reason behind div elements shifting when hovering over a particular element?

Currently, I have floated all my div elements (icons) to the left and margin-lefted them to create space in between. I've displayed them inline as well. However, when I hover over one element (icon), the rest of the elements move. Can you please help ...

Make sure that the two rows in my Bootstrap table are consistently positioned next to each other, regardless of the length of the text

When working with a Bootstrap panel containing text inside a table, I've encountered a challenge. One side features links while the other displays descriptions. At times, I find myself having to artificially lengthen the text to ensure it aligns corre ...

Utilizing Bootstrap 5's table design to occupy the rest of the available vertical

In my .NET Core 7 MVC project, I am facing a challenge where I want to make a details table scroll and occupy the available vertical space on the screen dynamically. I have tried using h-25, h-50 classes to achieve the scrolling effect on the table. Howev ...

Change the color of the plotly button when it is clicked

I recently implemented a custom button on my plotly modeBar and I would like it to retain a distinct color when clicked. This would help visually indicate its "active" state, allowing users to easily discern whether it is enabled or disabled based on its ...

div maintain aspect ratio while scaling

My current layout is structured like this: HTML <div id="container"> <div id="zoomBox"> <div class="box"></div> <div class="box"></div> <div class= ...

Ensuring Valid Submission: Utilizing Jquery for a Straightforward Form Submission with 'Alajax'

After searching for a straightforward JQuery plugin to streamline the process of submitting forms via Ajax, I stumbled upon Alajax. I found it quite useful as it seamlessly integrates into standard HTML forms and handles all the necessary tasks. However, I ...

Mapping choices array in ReactJS using the id as a key reference

Looking for assistance with JavaScript as I am relatively new to it. I have a page displaying scheduled exams, and clicking on "Learn more" opens a modal where you can edit exam details. Currently, the modal displays selected equipment and allows changing ...