Home > Blockchain >  Change font color with js
Change font color with js

Time:11-28

I want to change the

id="navbar"

font color while the page is in dark mode, and make the font color back when the page switches to light mode. The switch is made with js:

const onClick = () => {
  theme.value = theme.value === 'light'
    ? 'dark'
    : 'light'

  setPreference()
}

const getColorPreference = () => {
  if (localStorage.getItem(storageKey))
    return localStorage.getItem(storageKey)
  else
    return window.matchMedia('(prefers-color-scheme: dark)').matches
      ? 'dark'
      : 'light'
}

const setPreference = () => {
  localStorage.setItem(storageKey, theme.value)
  reflectPreference()
}

const reflectPreference = () => {
  document.firstElementChild
    .setAttribute('data-theme', theme.value)

  document
    .querySelector('#theme-toggle')
    ?.setAttribute('aria-label', theme.value)
}

const theme = {
  value: getColorPreference()
}

and the background is set here

html {
    background: linear-gradient(135deg, #a1c4fd 10%, #c2e9fb 90%);
    block-size: 100%;
    color-scheme: light;
    background-attachment: fixed;
}

html[data-theme=dark] {
    background: linear-gradient(135deg, #061c43 10%, #08101f 90%);
    color-scheme: dark;
    background-attachment: fixed;
    
}
#navbar ul li[data-theme=dark]  {
    padding: 10px;
    border-radius: 25px;
    float: right;
    margin-left: 3px;
    margin-right: 8px;
    font-weight: 500;
    color: white;
    box-shadow: -5px -5px 8px #ffffff60,5px 5px 10px #00000060;
}

that's not doing anything. what am i missing?

CodePudding user response:

if you want to change the color of an element using js , you gotta learn about DOM HTML in this exemple i'm trying to change the color of some elements

<!DOCTYPE html>
<html>
<body>

<h2 id="myH2">This is an example h2</h2>
<p id="myP">This is an example paragraph.</p>
<p id="myP2">This is also an example paragraph.</p>
<div id="myDiv">This is an example div.</div>
<br>

<button type="button" onclick="myFunction()">Set text color</button>

<script>
 function myFunction() {
 document.getElementById("myH2").style.color = "#ff0000";
 document.getElementById("myP").style.color = "magenta";
 document.getElementById("myP2").style.color = "blue";
 document.getElementById("myDiv").style.color = "lightblue";
  }
</script>

</body>
</html>

CodePudding user response:

Simply do this:

const reflectPreference = () => {
  document.firstElementChild.setAttribute('data-theme', theme.value);

  document.querySelector('#theme-toggle')?.setAttribute('aria-label', theme.value);

  document.getElementById("navbar").style.fontColor = theme.value === "dark" ? "white" : "black";
}

Read more here.

  • Related