How to Dynamically Change a Page’s CSS using jQuery

  John Mwaniki /    Updated on 07 Jul 2024

In web development, personalizing user experiences is a key aspect of creating engaging and interactive websites.

In some cases, you may want to dynamically change the look and feel of your pages based on user interactions, external events, or even internal logic.

For example, you may want your website to have different predefined themes (with different color schemes, fonts, and layouts) where users can easily switch between them based on their preferences and personalize their experiences.

Another example is the implementation of a day and night mode toggle, which has become a popular trend in modern web design. Users can switch between light and dark themes, providing a visually comfortable experience based on the time of day.

This can be achieved by dynamically manipulating or changing a page's CSS using jQuery.

In this article, I will show you how to dynamically change the styling of a page in a step-by-step guide using jQuery with the help of multiple examples.

Dynamically changing CSS with jQuery

You need to first include the jQuery library in your page before adding any jQuery code. You can do so by either downloading the library and linking it to your HTML file or using a CDN for quick integration.

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

There are several ways in which you can dynamically change the CSS styling on your page:

1. Using jQuery's css() Method

The css() method takes two arguments: the CSS property whose styling you want to change and its new value.

Syntax

$(selector).css(property, value)

Example

$("body").css({"background-color","black"});

You can also pass an object containing multiple property-value pairs for more extensive modifications.

Example

$("#mydiv").css({"background-color":"black","color":"white", "width": "80%"});

To dynamically change the CSS styling, you can trigger the changes based on various events such as click, hover, focus, mouseover, etc.

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dynamically changing CSS with jQuery</title>
<style type="text/css">
    .container {
        width: 70%;
        margin: auto;
        padding: 30px;
    }
    #mode {
        float: right;
    }
</style>
</head>
<body>
 <div class="container">
   <div id="mode">
    <button class="dark"> Dark Mode</button>
    <button class="light"> Light Mode</button>
   </div>
   <h1>Sample H1 heading</h1>
   <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
 </div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function(){
    $(".dark").click(function(){
        $("body").css({"background-color":"#000","color":"#fff"});
    });
    $(".light").click(function(){
        $("body").css({"background-color":"#fff","color":"#000"});
    });
});
</script>
</body>
</html>

In this example, we have a page with a heading, a paragraph, and two buttons (dark and light mode). By default, the page has a white background and black text when loading. On clicking the "Dark Mode" button, the page background changes to black and the text to white. On clicking the "Light Mode" button, the background color changes back to white and the text to black color.

We have used the click event handler on the buttons (using their classes as selectors) where we added the respective CSS styling on the body element for background and text colors using the jQuery's css() method.

2. Using jQuery's attr() Method

The attr() method sets attributes and values of the selected elements.

Syntax

$(selector).attr(attribute, value)

The attribute parameter specifies the name of the attribute and value specifies the value of the attribute.

An alternative method of dynamically changing the CSS styling is having the code already written for various CSS selectors (e.g. classes and IDs) in your stylesheet and then switching the attribute values for various elements.

This can easily be achieved with the attr() function.

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dynamically changing CSS with jQuery</title>
<style type="text/css">
    .light-theme {
        background-color: #fff;
        color: #000;
    }
    .dark-theme {
        background-color: #000;
        color: #fff;
    }
    .container {
        width: 70%;
        margin: auto;
        padding: 30px;
    }
    #mode {
        float: right;
    }
</style>
</head>
<body class="light-theme">
 <div class="container">
   <div id="mode">
    <button class="dark"> Dark Mode</button>
    <button class="light"> Light Mode</button>
   </div>
   <h1>Sample H1 heading</h1>
   <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
 </div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function(){
    $(".dark").click(function(){
        $("body").attr("class", "dark-theme");
    });
    $(".light").click(function(){
        $("body").attr("class", "light-theme");
    });
});
</script>
</body>
</html>

This works like in the previous example where on clicking the "Dark Mode" button, the page background turns to black and the text to white color. On clicking the "Light Mode" button, the page background changes to white and the text to black.

