Show different images depending on the theme #11
-
i have a problem understanding how to change image based on this toggle? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hey @ilyasabdut, thanks for reaching out! There are multiple ways to achieve this, it depends on if you are using an With CSSThe easiest way would be to specify two different image URLs as variables in CSS and then use it as the background for a div element: HTML: <div id="image-div"></div> CSS: /* Light Image */
[data-theme="light"] {
--image: url("/path/to/light.png");
}
/* Dark Colors */
[data-theme="dark"] {
--image: url("/path/to/dark.png");
}
#image-div {
background: var(--image);
} With JSIf you are using an HTML: <img id="image" src="/path/to/dark.png"> JavaScript: // Add darkmode toggle (more info in the documentation)
new Darkmode().attach()
// Specify the URL to an image for each theme
const imageSrc = {
dark: "/path/to/dark.png",
light: "/path/to/light.png"
}
// listen to theme-change event and change src tag to new theme
window.addEventListener('theme-change', e => {
const theme = e.detail.to // will return 'light' or 'dark'
document.getElementById('image').src = imageSrc[theme]
}); I hope this answers your question, let me know if you have a question about the code or if there's anything else I can help you with! |
Beta Was this translation helpful? Give feedback.
Hey @ilyasabdut, thanks for reaching out! There are multiple ways to achieve this, it depends on if you are using an
<img>
tag or are referencing the image via CSS.With CSS
The easiest way would be to specify two different image URLs as variables in CSS and then use it as the background for a div element:
HTML:
CSS:
With JS
If you are using an
img
tag, you have to use JavaScript to change thesrc
attribute of theimg
tag. You can do this by listening to …