Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change CSS variable on button click?

How can I make CSS change the button's box-shadow from var('--out') to var('--in') on button click, and when you click it again it'll change back to --out?

I tried doing it but whenever I click the button it just removes the whole shadow.

const btn = document.querySelector('button')
const state = '--out'
btn.addEventListener('click', _ =>{
    document.documentElement.style.setProperty(state, '--in')
})
:root{
--in: inset 25px 25px 60px rgba(0,0,0,.5);
--out: inset -25px -25px 60px rgba(0,0,0,.5);
}
.color_1{
background-color: blue;
border-radius: 200px;
height: 300px;
width: 300px;
box-shadow: var(--out);
}
<body>
<section>
<button class="color_1"/>
</section>
</body>
like image 638
Moe Avatar asked Sep 20 '25 10:09

Moe


1 Answers

You are trying to change the value of one variable with another variable.

You will need getComputedStlye():

:root{
    --in: inset 25px 25px 60px red;
    --out: inset -25px -25px 60px green;
}
.color_1{
    background-color: blue;
    border-radius: 200px;
    height: 300px;
    width: 300px;
    box-shadow: var(--out);
}
<body>
<section>
<button class="color_1">

</button>

<script>
    const btn = document.querySelector('button')
    const state = '--out'
    btn.addEventListener('click', _ =>{  document.documentElement.style.setProperty(state, getComputedStyle(document.documentElement).getPropertyValue('--in'));
    });
</script>

</section>
</body>

But the ideal way would not be to change the value of your root variable. What if you need that value somewhere else. You can have separate classes for this on your element, which you add/toggle on a conditional basis.

:root{
    --in: inset 25px 25px 60px red;
    --out: inset -25px -25px 60px green;
}
.color_1{
    background-color: blue;
    border-radius: 200px;
    height: 300px;
    width: 300px;
}

.shadow1{
    box-shadow: var(--out);
}
.shadow2{
    box-shadow: var(--in);
}
<body>
<section>
<button class="color_1 shadow1">

</button>

<script>
    const btn = document.querySelector('button')
    const state = '--out'
    btn.addEventListener('click', function() {
    //this.classList.remove('shadow1');
    this.classList.toggle('shadow2');
    });
</script>

</section>
</body>
like image 176
Tushar Shahi Avatar answered Sep 22 '25 00:09

Tushar Shahi