πter
πter

Reputation: 2217

How can I change linear-gradient percentage via JavaScript?

I want to make a circle background to fill in gradually using linear-gradient. I have my CSS and JavaScrpit file, only I can't figure out how to select the linear-gradient property in JS.

 <div id="circle" class="circleBase "></div>
    #circle{
        width: 300px;
        height: 300px;
        background-color:blue;
        background: linear-gradient(90deg, #FFC0CB 0%,white 100%);
    }

    function changeBackground() {
        var elem = document.getElementById("circle"); 
        var width = 1;
        var id = setInterval(frame, 10);
        function frame() {
            if (width >= 100) {
                clearInterval(id);
            } else {
               width++; 
               elem.style = ????
            }
        }
    }

Upvotes: 1

Views: 1904

Answers (1)

BenM
BenM

Reputation: 53198

Just define it as a string:

elem.style.background = 'linear-gradient(180deg, #FFC0CB 0%,white 100%)';

function changeBackground() {
        var elem = document.getElementById("circle"); 
        var width = 1;
        var id = setInterval(frame, 10);
        function frame() {
            if (width >= 100) {
                clearInterval(id);
            } else {
               width++; 
               elem.style.background = 'linear-gradient(180deg, #FFC0CB 0%,white 100%)';
            }
        }
    }
    
 
#circle{
        width: 300px;
        height: 300px;
        background-color:blue;
        background: linear-gradient(90deg, #FFC0CB 0%,white 100%);
    }
<div id="circle"></div>
<button onclick="changeBackground()">Change!</button>

Upvotes: 2

Related Questions