DEV Community

loading...

Discussion on: Set CSS styles with javascript

Collapse
mzahraei profile image
Ardalan • Edited

hey can you maybe help me ?
I have some things like this and I just want to Update the hidden class but I Update Complete Style

<style id="style">
    .hidden{
         animation-name: bgshower;
        animation-duration: 2s;
        position: absolute;
        z-index: 2;
    }
    .neopa{
        background-color: darkred;
        font-size: large;
    }
</style>
Enter fullscreen mode Exit fullscreen mode

var style = document.getElementById('style');
var counter = parseInt(60);

        style.innerHTML = `

        .bghidden {
            height: 100%;
            width: 100%;
            background-color: #E96565;
            top: 0;
            left: 0;
            `+ 'animation-duration:' + counter + "s" + `;

            animation-name: bgshower;
            animation-delay: 0s;

            position: absolute;
            z-index: 2;
        }
        `;
        document.adoptedStyleSheets = [style];
Enter fullscreen mode Exit fullscreen mode
Collapse
karataev profile image
Eugene Karataev Author

I'm not 100% sure what you're trying to achieve, but if you need to add animations on an element(s) with JS after some event, consider the following way:

  • Define styles with css like
.hidden {
...
}

.animate {
...
}
Enter fullscreen mode Exit fullscreen mode
  • Add/remove CSS classes with animations when necessary with DOM API: document.querySelectorAll('.hidden').classList.add('animate')
Collapse
mzahraei profile image
Ardalan

Thanks for writing but I just wanted to update an element's CSS with JS.
no more new class I wanted to Edit animation-duration value from JS.
I resolve it thx