Can you guide me on implementing a transition animation through class toggling?

I am facing an issue where certain elements need to be highlighted or unhighlighted conditionally. To achieve this, I have assigned a class called highlight to the elements that require highlighting with a transition animation.

The challenge arises when trying to animate the removal of the highlight class from elements. Since any element could potentially be highlighted, it is difficult to find a specific selector for them.

One workaround could be applying the transition property to all elements, but this solution does not feel optimal:

* {
  transition: background-color 1s;
}

Is there a more efficient way to address this issue? Below is a simplified example illustrating the problem:

[...document.querySelectorAll('body *')].forEach(e => e.addEventListener('click', () => e.classList.toggle('highlight')));
.highlight {
  background-color: red;
  transition: background-color 1s;
}
<h2>Click anything to toggle highlight</h2>

<p>Hello</p>
<p>World</p>
<p>Thanks</p>

Answer №1

Approach the problem with a different mentality

[...document.querySelectorAll('body *')].forEach(el => el.addEventListener('click', function(event) {
  event.target.classList.toggle('bg');
  event.target.classList.add('highlight'); /* always add highlight */
}));
/* remove highlight when the transition is completed */
[...document.querySelectorAll('body *')].forEach(el =>
  el.addEventListener('transitionend', function(event) {
    event.target.classList.remove('highlight');
  })
);
.highlight {
  transition: background-color 1s;
}

.bg {
  background: red;
}
<h2>Click anything to toggle highlight</h2>

<p>Hello</p>
<p>World</p>
<p>Thanks</p>

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

I am curious as to why the "default + label" pseudo-class is not functioning properly on the "input" element. Specifically, I am having trouble with the "+ label" portion

":default" works fine on its own, but when combined with the "label" pseudo-class, it fails to apply. .pseudo-test input:default { box-shadow: 0 0 20px 20px red; } .pseudo-test input:default+label { color: coral; } <div style ...

Is there a way to position the search bar on a new line within the navigation bar when the screen size is at its maximum width for mobile

I have a search bar on my navigation bar, but I am looking to move it to the next line within a maximum width if the screen display is extra small (xs) or for mobile devices. Below is the code snippet: <nav class="navbar navbar-expand-md fixed-top ...

Several DIVs with the same class can have varying CSS values

I am looking to modify the left-margin value of various separate DIVs using JavaScript. The challenge is: I only want to use a single className, and I want the margin to increase by 100px for each instance of the class. This way, instead of all the DIVs ...

CSS: the max-width property does not constrain an absolute positioned container from overflowing

I've been trying to figure this out for hours, but I can't seem to get it right. My top menu has submenus that include a popup menu. In one of my popups, I need the container to have a maximum width of 170 pixels and all the items inside to wra ...

I'm having trouble with my code not fitting all screen resolutions. I usually code on a Macbook, but recently switched to a Windows computer and now everything is out of whack

$(function(){ $("#Welcome").typed({ strings: ["PROGRAMMERS / NETWORKERS"], typeSpeed: 60 }); }); html { background-color: mintcream; background-size: 100%; } /* Home */ .homeheader button { background-color: #4CAF450; top: ...

Eliminate jQuery's delayed blinking effect with the use of an event

Utilizing the mouseenter and mouseleave events, I have implemented a functionality to add a button (not actually a button) to an <li>. However, there seems to be a problem with my code. The button appears and disappears on mouseleave and mouseenter, ...

GSAP also brings scale transformations to life through its animation capabilities

I have an SVG graphic and I'm looking to make four elements appear in place. I've been using GSAP, but the elements seem to be flying into place rather than scaling up. Here's the code snippet I've been using: gsap.fromTo( ...

Preventing special characters in an input field using Angular

I am trying to ensure that an input field is not left blank and does not include any special characters. My current validation method looks like this: if (value === '' || !value.trim()) { this.invalidNameFeedback = 'This field cannot ...

Automatically populate the next dropdown menu depending on the answer provided in the previous field

Can you help guide me in the right direction with 2 questions I have? If the answer to the first question is 1, then I would like the following answer to automatically be populated as Yes. Please assist me! <div class="field"> <!-- Number of Em ...

What is the best way to customize CSS in Material UI?

When working with material UI and reactjs, I encountered an issue while trying to override the button color without affecting the tab colors (see screenshot). How can I achieve this using themes in material UI? Code: const theme = createMuiTheme({ p ...

CSS based on conditions for 2 specific divs

Hello, I am working on an HTML page where I need to apply CSS only if certain conditions are met. The div with the id "flipbook-page3-front" will always be present on this HTML page. Sometimes, another div with the id "pagesFlipbook" may also appear on t ...

Separate the label and content sections in an Angular Material vertical stepper

After applying the following CSS: mat-step-header{ display: flex ; justify-content: flex-end ; } I am attempting to make this stepper function properly. I have implemented Angular Material design for a vertical stepper. How can I position the steppe ...

Get the value of an HTML element

Is there a way to retrieve the value of an HTML element using PHP or JavaScript, especially when the value is dynamically loaded from another source? I have tried using jQuery with the DOM ready event, but often encounter the issue where the element's ...

Enrollment in the course is conditional on two words being a perfect match

I have a concept in mind, but I'm struggling to piece it together. I have bits of different methods that just don't seem to align. That's why I'm reaching out for your expertise. Let's say I have 3 content containers with the clas ...

After swapping out "div" with "input" and then replacing "input" with

My goal is to create a function where a user can edit text within a div. The idea is to replace the current text with an editable input field, and then convert it back into a div after the user hits enter. I've encountered an issue while trying to im ...

What is the best way to save JavaScript array information in a database?

Currently working on developing an ecommerce website. My goal is to have two select tags, where the options in the second tag are dynamically populated based on the selection made in the first tag. For example, if "Electronics" is chosen in the first tag f ...

Experimenting with animating an element through onClick event using JavaScript

I would like to create an animated div using JavaScript that activates on click. <div class="Designs"> <p>Designs</p> <div class="Thumbnails" data-animation="animated pulse"> <a href=" ...

Is there a way to add a <video> tag in tinymce editor without it being switched to an <img /> tag?

I am attempting to include a <video> tag within the tinymce editor, but it keeps changing it to an <img> tag. Is there a way to prevent this conversion and keep the <video> tag intact? I want to enable videos to play inside tinymce whil ...

Turn off the automatic resizing of Internet Explorer 11 to fit the width of the viewport - IE11

Is there a way to stop Internet Explorer 11 from automatically zooming to fit the viewport width? I need the browser to respect my max-width rule and not scale the content to fill the entire width of the viewport on its own. This issue is happening in IE ...

Set the minimum height of a section in jQuery to be equal to the height of

My goal is to dynamically set the minimum height of each section to match the height of the window. Here is my current implementation... HTML <section id="hero"> </section> <section id="services"> </section> <section id="wo ...