JSFiddle - React, Tailwind, and code Playground
HTML
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<p>On clicking the first button, we first make a copy of the current inline styles of each div (in the form of a CSSStyleDeclaration) and then make some random changes to the divs' width and height attributes.</p>
<button id="alterStyleAttribute">1. Make some changes to the elements' inline styles</button>
<p>Reset the divs' style back to how they were before the first button was pressed.</p>
<button id="resetStyleAttribute">2. Replace the "style" attribute</button>
CSS
.test {
transition: opacity 1s;
-webkit-transition: opacity 1s;
width: 50px;
height: 50px;
background-color: #f00;
margin: 5px;
}
JavaScript
var i = 0;
var originalStyles = [];
function tick() {
// Here is the JavaScript-based animation
x = (Math.sin(i / 100) + 1) * 200;
$('.test').css('margin-left', x + 'px');
requestAnimationFrame(tick);
i++;
if (i % 120 === 0) {
$('.test').css('opacity', 1);
} else if (i % 60 === 0) {
$('.test').css('opacity', 0);
}
}
requestAnimationFrame(tick);
/*
* Set the "transition-delay" property inline, and make a copy of the current inline styles
* of each div (in the form of a CSSStyleDeclaration) for later use.
*/
var delay = 0.1;
$.each($('.test'), function (index, el) {
$(el).css('transition-delay', delay + 's');
$(el).css('-webkit-transition-delay', delay + 's');
delay += 0.2;
// The cloneNode() method is needed as otherwise the CSSSStyleDeclaration
// object is copied by reference, and will change whenever we change the
// divs' inline style. Cloning makes a new copy that is no longer linked to the
// current div.
originalStyles[index] = el.cloneNode().style;
});
/**
* On clicking the first button, we make some random changes
* to the divs' width and height attributes.
*/
$('#alterStyleAttribute').on('click', function () {
$.each($('.test'), function (index, el) {
$(el).css('width', Math.random() * 100 + 'px');
$(el).css('height', Math.random() * 100 + 'px');
});
});
/*
* Reset the divs' style back to how they were before
* the first button was pressed.
*/
$('#resetStyleAttribute').on('click', function () {
$.each($('.test'), function (index, el) {
// first we need to delete all the style rules
// currently defined on the element
for (var i = el.style.length; i > 0; i--) {
var name = el.style[i];
el.style.removeProperty(name);
}
// now we loop through the original CSSStyleDeclaration
// object and set each property to its original value
var styleObject =...