I have a dark-mode system built into my website but I can’t figure out how to switch the image source. I’m using the Javascript below with no problems for a bunch of other variables (mostly color but also element positions, etc), I just need to add something for the img src but I’m not sure what to do next.
Code
const toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]');
function switchTheme(e) {
if (e.target.checked) {
document.documentElement.setAttribute('data-theme', 'dark');
} else {
document.documentElement.setAttribute('data-theme', 'light');
}
}
toggleSwitch.addEventListener('change', switchTheme, false);
<picture class="swoop">
<source srcset="assets/landingContentSwoopDark.png">
<img src="assets/landingContentSwoopWhite.png ">
</picture>
EDIT:
I tried the answer below with some changes for my particular case and it still isn’t working, but I’m guessing that’s due to what I changed. Here is the updated code:
<div class="theme-switch-wrapper col-md-3">
<label class="theme-switch switch pull-right" for="checkbox">
<input type="checkbox" id="checkbox">
<span class="slider round"></span>
</label>
<script>
const image = document.querySelector('.swoopImage');
const toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]');
function switchTheme(e) {
if (e.target.checked) {
document.documentElement.setAttribute('data-theme', 'dark');
image.src = 'assets/landingContentSwoopDark.png';
}
else {
document.documentElement.setAttribute('data-theme', 'light');
image.src = 'assets/landingContentSwoopWhite.png';
}
}
toggleSwitch.addEventListener('change', switchTheme, false);
</script>
</div>
and
<div class="swoop">
<img style="margin-top: -53%; position: relative; pointer-events: none;" class="swoopImage" src="assets/landingContentSwoopWhite.png" alt="image">
</div>
2
Answers
Problem
Given your code, I think it’s because of the use of
picture
tag as it uses the first one if possible else it falls back to the next ones, and since your first image works it does not goes to next one. And then to switch the images you are changing the--bg-swoop
variable through which you wanted to switch background image (I assume) but that’s not how this works. To change the source of the image you need to use JS to change the value insrc
of the image.Solution
There are some vague places. SO assuming you want to just swap the image based on Toggle dark mode, you can use the following:
and as for HTML, you can only have a image tag:
Demo
For your case
For your particular case, the code would be:
Hope that works.
I would approach this quite differently than you are currently doing.
I would have the page theme determined by which CSS classes are in use and then just toggle the CSS classes when the theme needs to be changed.
When it comes to swapping images, I would set the image as a background on an element, rather than use
picture
orimg
because background images can be set with CSS.Here is an example: