Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 45 - Modifying CSS with JavaScript

In this lesson, we will explore how to dynamically change the styles of elements using JavaScript.


Why Modify CSS with JavaScript?

  • To create dynamic UI changes.
  • To apply styles based on user interactions.
  • To make elements responsive to events and conditions.

Modifying CSS Using style Property

Every HTML element in JavaScript has a .style property, allowing you to change its CSS.

Example 1: Changing Text Color

let heading = document.getElementById("title");
heading.style.color = "blue";

???? Changes the text color of the element with ID "title" to blue.


Example 2: Changing Multiple Styles

let box = document.getElementById("box");

box.style.width = "200px";
box.style.height = "200px";
box.style.backgroundColor = "lightblue";

???? This sets the box width, height, and background color dynamically.


Adding and Removing CSS Classes

Instead of modifying individual styles, you can add or remove CSS classes.

Example 3: Adding a Class

let button = document.getElementById("myButton");
button.classList.add("active");

???? Adds the "active" class to the button.


Example 4: Removing a Class

button.classList.remove("active");

???? Removes the "active" class from the button.


Example 5: Toggling a Class

button.classList.toggle("highlight");

???? If the "highlight" class is present, it removes it; otherwise, it adds it.


Try Your Hand

Steps:

  1. Create a File:

    • Name it lesson45-style.html.
  2. Write the Code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Lesson 45 - Modify CSS with JavaScript</title>
       <style>
           .highlight {
               background-color: yellow;
               font-size: 20px;
           }
       </style>
    </head>
    <body>
       <h2 id="title">Hello JavaScript!</h2>
       <button id="toggleBtn">Toggle Highlight</button>
    
       <script>
           let title = document.getElementById("title");
           let button = document.getElementById("toggleBtn");
    
           button.addEventListener("click", function() {
               title.classList.toggle("highlight");
           });
       </script>
    </body>
    </html>
  3. Save and Open in a Browser.

  4. Click the Button to Toggle the CSS Style!


Experiment

  1. Change the background color of a div when a button is clicked.
  2. Hide an element using .style.display = "none" and show it again.
  3. Modify the font size of a paragraph dynamically.

Key Takeaways

  • Modify styles using .style.propertyName(e.g: elem.style.color='red')
  • Use .classList.add(), .classList.remove(), and .classList.toggle().
  • Efficiently manage CSS styles without modifying the HTML structure.