Dynamically Change Styles
Now that we understand how to add and remove elements, it is time to give a special touch to our pages by changing styles dynamically. Let’s learn how to do this in an easy and effective way.
Changing Colors with Style
The most direct way to change the style of an element is through the style property. Let’s see an example of how to change the color of an element:
// Finding the desired item var myElement = document.getElementById('myElement'); // Changing background color to red MyElement.style.backgroundColor ='red';
Here, we access the element’s style property and modify its background color directly. Simple, isn’t it?
Modifying Dimensions with style
We can do more than just change colors. If we want to adjust the dimensions of an element, such as width and height, we can also use style:
// Modifying element width MyElement.style.width = '200px'; // Modifying element height MyElement.style.height = '100px';
This approach allows us to adjust the layout of the page dynamically.
Animations with style and setTimeout
Let’s give a more interactive touch by adding a simple animation using setTimeout:
// Adding an animation class MyElement.classList.add('animation'); // Removing class after 1 second for animation to occur setTimeout(function() { MyElement.classList.remove('animation'); }, 1000);
Here, we add a class that contains an animation and remove that class after a second to create an animated effect.
Example to improve understanding
Let’s improve our understanding of dynamic style change with a more complete example. In this example, we will have a button that, when clicked, will change the background color of an element and apply an animation. Let’s go.
Basic HTML:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Style Manipulation Example</title> <link rel="tylesheet" href="styles.css"> </head> <body> <div id="myElement">This is my element</div> <button onclick="changeStyle()">change Style</button> <script src="script.js"></script> </body> </html>
CSS (styles.css):
#myElement { width: 200px; height: 100px; background-color: lightblue; transition: background-color 0.5s ease; } .animation { animation: highlight 1s ease; } @keyframes highlight { 0% {transform: scale(1); } 50% {transform: scale(1.2); } 100% {transform: scale(1); } }
JavaScript (script.js):
function changeStyle() { // Finding the desired item var myElement = document.getElementById('myElement'); // Changing background color to yellow myElement.style.backgroundColor = 'yellow'; // Adding animation class MyElement.classList.add('animation'); // Removing class after 1.5 seconds for animation to occur setTimeout(function() { MyElement.classList.remove('animation'); }, 1500); }
Visualization