Any way to create an evrnt to know if we are in dark mode or light mode in JS to change an image or a filter ? (or maybe in CSS)
TY
You can use MutationObserver to watch for changes to a DOM node’s attributes. Just add this JS to your design:
window.addEventListener('DOMContentLoaded', () => {
const getTheme = () => document.documentElement.getAttribute('data-bs-theme');
let theme = getTheme();
const observer = new MutationObserver(() => {
theme = getTheme();
onThemeChange(theme);
});
observer.observe(document.documentElement, { attributeFilter: ["data-bs-theme"] });
function onThemeChange(theme) {
// Do stuff
console.log(theme);
}
});
You can add your logic for what happens when the theme changes in the onThemeChange()
function.
If you want to change the appearance of a component depending on the mode, you can do it with this CSS:
[data-bs-theme=dark] .your-selector {
/* Add your styles here */
}
Change .your-selector
to a selector that matches the element you want to change and add your styles in the block. They will only be applied in dark mode.
2 Likes
Thank you.
Both working, CSS is beter for me.