I'm trying to apply various transforms to a given element or set of elements by clicking buttons to toggle classes on and off. This works for most things, but not when I try to toggle on more than one rotate transform. Once an element has two separate rotate transform classes (rotateX, rotateZ), the transforms stop working as I expect.
Please see my example here: http://jsfiddle.net/XTVd7/9/
CSS
#box {
width: 100px;
height: 100px;
border: 1px solid blue;
transition: all 1s;
}
.flip {
-webkit-transform: rotateX(360deg);
-moz-transform: rotateX(360deg);
-ms-transform: rotateX(360deg);
-o-transform: rotateX(360deg);
}
.spin {
-webkit-transform: rotateZ(360deg);
-moz-transform: rotateZ(360deg);
-ms-transform: rotateZ(360deg);
-o-transform: rotateZ(360deg);
}
jQuery
$("#flipBtn").on("click", function() {
$("#box").toggleClass("flip");
});
$("#spinBtn").on("click", function() {
$("#box").toggleClass("spin");
});
I'd expect that I could flip or spin the box at any time by toggling either class on or off. This is not the case once both classes have been added to it.
The transform property can be given multiple values that are applied one after another.
Add CSS. Use a loaded image for the background property and specify the width, height, and border properties. Add the transform property with two of its values: rotate and translate.
The matrix transform function can be used to combine all transforms into one.
transformation: translate(0,10%) rotate(25deg); The rotate operation is done first, then the translate .
If you want to toggle multiple values for the same property, you have to manually construct the property text (fiddle):
function createToggleFunction(element$) {
var transforms = {
flip: 'rotateX(120deg)',
spin: 'rotateZ(180deg)',
};
var state = {};
return function(transform) {
state[transform] ^= true;
var text = "";
for(var key in transforms) {
if(state[key]) text += transforms[key] + ' ';
}
element$.css('transform', text);
};
}
var toggle = createToggleFunction($('#box'));
$("#flipBtn").on("click", function() {
toggle('flip');
});
$("#spinBtn").on("click", function() {
toggle('spin');
});
A simpler solution would be to have two nested elements to represent the "box", with one of the transformations applying to the outer one and one applying to the inner one:
(See this edited version of jblasco's fiddle)
#spinner {
width: 100px;
height: 100px;
transition: all 1s;
}
#flipper {
width: 100%;
height: 100%;
transition: all 1s;
border: 1px solid blue;
}
HTML:
<div id="spinner">
<div id="flipper">
a
</div>
</div>
JQuery:
$("#flipBtn").on("click", function() {
$("#flipper").toggleClass("flip");
});
$("#spinBtn").on("click", function() {
$("#spinner").toggleClass("spin");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With