Manipulating CSS animations through JQuery

Currently, my animation is triggered by a :hover event. However, I would like to change it so that the animation starts when a button is clicked. Can someone guide me on how to manipulate the CSS using JQuery?

//CSS

.mouth{
  top: 268px;
  left: 273px;
  position: relative;
}

.frame:hover .mouth {
  animation-name: talk;
  animation-duration: 0.75s;
  animation-iteration-count: 5;
}

@keyframes talk {
  0%, 100%{
    top: 268px;
    left: 273px;
  }

  50% {
    top: 308px;
    left: 273px;
  }
}

//JQuery

  $('#getQuote').click(function() {

  });

Answer №1

Swap out the :hover pseudo-class with a different class, then use jQuery to apply this new class to the element that was clicked.
By doing this, we ensure that when an item is clicked on, the extra class is included and the necessary conditions are met to activate the animation.

Answer №2

It's a simple process to achieve this effect. You will have to make some adjustments to your CSS code.

Instead of relying on the :hover selector, create a new class such as .StartAnimation. Update your CSS accordingly:

.StartAnimation .mouth{
    animation-name: talk;
    animation-duration: 0.75s;
    animation-iteration-count: 5;
 }

To apply or remove this class using JQuery, you can do the following:

$('#getQuote').click(function() {
    $('.frame').addClass('StartAnimation');
    // Toggle it if a second click should undo the animation
    // $('.frame').toggleClass('StartAnimation');
});

If you still want the hover effect but also need to trigger the animation with a button click, you can use the .trigger() method in JQuery. More information can be found here: http://api.jquery.com/trigger/

$('#getQuote').click(function(){
    $('.frame').trigger('mouseenter');
});

Answer №3

To initiate the animation, add a class and then use the animationend event to remove the added class so the animation can be triggered again.

$('#getQuote').click(function() {
  $('.mouth').addClass('animate');
});
$('.mouth').one('animationend', function(ev) {
  $('.mouth').removeClass('animate');
});
.mouth{
  top: 268px;
  left: 273px;
  position: relative;
  
  width: 100px;
  height: 100px;
  background-color: red;
}

.mouth.animate {
  animation-name: talk;
  animation-duration: 0.75s;
  animation-iteration-count: 5;
}

