Implement a CSS animation for the h1 element when a button is clicked, with the help of either JQuery

Hey there! I have a heading (h1) and a button on my webpage. I've created a cool animation using CSS that I want to apply to the h1 when the button is clicked using JQuery.

The idea is that when the button is clicked, the animation should add more content to the h1 element. The problem is, currently the animation starts as soon as the HTML loads, but I want it to start only when the button is clicked.

Since I'm still learning these skills, I find complex answers confusing. Could someone please guide me through this?

Below is the snippet of HTML code:

<div class="container-fluid center" id="mainPage">
    <div id="heading" class="row">
        <h1 id="wishH1">NAME!</h1>
    </div>
</div>
<div class="container-fluid center" id="gift">
    <button type="button" id="giftButton">
        <img id="giftImg" src="gift.png">
    </button>
</div>

And here's how the CSS looks like:

@keyframes wish {
  25% {
    content: : "hi ";
  }
  50% {
    content: : "hello ";
  }
  75% {
    content: "hola ";
  }
}

#wishH1::before {
  content: "hey there ";
  animation: wish 20s linear infinite;
}

Additionally, this is the JQuery script I've tried:

I've made multiple attempts with different comments in the code block below but none seem to work. They either don't trigger the animation or start automatically without waiting for the button click.

$('#giftButton').click(function() {
  $("#gift").fadeOut(1500);

  // Various attempts to start the animation after clicking the button
  /*$("#wishH1").css("animation",wish);
    $("#wishH1").css("animation-duration",6s);
    $("#wishH1").css("animation-timing-function",linear);
    $("#wishH1").css("animation-iteration-count",infinite);*/
  
  setTimeout(function() {
    $("#gift").fadeIn(1500);
  }, 20000);
});

This is how the h1 changes during the animation:

hey there NAME!

hi NAME!

hello NAME!

hola NAME!

If anyone can help me understand what adjustments need to be made in the JQuery code or if any changes are required in the CSS for the desired output, I would greatly appreciate it. Thank you!

Also, apologies if my question isn't clear enough, it's my first time asking one. Thank you for your patience.

Answer №1

In order to trigger the animation after a click event, you cannot directly target pseudo elements (such as ::before) in jQuery since they are not part of the DOM. Instead, you can apply a specific class (animation-start) to the parent element and manipulate its pseudo elements using CSS.

$('#giftButton').click(function() {
  $("#gift").fadeOut(1500);
  $('#wishH1').addClass('animation-start');
  setTimeout(function() {
    $("#gift").fadeIn(1500);
  }, 20000);
});
@keyframes wish {
  25% {
    content: "hi ";
  }
  50% {
    content: "hello ";
  }
  75% {
    content: "hola ";
  }
}

#wishH1::before {
  content: "hey there ";
}

#wishH1.animation-start::before {
  animation: wish 5s linear infinite;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container-fluid center" id="mainPage">
  <div id="heading" class="row">
    <h1 id="wishH1">NAME!</h1>
  </div>
</div>
<div class="container-fluid center" id="gift">
  <button type="button" id="giftButton">
        <img id="giftImg" src="gift.png">
    </button>
</div>

The issue with extra semicolons in your CSS could have been causing some problems for you.

@keyframes wish{
25%{
    content:: /* here */ "hi "; 
}
50%{
    content:: /* here */ "hello "; 
}
75% {
    content: "hola ";
}

Answer №2

The issue lies in the CSS code where the animation is directly set, instead of adding it on click.

You should modify it to something like this:

CSS

@keyframes greeting{
25% {
    content: "hi ";
}
50% {
    content: "hello ";
}
75% {
    content: "hola ";
}
}
#wishH1::before {
  content: "hey there ";
}

#wishH1.active::before {
  animation: greeting 2s linear infinite;
}

JavaScript

$('#giftButton').click(function(){
$('#wishH1').addClass('active');
$("#gift").fadeOut(1500);
setTimeout(function() {
  $("#gift").fadeIn(1500);
    $('#wishH1').removeClass('active');
}, 20000);
});

Answer №3

CSS

<style>
  h1 {
    color: blue;
    font-size: 24px;
  }

JAVASCRIPT

let interval;
let i = 0;
let colors = ['red', 'green', 'blue'];

$('#changeColor').on("click", function () {
  interval = setInterval(function () {
    if (i >= colors.length) {
      i = 0;
    }
    $('h1').css('color', colors[i]);
    i++;
  },
    1000);
})

HTML

<h1 id="changeColor">Change My Color!</h1>
<button type="button" id="colorButton">Click Me</button>

Answer №4

Although it's not possible to directly manipulate the style of a pseudo element using Javascript, you can achieve the desired effect by setting a CSS variable on the actual element which will be reflected in the pseudo element.

To start off, we set --name: none and then use Javascript (or jquery) to update the CSS variable to wish triggering the animation.

document.querySelector('button').addEventListener('click', function () {
  document.querySelector('#wishH1').style.setProperty('--name', 'wish');
});
@keyframes wish{
25%{
    content: "hi ";
}
50%{
    content: "hello ";
}
75% {
    content: "hola ";
}
}

#wishH1 {
  --name: none;
}
#wishH1::before {
  content: "Hey there ";
  animation: var(--name) 20s linear infinite;
}
<div class="container-fluid center" id="mainPage">
    <div id="heading" class="row">
        <h1 id="wishH1">NAME!</h1>
    </div>
</div>
<div class="container-fluid center" id="gift">
    <button type="button" id="giftButton">
        <img id="giftImg" src="gift.png">
    </button>