Instead of adding the CSS code directly using jQuery, we added it within the page's styling. We have the styling for a "dark-theme" and a "light-theme" class. These classes are to be applied to the body element at different times.

We added the "light-theme" class in the body element so that the light mode is applied by default when the page loads.

Clicking the "Dark Mode" and "Light Mode" buttons uses the attr() method to change the class attribute values for the body element to "dark-theme" and "light-theme" respectively. This in turn changes the page's styling dynamically.

You can do the same with any HTML element e.g. div, h1, li, etc.

Alternatively, you can add inline CSS directly to the element you want to change styling using the attr() method. In this case, you will need to set the style attribute and then specify the styling within the value parameter.

Example

<script>
$(function(){
    $(".dark").click(function(){
        $("body").attr("style", "background-color: #000; color:#fff;");
    });
    $(".light").click(function(){
        $("body").attr("style", "background-color: #fff; color:#000;");
    });
});
</script>

Dynamically Switching Style Sheets with jQuery

To do a more complex dynamic change in styling for the entire page, such as the layout, fonts, and color scheme for different elements across the page, then switching the entire style sheet is more effective.

You can use the attr() method to achieve this. Start by creating multiple style sheets, each defining a unique visual theme for your website. For instance, you might have a "light.css," a "dark.css," and a "colorful.css" file.

Include a link to your default style sheet in the HTML file. This will be the initial style applied to your webpage. Within that link, make sure to add a class or ID attribute that will help you target the element later.

<link id="pagestyle" rel="stylesheet" type="text/css" href="styles/light.css">

In this example, we have used an ID with value "pagestyle" and stored the CSS files in a "styles" folder located in the same folder as our HTML page. Make sure to use the correct path if you store yours in a different directory to ensure the style sheet gets loaded properly.

As we did in the earlier examples, implement a user interface (e.g., a set of buttons or a dropdown) that allows users to choose the desired style.

For this example, we'll use a simple dropdown. Each dropdown option has a CSS file name as its value.

<label for="styleSelector">Select Theme:</label>
<select id="styleSelector">
   <option value="light.css">Light Theme</option>
   <option value="dark.css">Dark Theme</option>
   <option value="colorful.css">Colorful Theme</option>
</select>

Lastly, you need to write jQuery code to dynamically switch style sheets based on user selection. Attach an event handler to the style selector to update the href attribute of the style sheet link tag with the value of the selected option.

$(function(){
   $("#styleSelector").on("change", function () {
      var selectedStyle = $(this).val();
      $("#pagestyle").attr("href", "styles/" + selectedStyle);
   });
});

When a user selects a different theme, the CSS file gets automatically updated, and the styling changes.

You can enhance the user experience by adding smooth transitions between style changes. This can be achieved by applying CSS transitions to elements affected by style modifications.

body {
   transition: background-color 0.5s ease-in-out;
}

Full Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dynamically changing CSS with jQuery</title>
<link id="pagestyle" rel="stylesheet" type="text/css" href="styles/light.css">
<style type="text/css">
body {
   transition: background-color 0.5s ease-in-out;
}
</style>
</head>
<body>
 <div class="container">
   <div id="themeswitcher">
     <label>Select Theme:</label>
     <select id="styleSelector">
       <option value="light.css">Light Theme</option>
       <option value="darker.css">Dark Theme</option>
       <option value="colorful.css">Colorful Theme</option>
     </select>
   </div>
   <h1>Sample H1 heading</h1>
   <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
 </div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function(){
   $("#styleSelector").on("change", function () {
      var selectedStyle = $(this).val();
      $("#pagestyle").attr("href", "styles/" + selectedStyle);
   });
});
</script>
</body>
</html>

Conclusion

Allowing dynamic change of CSS styling enables personalization of user experience on a website.

Whether it's adjusting to different themes or accommodating user preferences, this approach allows seamless transformation to the look and feel of the web pages.

All this can be implemented using jQuery and by following the methods in this article, you can now easily do it by yourself in your projects.