@keyframes talk {
  0%, 100%{
    top: 268px;
    left: 273px;
  }

  50% {
    top: 308px;
    left: 273px;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mouth"></div>
<button id="getQuote">Get Quote</button>

Answer №4

Here's an easy way to do it:

$('.mouth').style({
 '<property>':'<value>',
 '<property>':'<value>',
 '<property>':'<value>'...
});

Answer №5

To implement the talking animation, I recommend using a CSS class like this:

.smile.animated {
    animation-name: chatter;
    animation-duration: 0.75s;
    animation-iteration-count: 5;
}

For the JavaScript portion:

$( "#generateSmile" ).click(function() {
    $(this).prop('disabled', true); // Disabling to prevent animation from being restarted
    $(".smile").addClass("animated");
    setTimeout(function(){
        $( "#generateSmile" ).prop('disabled', false);
        $(".smile").removeClass("animated");
    }, 750*5)
});

Answer №6

My typical approach to this situation is as follows:

//CSS
.animation{
   ......
}

//JavaScript (using jQuery)
var animationTimer;
$('#getQuote').click(function() {
    clearTimeout(animationTimer);
    $('.mouth').addClass('animation');
    animationTimer = setTimeout(function(){
        $('.mouth').removeClass('animation');
    }, 'duration of animation in milliseconds')
});

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 entire title serves as a hyperlink, not just the text portion

Apologies if I'm making mistakes, I'm just starting out with coding and navigating this website. So here's the deal: I am trying to add advertisements to my website on the left and right sides of the centered "Logo" at the top. The issue i ...

Submitting a specific group of form inputs using ajax involves selecting the desired elements within the form

My task involves dealing with a large form that needs to be submitted in PHP, which poses a challenge due to the maximum input variable limits in PHP +5.3 as discussed on this Stack Overflow thread. Instead of submitting everything from the form, I only n ...

Program that duplicates text to clipboard upon clicking on the text

Hey there, I have a query regarding the script provided below: function copyElementText(id) { var text = document.getElementById(id).innerText; var elem = document.createElement("textarea"); document.body.appendChild(elem); ...

Top method for independently scrolling overlapping elements in both the x and y directions

Sorry if this is repeating information. I have a structure of nested divs like this: -container -row In order to enable scrolling without the default scrollbar appearing, each container and row has an additional container. My goal is to be able to scrol ...

What is the most efficient way to handle dependencies and instantiate objects just once in JavaScript?

I am interested in discovering reliable and tested design patterns in Javascript that ensure the loading of dependencies only once, as well as instantiating an object only once within the DOM. Specifically, I have the following scenario: // Block A in th ...

Struggles with Managing 5-Digit Unicode Characters with jQuery

I need some assistance with using larger Unicode images in JQuery, as I am encountering difficulties that I cannot seem to resolve. For example, when I use the following line of code: if ( IsItOverFlowing() ) { $HM.text("\u2302"); } a charming litt ...

AJAX in jQuery cannot be used to send data to a PHP

I am facing an issue with my script that uses AJAX to post data to the server and display it, but unfortunately, it is not functioning properly... Here is the current output: Your viewport width is 1332x670 Ajax initialization failed! In this scenario, ...

A React component enclosed within a useCallback function

According to the React docs, to prevent a Child component from re-rendering in certain cases, you need to wrap it in useMemo and pass down functions in useCallback within the Parent component. However, I'm confused about the purpose of this implementa ...

When Vue.js Vuex state changes, the template with v-if does not automatically refresh

I have tried setting the v-if value in computed, data, passing it as props, and directly referencing state, but it never seems to re-render despite the fact that the state I am checking for is changed to true. Currently, I am directly referencing the stor ...

Using Jquery to add new HTML content and assign an ID to a variable

Here is some javascript code that I am having trouble with: var newAmount = parseInt(amount) var price = data[0]['Product']['pris']; var id = data[0]['Product']['id']; var dat ...

The navigation bar buttons in my IONIC 2 app are unresponsive on both the

In Ionic 2 for Android, I encountered an issue with the title placement. To resolve this, I applied some CSS to center the title and added left and right buttons to the nav bar. However, when I tried to implement onclick functionality for these buttons, no ...

Preventing a JavaScript timer function from executing multiple times when triggered by an 'in viewport' function

I am trying to create a website feature where a timer starts counting up once a specific div is scrolled into view. However, I am encountering an issue where scrolling away restarts the timer, and I would like the final value that the timer reaches to rema ...

A guide on aligning a CSS item perfectly in the center using absolute positioning

I have been searching for a solution to my problem, but all I found were answers that addressed similar issues in a slightly different way. My challenge involves placing multiple smaller images on top of a larger background image. To achieve this, I utili ...

Unable to display Polygon using ReactNativeMaps

Having trouble displaying the polygon correctly on my screen. I suspect it's due to receiving an array of objects from my API. This is the code snippet in question: <MapView.Polygon coordinates={poligonofinale} strokeColor="#000" fillColor= ...

Retrieve the most recent score of authorized players using the Google Game API and Node.js

How can I display the last score of a specific game using the Google Play Game API? For example, I am looking to retrieve the latest scores of authenticated users playing "Rush Fight" with NodeJS. Any suggestions on how to achieve this? ...

"Feeling puzzled by the intricacies of the Jquery Timer

I am currently using the jQuery Timer plugin from to dynamically generate documents every 5 seconds with pause and resume functionality. Below is my script: $(function() { $('.handler').load("../Pages/csFetchCustomer.ashx?"); ...

``Are there any thoughts on how to troubleshoot display problems specifically on mobile

Whenever I use Safari on iOS for my web application, I encounter strange rendering issues. It's odd because the majority of the time everything functions as it should, but every now and then these bugs crop up with no discernible pattern. Examples th ...

Implementing Object Value Assignment to an Element Using jQuery

I recently received a set of data via an API request: https://i.stack.imgur.com/YGe2D.jpg In order to display this data as selectable options, I included the following code snippet in my AJAX script: $.each($(value.routes), function(index, route){ $ ...

I keep encountering the following issue: "It seems that the file requested at /images/crown.png is not recognized as a valid image, as it was received as text/html; charset=utf-8."

I encountered an issue while utilizing Next.js. Here is the code snippet where the error occurred: import React from "react"; import { Container, Col, Row } from "react-bootstrap"; import Image from "next/image"; export defaul ...

Is there a way to trigger jQuery animations even when the browser window is not in focus?

Hi there, I am currently working on developing an ajax-based multiplayer game that connects to a server for updates. The game has various game states and requires the GUI to be animated accordingly. However, I have encountered a problem where jquery anima ...