JSFiddle - React, Tailwind, and code Playground
by Pankaj Patel
HTML
<div class="red"></div>
<div class="green"></div>
CSS
.red {
height: 100px;
width: 100px;
margin: 20px;
background-color: red;
}
.green {
height: 100px;
width: 100px;
margin: 20px;
background-color: green;
}
JavaScript
var shakingElements = [];
var shake = function (element, magnitude = 16, angular = false) {
//First set the initial tilt angle to the right (+1)
var tiltAngle = 1;
//A counter to count the number of shakes
var counter = 1;
//The total number of shakes (there will be 1 shake per frame)
var numberOfShakes = 15;
//Capture the element's position and angle so you can
//restore them after the shaking has finished
var startX = 0,
startY = 0,
startAngle = 0;
// Divide the magnitude into 10 units so that you can
// reduce the amount of shake by 10 percent each frame
var magnitudeUnit = magnitude / numberOfShakes;
//The `randomInt` helper function
var randomInt = (min, max) => {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
//Add the element to the `shakingElements` array if it
//isn't already there
if(shakingElements.indexOf(element) === -1) {
//console.log("added")
shakingElements.push(element);
//Add an `updateShake` method to the element.
//The `updateShake` method will be called each frame
//in the game loop. The shake effect type can be either
//up and down (x/y shaking) or angular (rotational shaking).
if(angular) {
angularShake();
} else {
upAndDownShake();
}
}
//The `upAndDownShake` function
function upAndDownShake() {
//Shake the element while the `counter` is less than
//the `numberOfShakes`
if (counter < numberOfShakes) {
//Reset the element's position at the start of each shake
element.style.transform = 'translate(' + startX + 'px, ' + startY + 'px)';
//Reduce the magnitude
magnitude -= magnitudeUnit;
//Randomly change the element's position
var randomX = randomInt(-magnitude, magnitude);
var randomY = randomInt(-magnitude, magnitude);
element.style.transform = 'translate(' + randomX + 'px, ' + randomY + 'px)';
//Add 1 to the counter
counter += 1;
...