Highlight with CSS Transition + JS

You can combine css transitions with javascript in order to highlight an element and fade the highlight out over e.g. 2 seconds while the actual style of the element is reverted quickly to the original state.

Here is a quick example:

Try it out live here: https://leovt.github.io/leovt/highlight.html

The animation is controlled by the browser, you do not have to worry about what happens when the animation is finished, to reset all sttyles properly:

The code works as follows:

  1. The normal style of the element contains a rule for the transition from the highlighted state back to the original.
  2. The highlighted style disables the transition, so as to immediately highlight without any delay.
  3. When clicking the button the highlighted state is set, and (almost) immediately reset with a setTimeout callback.

Define the normal style of the element and the highlighted state:

      .score {
        transition: all 1.5s ease-out;
        background: lightblue;
      }

      .score.hit {
        transition: none;
        background: crimson;
        color: white;
      }

The event handler for the button click is very simple. Note the timeout uses a delay of 50ms. With a delay of 0ms I could not get a reliable result, it seems the change to .hit and back was so fast the engine could not register it properly.

      function addPoints() {
        var element = document.getElementById('sc1');
        element.innerText = (+element.innerText) + 100;
        element.classList.add('hit');
        window.setTimeout( () => element.classList.remove('hit'), 50);
      }

The example as a self-contained page: https://github.com/leovt/leovt/blob/master/highlight.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: