Skip to main content

Dynamic Style Updates with CSS and JavaScript

In this tutorial, we'll learn how to dynamically update CSS styles using JavaScript. This enables you to create interactive and responsive web applications that adjust their appearance based on user interactions or other events.

Event listeners

Use JavaScript event listeners to detect user interactions, such as clicks or mouse movements, and trigger functions that modify the CSS styles.

JavaScript
const button = document.getElementById('example-button');

button.addEventListener('click', function () {
// Code to execute when the button is clicked
});

Modifying CSS styles on events

Update the CSS styles of elements in response to events by accessing the style property and setting new values for specific CSS properties.

JavaScript
button.addEventListener('click', function () {
const element = document.getElementById('example-element');
element.style.backgroundColor = 'green';
});

Toggling CSS classes

Toggle CSS classes on elements to apply or remove a set of styles in response to user interactions.

JavaScript
const exampleElement = document.getElementById('example-element');

button.addEventListener('click', function () {
exampleElement.classList.toggle('active');
});

Dynamic theming

Update the CSS styles of multiple elements by manipulating CSS variables with JavaScript.

HTML
<style>
:root {
--main-color: blue;
}

.element {
color: var(--main-color);
}
</style>
JavaScript
button.addEventListener('click', function () {
document.documentElement.style.setProperty('--main-color', 'red');
});

Responsive styles

Dynamically adjust CSS styles based on window size or other factors, allowing for responsive web design without media queries.

JavaScript
window.addEventListener('resize', function () {
const width = window.innerWidth;
const element = document.getElementById('example-element');

if (width < 768) {
element.style.fontSize = '16px';
} else {
element.style.fontSize = '24px';
}
});

Conclusion

By using JavaScript to dynamically update CSS styles, you can create web applications that react to user interactions, adapt to different screen sizes, and provide a more engaging user experience.