</div>

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

Necessity of "position: relative" in Bootstrap 4 Scrollspy

According to the Bootstrap 4 website, Scrollspy has certain requirements for use. One of these requirements is that "Scrollspy requires position: relative on the element you’re spying on, usually the ." Interestingly, it appears that Scrollspy can still ...

What is the best way to keep a header row in place while scrolling?

I am looking to keep the "top" row of the header fixed or stuck during page scrolling, while excluding the middle and bottom rows. I have already created a separate class for the top row in my header code: view image description ...

Triggering a JavaScript function when the mouse moves off an element

Recently, I created the following code snippet for marquee effect. The main functionality it is missing is triggering a function on mouse-over. <marquee class="smooth_m" behavior="scroll" direction="left" scrollamount="3"> <span style="float:le ...

What are the steps to resolve the error 'content-type missing boundary' and encountering the issue with getBoundary not being recognized as a function?

fetchCarouselData: async (params) => { let bodyFormData = new FormData(); for (let prop in params) { bodyFormData.append(prop, params[prop]); } return axios({ method: "post", url: `${baseURL}/fetchCarouselData`, data: b ...

The expected functionality of padding in a wrapper/parent element is not being achieved

https://i.sstatic.net/7CuKj.png I am currently utilizing React and have integrated a piano component (from an external library) that is responsive. Within my application, I have implemented 3 different "levels" that determine the ranges of the piano - esse ...

In an HTML form, there are two fields to input registration number and full name. I need a script in JavaScript that automatically fills in the full name field when the corresponding registration number is entered

<html> <head> <title>Registration Form</title> </head> <body> <form> <!--at runtime, fill in the full name when the user enters a registration number associated with their name--> Registration ...

The challenge of handling Set type in TypeScript errors

I'm currently facing two errors while trying to convert a function to TypeScript. The issue lies with the parameters, which are of type Set import type {Set} from 'typescript' function union<T>(setA: Set<T>, setB: Set<T>) ...

Another option instead of using the .siblings() method would be

Is there an alternative to using the .siblings() method in jQuery for traversing through divs of a specific class in separate container divs? How can this be achieved with the following code: HTML: <div id="container1"> <div id="1"></di ...

Converting JSON data retrieved from a URL into HTML format

I have a JSON output from a URL that I need to format into html. The structure of the JSON data is as follows: prtg-version "xxxxxxx" treesize 0 channels 0 name "Downtime" name_raw "Downtime" lastvalue "" lastvalue_raw "" 1 name ...

JavaScript: organizing data by category with summarization

I have a basic JSON list provided below: { "myList": [ { "endOfPeriod": 1461362400000, "rate": 0.03726378 }, { "endOfPeriod": 1461535200000, "rate": 0.03726378 }, { "endOfPeriod": 1461967200000, ...

Transitioning in Vue.js can be triggered by changing a value up or down

My current transition block component is set up like this: <div v-if="!surveyResultIsReady" class="vh-md-40 position-relative" > <transition name="custom-classes-transition" enter-active-class="animated slideInRight" ...

Encountering "Error: Class constructor vA cannot be invoked without 'new'" when using Angular 10 Kendo Grid

I am currently working on integrating a Kendo Grid into my Angular application. However, I have run into an error when enabling the Kendo Grid component: vendor.4add67dadae0cd9152b9.js:16 ERROR Error: Uncaught (in promise): TypeError: Class constructor vA ...

Making changes to a JSON File

I've been attempting to integrate a jQuery gantt chart into my WordPress website as a plugin. However, I've hit a roadblock when it comes to editing the data.json file. My approach involves using a PHP form to add a new item. Upon form submission ...

Discover a faster way to access object properties suggestions in vscode similar to Chrome console

When using Chrome DevTools, selecting an element will display its corresponding properties and methods that can be accessed with a dot (.). However, in VSCode, this information may appear as gibberish. Is there a way to get the same suggestions as Chrome D ...

PHP and HTML form: The ultimate guide to sending emails through your website

Currently, I am in the process of learning PHP and attempting to send an email to myself using an HTML form. However, I am experiencing some difficulties. <form action="index.php" role="form" method="post" name="emailform"> ...

"Share your social media profiles without redirecting users to new tabs

Currently in the process of launching my own website using the free Portra theme. So far, everything has been going smoothly with this widget free template. However, I have encountered an issue with my social links opening in the same window. I would prefe ...

Problem with personalized Domino login page

I have been working on creating a custom login page in domcfg.nsf. Everything is functioning as expected, except for the Style Sheets. I am attempting to load them from the same Domino server, but it appears they are unable to load until I actually log in ...

What's the best way to maintain the return type of a function as Promise<MyObject[]> when using forEach method?

I am currently working with a function called search, which at the moment is set up to return a type of Promise<MyObject[]>: export function search(args: SearchInput) { return SomeInterface.performSearch(args) .then(xmlRequest =&g ...

Having issues retrieving tweets from my Twitter account, even though I am able to successfully post tweets

I've been attempting to retrieve tweets from my Twitter account using the Twitter API, but I keep encountering errors with all combinations failing. Despite having all the necessary node_modules and everything appearing to be in order, I still receive ...

Alignment of text to the left can be achieved by using either relative or absolute

After researching several solutions, none seem to solve the issue I am experiencing. My code is meant to create two red colored boxes as shown below: .redboxes-horz { width: 100%; margin-bottom: 50px; height: auto; top: 0; right: 0; } ...