style. color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id . You could also use setAttribute(key, value) to set a style on an element.
If you want to change the CSS styles dynamically you'll have to attach this portion of code to some event. For example, if you want to change the styles of your element when clicking on a button, then you have to first listen to the click event and attach a function containing the previous code.
The HTML DOM allows JavaScript to change the style of HTML elements.
Like we saw in the introduction, we have two ways to alter the style of an element using JavaScript. One way is by setting a CSS property directly on the element. The other way is by adding or removing class values from an element which may result in certain style rules getting applied or ignored.
The JavaScript style names are WebkitTransformOrigin
and WebkitTransform
element.style.webkitTransform = "rotate(-2deg)";
Check the DOM extension reference for WebKit here.
Here are the JavaScript notations for most common vendors:
webkitProperty
MozProperty
msProperty
OProperty
property
I reset inline transform styles like:
element.style.webkitTransform = "";
element.style.MozTransform = "";
element.style.msTransform = "";
element.style.OTransform = "";
element.style.transform = "";
And like this using jQuery:
$(element).css({
"webkitTransform":"",
"MozTransform":"",
"msTransform":"",
"OTransform":"",
"transform":""
});
See blog post Coding Vendor Prefixes with JavaScript (2012-03-21).
Try using
img.style.webkitTransform = "rotate(60deg)"
If you want to do it via setAttribute
you would change the style
attribute like so:
element.setAttribute('style','transform:rotate(90deg); -webkit-transform: rotate(90deg)') //etc
This would be helpful if you want to reset all other inline style and only set your needed style properties' values again, BUT in most cases you may not want that. That's why everybody advised to use this:
element.style.transform = 'rotate(90deg)';
element.style.webkitTransform = 'rotate(90deg)';
The above is equivalent to
element.style['transform'] = 'rotate(90deg)';
element.style['-webkit-transform'] = 'rotate(90deg)';
To animate your 3D object, use the code:
<script>
$(document).ready(function(){
var x = 100;
var y = 0;
setInterval(function(){
x += 1;
y += 1;
var element = document.getElementById('cube');
element.style.webkitTransform = "translateZ(-100px) rotateY("+x+"deg) rotateX("+y+"deg)"; //for safari and chrome
element.style.MozTransform = "translateZ(-100px) rotateY("+x+"deg) rotateX("+y+"deg)"; //for firefox
},50);
//for other browsers use: "msTransform", "OTransform", "transform"
});
</script>
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