CSS Manipulation
With Javascript we can manipulate the CSS of any element of the page. For this, we just need to use the style property of the elements.
The style property is an object that has the CSS properties.
<button id="color_button">Click here to change color and move it to the right</button>
document.getElementById("color_button").onclick = function() {
document.getElementById("color_button").style['background-color'] = "purple";
document.getElementById("color_button").style.transform = "translateX(100px)";
};
/* Since the background-color property does not folow the variable name rules, we need to use braces to access it. */
By using the keyword this we can simplify our code:
document.getElementById("color_button").onclick = function() {
this.style['background-color'] = "purple";
this.style.transform = "translateX(100px)";
};
// We can also simplify it by creating a variable and assigning the HTML element to it:
var button = document.getElementById("color_button");
button.onclick = function() {
button.style['background-color'] = "purple";
button.style.transform = "translateX(100px)";
};