Shake button

by Brain Shi

HTML

<button id="shaker" onclick="animate(this, 1000)">Shaker here</button>

JavaScript

function animate(_e, _time) {
    if (typeof (_e) === "string") _e = document.getElementById(_e);
    if (!_time) _time = 1000;
    var originalStyle = _e.style.cssText;

    _e.style.position = "relative";
    var timer = 0;
    var distance = 5;
    var tempTime = setInterval(function () {
        shake(_e, timer, distance);
        timer += 5;
        if (timer >= _time) {
            clearInterval(tempTime);
            _e.style.cssText = originalStyle;
        }
    }, 5);


}

function shake(_e, _timer, distance) {
    x = distance * Math.random() * Math.pow(-1, _timer);
    y = distance * Math.random() * Math.pow(-1, _timer);
    _e.style.left = x + "px";
    _e.style.top = y + "px";

}