Search code examples
javascripthtmlcssinnerhtml

I want the CSS of a page to change when a button is clicked


I found how you could do this with individual elements but I couldn't find anything that would change the the body CSS of a page. I am trying to make a thing where it will switch between light and dark mode when you click the button.

<!DOCTYPE html>
<button style="background-color: #252525;
border: 2px;
border-style: solid;
border-color: white;
color: white; 
padding: 10px 32px;
text-align: center;
text-decoration: none; 
display: inline-block;
font-size: 16px;  
font-weight: bold;
margin: 4px 2px;
cursor: pointer;" id="changethemebutton" onclick="changeTheme()">Change Theme</button>

function changeTheme() {
document.getElementById(".background").style.background = "black";
}
</script>
<style>
body{
    background-color:white
}
</style>

Solution

  • Best way to set a dark-mode on your website is to toggle a class .dark-mode on your body using javascript and then stylize it using css:

    body {
      /* light-mode styles */
      background-color: white;
    }
    
    body.dark-mode {
      /* dark-mode styles */
      background-color: black;
    }
    <button style="background-color: #252525;
    border: 2px;
    border-style: solid;
    border-color: white;
    color: white; 
    padding: 10px 32px;
    text-align: center;
    text-decoration: none; 
    display: inline-block;
    font-size: 16px;  
    font-weight: bold;
    margin: 4px 2px;
    cursor: pointer;" id="changethemebutton" onclick="changeTheme()">Change Theme
    </button>
    
    <script>
      function changeTheme() {
        document.body.classList.toggle('dark-mode');  // <-- Toogle dark-mode class to <body>
      }
    </script>