Home > Net >  How can I change CSS variable on button click?
How can I change CSS variable on button click?

Time:02-02

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.

HTML JS:

<body>
<section>
<button >

</button>

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

</section>
</body>

CSS:

: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);
}

CodePudding user response:

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

You will need Demo

Finally, the best solution would be toogle only the state you desire, like this:

<body>
    <style>
        :root{
            --in: inset 25px 25px 60px rgba(0,0,0,.5);
            --out: inset -25px -25px 60px rgba(0,0,0,.5);
            --one: blue;
            --two: red;
        }

        .color_1{
            background-color: blue;
            border-radius: 200px;
            height: 300px;
            width: 300px;
        }

        .state1{
            box-shadow: var(--out);
        }
        
        .state2{
            box-shadow: var(--in);
        }
    </style>
    
<section>
<button >

</button>

<script>
    const btn = document.querySelector('button')
    const state = '--out'
    btn.addEventListener('click', _ =>{
        btn.classList.toggle('state2');
    });
</script>

</section>
</body>

  •  Tags:  
  • Related