Home > front end >  Add a button to change to dark mode in react website
Add a button to change to dark mode in react website

Time:11-03

I wanna bring up a button on my site which let's the users change to dark or light mode whenever they want. I followed a tutorial and did the dark mode, but the problem is that the user has to press the Enter key to enter dark mode.. But I want that there's a button which helps them change to dark or light mode Here's the code which I used in js:-

<script>
      window.onload = function () {
  document.onkeypress = function (e) {
    console.log(e);
    e = e || window.event;
    if (e.keyCode === 13) {
      document.documentElement.classList.toggle("dark-mode");
      document.querySelectorAll(".inverted").forEach((result) => {
        result.classList.toggle("invert");
      });
    }
  };
};
    </script>

And here's what I used in css :-

.dark-mode {
  filter: invert(1) hue-rotate(180deg);
}
.invert {
  filter: invert(1) hue-rotate(180deg);
}'

The .inverted class in js is because I don't want the images to invert their colors.. so I gave all the images a class='inverted'

So, this is what I've done and someone pls lemme know that how should I bring up a button that changes to dark or light mode instead of pressing the Enter key for it

Thanks!

CodePudding user response:

You can run the function on an onClick event on your button like this:

<button onClick="toggleMode()">Toggle Mode</button>

<script>
  function toggleMode () {
      document.documentElement.classList.toggle("dark-mode");
      document.querySelectorAll(".inverted").forEach((result) => {
        result.classList.toggle("invert");
      })
  }
</script>

CodePudding user response:

you can create a button on your HTML page and then attach an event listener to it.

function myfunction(e) {
  console.log("you clicked");
  document.documentElement.classList.toggle("dark-mode");
  document.querySelectorAll(".inverted").forEach((result) => {
    result.classList.toggle("invert");
  });
}
const btn = document.querySelector('.btn')
btn.addEventListener('click', myfunction);
<button class="btn">Dark Mode</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

BTW why are you using the script tag inside a react-app?

  • Related