JavaScript UI: Shake Element

By Xah Lee. Date: . Last updated: .

This page shows you how to shake a HTML element using JavaScript.

here's the HTML code:

<button id="id69917">shake</button>

here's the JavaScript code:

//-*- coding: utf-8 -*-
// 2013-07-10, 2018-05-27
// Copyright 2018 by Xah Lee
// JavaScript UI: Shake Element http://xahlee.info/js/js_shake_box.html

// code originally based on
// JavaScript Book by David Flanagan
// http://xahlee.info/comp/js_book_man_made_complexity.html

const shake = ((e, distance = 5, duration = 500) => {
       // shake element e left and right.
    const originalStyle = e.style.cssText;
    e.style.position = "relative";
    const startTime = (new Date()).getTime();

    const animateIt = (() => {
        const now = (new Date()).getTime();
        const elapsedTime = now - startTime;
        const fraction = elapsedTime/duration;

        if (fraction < 1) {
        let x = distance * Math.sin(fraction*4*Math.PI);
            e.style.left = x + "px";
            setTimeout(animateIt, Math.min(25, duration - elapsedTime));
        }
        else {
            e.style.cssText = originalStyle;
        }
    });

    animateIt();

});

document.getElementById("id69917").addEventListener("click", ((e) => {  shake(e.target) }) , false);

The code is based on [JavaScript Definitive Guide (6th ed.) By David Flanagan. @ Buy at amazon ]

[see JavaScript Book by David Flanagan, and the Man-made Complexity in Computer Language]

JavaScript Fancy UI Examples

  1. JS: Image Rollover
  2. JS: Pop-up New Window
  3. JS: Digital Clock
  4. JS: Stopwatch
  5. JS: Fade a Element
  6. JS: Fade a Element Using CSS Transition
  7. JavaScript UI: Shake Element
  8. JS: How to Create Tooltip
  9. JS: Falling Snow Effect
  10. JavaScript: Floating Box Following Scroll
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.