Note the transform
property can have different values, which are not commutative. For example, the following values produce different results:
transform: translateX(100px) rotate(90deg); /* This is different... */
transform: rotate(90deg) translateX(100px); /* ... than this! */
.box {
height: 100px;
width: 100px;
background: red;
}
#box1 {
transform: translateX(100px) rotate(90deg);
}
#box2 {
transform: rotate(90deg) translateX(100px);
}
<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
One may think that rotating 45deg
more would be
transform: translateX(100px) rotate(135deg); /* OK */
transform: rotate(135deg) translateX(100px); /* FAIL! */
.box {
height: 100px;
width: 100px;
background: red;
}
#box1 {
transform: translateX(100px) rotate(135deg);
}
#box2 {
transform: rotate(135deg) translateX(100px);
}
<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
However, that would only work for the first example, because rotate
was the last transform function. In general, the proper way would be
transform: translateX(100px) rotate(90deg) rotate(45deg); /* OK */
transform: rotate(90deg) translateX(100px) rotate(45deg); /* OK */
.box {
height: 100px;
width: 100px;
background: red;
}
#box1 {
transform: translateX(100px) rotate(90deg) rotate(45deg);
}
#box2 {
transform: rotate(90deg) translateX(100px) rotate(45deg);
}
<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
Then, you can add this method:
$.fn.addTransform = function(val) {
return this.each(function() {
var tr = $(this).css('transform');
if(tr === 'none') tr = '';
$(this).css('transform', tr + ' ' + val);
});
};
And use it like
$('#move').addTransform('rotate(5deg)');
$.fn.addTransform = function(val) {
return this.each(function() {
var tr = $(this).css('transform');
if(tr === 'none') tr = '';
$(this).css('transform', tr + ' ' + val);
});
};
$('input').click(function() {
$('#move').css({
backgroundColor: 'aqua',
position: 'absolute',
transition: '500ms ease-in-out',
right: '-=50px'
}).addTransform('rotate(5deg)');
});
#move {
height: 70px;
width: 70px;
border: 2px solid black;
border-radius: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Move Right" />
<div id="move"></div>