Search code examples
javascripthtmlcssdarkmode

Dark mode through JS on a webpage


I have been trying to add dark mode on a practice webpage, it works to change the body background color, but isn't working on the buttons, the code is:

the code is not working on the .icons CSS class, it comes up in chrome, but doesn't function,

explanation is highly appreciated.

Thank You

document.querySelector(".slider-button").addEventListener("input", function(){
  document.querySelector("#data-left").innerHTML = this.value;
})

document.querySelector(".slider-button").addEventListener("input", function(){
  document.querySelector(".gb-left").innerHTML = 1000-this.value;
})

document.querySelector(".button-color-mode").addEventListener("click", function(){
  document.body.classList.toggle("darkmode");
  document.querySelector(".icons").classList.toggle("darkmode");
})
body {
  position: fixed;
  background-color: hsl(229, 57%, 11%);
  background-image: url("images/bg-desktop.png");
  background-position: center 400px;
  background-repeat: no-repeat;
  background-size: cover;
}
.button-color-mode{
  background-color: black;
  color: white;
  outline: none;
  border-radius: 15px;
}

.darkmode{
  background-color: white;
}

.icons {
  background-color: hsl(229, 57%, 11%);
  border-style: none;
  border-radius: 10px;
  width: 50px;
  height: 50px;
  padding: 10px;
  margin: 5px;
  outline: none;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@400;700&display=swap" rel="stylesheet">
  <link rel="icon" href="images/favicon-32x32.png">
  <link rel="stylesheet" href="styles.css">
  <title>Fylo Data Storage</title>
</head>

<body>
      <button class="icons" type="button"><img src="images/icon-document.svg" alt="" name="button"></button>
      <button class="icons" type="button"><img src="images/icon-folder.svg" alt="" name="button"></button>
      <button class="icons" type="button"><img src="images/icon-upload.svg" alt="" name="button"></button>
</html>


Solution

  • In CSS the order in which selectors are defined matters. When a rule (e.g. background-color) is defined in multiple selectors of the same specificity the one defined last will overwrite any previous definition.

    In this case .icons { background-color: ... } is defined after .darkmode { background-color: ... }, therefore .icons "wins" even if the darkmode class is set as well.

    In other words: Move the .darkmode-block below the .icons-block.