Connect with us

CSS

How to Change CSS Using JavaScript?

Spread the love

JavaScript allows developers to dynamically manipulate CSS styles to create interactive and responsive web applications. Whether you need to update colors, hide elements, or apply animations, JavaScript provides multiple ways to modify CSS styles effectively.

1. Why Change CSS Using JavaScript?

Dynamic Styling: Update styles based on user interactions (e.g., button clicks, hover effects).
Responsive Design: Adjust layouts for different screen sizes dynamically.
Animations & Effects: Create smooth transitions without CSS-only animations.
Theming Support: Enable dark mode or custom themes dynamically.


2. Methods to Change CSS Using JavaScript

1. Using the style Property (Inline CSS)

The simplest way to modify CSS is by changing an element’s inline style using JavaScript.

Example: Change Background Color on Button Click

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change CSS with JavaScript</title>
    <style>
        #box {
            width: 200px;
            height: 200px;
            background-color: lightblue;
            text-align: center;
            line-height: 200px;
            font-size: 18px;
            transition: 0.5s;
        }
    </style>
</head>
<body>

    <div id="box">Click the Button</div>
    <button onclick="changeColor()">Change Color</button>

    <script>
        function changeColor() {
            const box = document.getElementById("box");
            box.style.backgroundColor = "tomato";  // Changing background color
            box.style.color = "white";  // Changing text color
            box.style.fontSize = "24px";  // Changing font size
        }
    </script>

</body>
</html>

Pros:
✔ Simple and quick for minor style updates.

Cons:
❌ Adds inline styles, which may override external stylesheets.


2. Using classList to Add/Remove CSS Classes

A better approach is adding or removing CSS classes, keeping styles in a separate CSS file.

Example: Toggle Dark Mode

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Toggle Dark Mode</title>
    <style>
        body {
            background-color: white;
            color: black;
            transition: 0.5s;
        }

        .dark-mode {
            background-color: black;
            color: white;
        }
    </style>
</head>
<body>

    <h2>Click the button to toggle Dark Mode</h2>
    <button onclick="toggleMode()">Toggle Dark Mode</button>

    <script>
        function toggleMode() {
            document.body.classList.toggle("dark-mode");
        }
    </script>

</body>
</html>

Pros:
✔ Clean and maintains separation of concerns (CSS stays in stylesheets).
✔ Easily reusable for multiple elements.

Cons:
❌ Requires predefined CSS classes.


3. Using setProperty() to Modify CSS Variables (Custom Properties)

CSS variables (--var) allow more flexible styling changes using JavaScript.

Example: Change Theme Colors Dynamically

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change CSS Variables</title>
    <style>
        :root {
            --primary-color: blue;
        }

        body {
            background-color: var(--primary-color);
            color: white;
            text-align: center;
            transition: 0.5s;
        }
    </style>
</head>
<body>

    <h2>Click to Change Theme Color</h2>
    <button onclick="changeTheme()">Change Color</button>

    <script>
        function changeTheme() {
            document.documentElement.style.setProperty("--primary-color", "purple");
        }
    </script>

</body>
</html>

Pros:
✔ Best for managing themes or reusable styles.
✔ Supports dynamic styling across multiple elements.

Cons:
❌ Limited browser support in older versions.


4. Changing Stylesheets Dynamically

If you want to switch between entire stylesheets dynamically, you can modify the stylesheet link.

Example: Switch Between Light and Dark Stylesheets

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Switch Stylesheets</title>
    <link id="theme-style" rel="stylesheet" href="light.css">
</head>
<body>

    <h2>Click to Switch Theme</h2>
    <button onclick="switchTheme()">Switch Theme</button>

    <script>
        function switchTheme() {
            const themeLink = document.getElementById("theme-style");
            themeLink.href = themeLink.href.includes("light.css") ? "dark.css" : "light.css";
        }
    </script>

</body>
</html>

Pros:
✔ Great for switching full themes or stylesheets.

Cons:
❌ Requires multiple CSS files.


5. Best Practices for Changing CSS with JavaScript

Use classList instead of style property for maintainability.
Prefer CSS variables (setProperty) for better flexibility.
Avoid inline styles as they make styles harder to manage.
Use event listeners instead of onclick attributes for better scalability.
Keep JavaScript and CSS separate for clean code organization.


6. Conclusion

JavaScript provides several ways to change CSS dynamically, from modifying inline styles to toggling classes, using CSS variables, and even switching full stylesheets. Choosing the right approach depends on the complexity and scalability of your project.

Quick Recap:

✔ Use .style for quick style changes.
✔ Use .classList.add() and .classList.toggle() for better maintainability.
✔ Use setProperty() for dynamic CSS variables.
✔ Change the stylesheet dynamically for large-scale style changes.

By applying these techniques, you can create interactive and visually appealing web applications.


Spread the love
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *