Clickable CSS3 animations

Currently exploring the fundamentals of CSS3 animation and onclick events, but I've hit a roadblock.

My objective is to utilize button id="3" to initiate the animation on the red square displayed here: https://jsfiddle.net/4swmegpn/ Additionally, I aim to use button id="4" to halt or reset the animation of the red square.

I'm unsure where to begin. I started by adding onclick to:

<button id="button1" onClick=""> > </button>

However, beyond that initial step, I am unsure of what actions to take next. I need something to trigger and execute the "keyframes example" from the css-file, but I'm unclear on how to proceed.

Answer №1

To initiate or conclude an animation, you can manipulate the element by adding or removing a class. Then in your CSS, assign the desired animation to that class (check out this example). It's best practice to avoid embedding JavaScript directly into your HTML code (such as using onclick), but instead, utilize event listeners within scripts:

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

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

You could also employ checkboxes, hover states, or other selectors to trigger animations purely through CSS. There are numerous methods available depending on your specific requirements.

Answer №2

Before we delve into the world of animation, here are a few tips to keep in mind:

  • No need to type out doctype, head, and body tags as JSFiddle handles that for you.

  • Remember to escape characters like < and > with &lt; and &gt; to prevent breaking your HTML code.

  • When working on CSS3 animations, make sure to use Vendor Prefixes for better browser compatibility:

    1. Chrome & Safari: -webkit-
    2. Firefox: -moz-
    3. Opera: -o-
    4. Internet Explorer: -ms-

It's recommended to save non-prefixed CSS3 code for last as it will override any browser-specific prefixes. For keyframes, structure them like this example:

@-webkit-keyframes tutsFade { /* your style */ }
@-moz-keyframes tutsFade { /* your style */ }
@-ms-keyframes tutsFade { /* your style */ }
@-o-keyframes tutsFade { /* your style */ }
@keyframes tutsFade { /* your style */ }

Now onto the animation part - check out this simplified version of your example here. The .exampleAnimation class includes everything needed for an element to start animating with the defined example animation at the end of the CSS file. You can directly apply this class to an HTML element or manage it through JavaScript to control the animation playback.

For beginners, here are some beginner-friendly tutorials: Introduction to CSS Animation, and Control CSS3 Animations With jQuery.

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

Tips for re-formatting JSON data using Lodash / JavaScript

Can anyone help me with reformatting the JSON data below? [ { "name": "Hello", "value": 1 }, { "name": "Hello", "value": 11 }, { "name": "Bye", "value": 2 }, { "name": "Bye", "value": 22 } ] I want to trans ...

Showing time on a JSON document using JavaScript Timeline

Currently, I am in the process of creating a widget using a timeline JS template. The main challenge lies in receiving events in JSON format, which is essential for the functionality of the widget. At this stage, my focus is on being able to fetch events f ...

How to properly handle string escaping within a JSON object

When I send this object as JSON response, it includes double backslashes in the URL. {"__type":"http:\/\/example.com\/contracts\/documents\/rendering\/instructions\/1\/0"} My desired response is: {"__type":"http:& ...

Stuck on loading screen with Angular 2 Testing App

Currently working on creating a test app for Angular 2, but encountering an issue where my application is continuously stuck on the "Loading..." screen. Below are the various files involved: app.component.ts: import {Component} from '@angular/core& ...

Do the Push Notification APIs in Chrome and Firefox OS follow the same set of guidelines and standards?

Do Chrome and Firefox OS both use Push Notifications APIs that adhere to the same standard? If not, is either one moving towards standardization? ...

What is the best way to implement client-side shopping cart calculations using jQuery?

https://i.stack.imgur.com/aOajr.png Here is the content of my shopping cart. Below, I will explain the flow. [product image clicked] -> ajax request fetches details from database for that particular product id and appends (product name,id and price ...

Having trouble making class changes with ng-class

I am attempting to change the direction of the arrow in my checkbox by utilizing two classes with the assistance of ng-class. Unfortunately, it is not producing the desired outcome. Below is my code: Note: The angularJS CDN has already been incorporated. ...

Sustaining the hover effect background color when hovering over submenu options

I am currently working on a navigation menu that includes list items a, b, c, d, e, f. One issue I am facing is when a user hovers over the list item d, the submenu items like d1, d2, d3, d4, and d5 appear within the d section. However, the background col ...

Obtaining metadata from Youtube videos with Javascript and HTML5

Is there a way to fetch YouTube video data with Javascript and HTML5? If so, could you provide some helpful resources or links? ...

What is the best way to execute a JavaScript file with npm scripts?

Trying to use npm but encountering some issues. In my package.json file, I have: "scripts": { "build": "build.js" } There is a build.js file in the same folder that simply console.logs. However, when I execute npm run build I receive the error messag ...

The web application I developed has a glitch where it duplicates user input when creating a new post, and doesn't display the user's deleted

I've created a small Javascript app that serves as a to-do list. The frontend is built in basic Javascript, fetching data from an array and allowing users to add items to the list through post requests. The intended functionality includes the ability ...

Expanding containers with flexbox to allow for flexibility in size

I need help with a page that contains 3 div elements, where 2 of them need to be resizable. These elements should be able to be moved left or right, and maximized or minimized. You can view the example on Stackblitz. The issue I'm facing is that som ...

Ways to turn off textarea resizing

Is there a way to prevent horizontal resizing on a textarea while still allowing vertical resizing? I find that the textarea often disrupts the design of my contact us page. If anyone has a solution for disabling the horizontal resize feature, please shar ...

Transferring information from one webpage to another using AJAX or embedding it with an iframe

I recently received an address with a basic HTML structure containing numbers. I attempted to display it using an iframe, which worked when tested separately but encountered a connection refusal error when embedded in my page. Alternatively, I tried AJAX ...

"Encountering issues with $http.get() function in my controller while trying to

Currently, I am working on an Application that utilizes Angularjs. I am trying to call an API and retrieve data using $http.get(). However, I am facing an issue where my API url does not seem to work properly. Interestingly, when I use a URL from a tutoria ...

Uninterrupted text streaming with dynamic content that seamlessly transitions without any gaps

I'm currently facing a challenge with an outdated element like <marquee>. Here's a fiddle where you can check it out: https://jsfiddle.net/qbqz0kay/1/ This is just one of the many attempts I've made, and I'm struggling with two m ...

node-fetch fails to catch HTTP errors

I am encountering issues with handling fetch exceptions in Node.js What I am anticipating to occur is: An HTTP error happening within my fetch call The CheckResponseStatus function running and throwing an error with the server error status and text This e ...

Is it possible to alter the css twice through the action of clicking on two individual buttons

One feature I have in my interface allows users to click on the edit button to bring up borders and change the background color of other divs. Once the edit button is pressed, it is replaced by cancel and save buttons. The goal is for the borders and backg ...

What is the best way to conditionally update all subdocuments in MongoDB?

{ _id: UniqueObjectId(), creatures: [ { kind: "dog", IQ: 100 }, { kind: "cat", IQ: 110 }, { kind: "bear", IQ: 120 }, ... ] } What is the best approach to construct an updateOne query in order to mo ...

How can I set a specific value for a variable that is located within an array?

For instance: var x = y = z = null; var list = [x, y, z]; var number = 10; Is there a way to assign number to x using list, without replacing list[0]? ...