Ask your own question, for FREE!
Computer Science 22 Online
Basic:

How do I create an interval using JavaScript that would display a CSS circle changing colors? @ultrilliam

Ultrilliam:

I mean, technically speaking you can do this with only CSS using CSS animations, but the simplest way would be to first create the circle. To do that lets create a div with the ID of circle ```html <div id="circle"></div> ``` Now lets style that element to be a circle using CSS: Below I'll set the circle element to have a width and height of 100 pixels, and tell it to be black. Then I'll set the border radius to 100 pixels which since it is the same as the width and height, will result in it being a circle. (Border radius rounds the corners of the element by the desired amount) ```css #circle { /*Set Width and Height*/ width: 100px; height: 100px; /*Assign Default Background Color*/ background: black; /*Make it a circle*/ border-radius:100px; } ``` Now finally if we want it to change colors using javascript rather than a CSS animation, you can do that by selecting the element via the ID, then using a setInterval loop to change the color every x seconds. ```javascript //set the variable circle to the circle element var circle = document.getElementById("circle") //create interval loop setInterval(function() { //choose random color to set the circle to circle.style.background = "#"+Math.floor(Math.random()*16777215).toString(16); }, 500) //loop every 500ms, or half a second ``` There are lots of other ways to do this, and lots more elegant ways as well such as using a CSS animation that will result in smooth color transfers, but this is fairly basic aside from the random color chooser. Another way you could choose a color is have an array, and choose randomly from the array every iteration, or have a counter that increments every loop, and use that to determine what color should be shown. But at it's most basic, there ya go.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!