Skip to content Skip to sidebar Skip to footer

Permanently Change A :root .css Variable With Javascript (getting Info For Variable Via Input)

I was working on an idea for this website i'm creating and the idea is to basically ask the user for a color input (#12345;) and once inputted the user submits the input and that w

Solution 1:

I think that you can't change your css variable inside your css file from outside, without rewriting or preprocessing your file (for example on the server side). But you can still change it's loaded value on the client side. Here I made example for your first heading text and submit button:

HTML:

<div class="adminpage-background">
    <h1 class="primary-text">Input to change primary colors (header, footer, service borders)</h1>
    <input id="primary-text-input" type="text" name="primaryChange" placeholder="#12345;">
</div>

CSS:

:root {
    --clr-primary: #098ef6;
}

.primary-text {
    color: var(--clr-primary);
}

JS:

const primaryInput = document.getElementById('primary-text-input');
const primaryBtn = document.getElementById('primary-text-btn');

primaryBtn.onclick = () => {
    document.querySelector(':root').style.setProperty('--clr-primary', primaryInput.value);
};

Solution 2:

As Rodiax mentions it's probably not possible to change the actual value in the css file.

However you can set a localStorage object and read it on page load, which would set the CSS variable again throughout the page, for every new page the user visits.

primaryBtn.onclick = () => {
    document.querySelector(':root').style.setProperty('--clr-primary', primaryInput.value);
    localStorage.setItem('primary-color', primaryInput.value); 
};
window.onload = () => {
  if (localStorage.getItem('primary-color')) {
        document.querySelector(':root').style.setProperty('--clr-primary', localStorage.getItem('primary-color'));
  }
}

Post a Comment for "Permanently Change A :root .css Variable With Javascript (getting Info For Variable Via Input)"