最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use a function to change background color with linear gradient? - Stack Overflow

programmeradmin4浏览0评论

I am trying to change the background color randomly using functions but it seems not working.

I've tried with normal/basic colors and it works normally.

var change = document.getElementById("meBaby"); // add to the top

function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function changeColor() {
    change.style.backgroundColor = getRandomColor();
}

setInterval(changeColor, 10000);

However, when I try to change to linear gradient it is not possible, sorry I don't know where is my mistake. I even remove the var color = '#'; to var color; to see whether it would work but nothing. See the code below

var change = document.getElementById("meBaby"); // add to the top

function getRandomColor() {
    var letters = ['linear-gradient(120deg, #f6d365 0%, #fda085 100%)',
    'linear-gradient(to top, #fdcbf1 0%, #fdcbf1 1%, #e6dee9 100%)',
    ];
    var color;
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * letters.length)];
    }
    return color;

}

function changeColor() {
    change.style.backgroundColor = getRandomColor();
}
changeColor();
setInterval(changeColor, 10000);

I console.log(changeColor()); but it is undefined I don't know why. Any help would be really appreciated.

I am trying to change the background color randomly using functions but it seems not working.

I've tried with normal/basic colors and it works normally.

var change = document.getElementById("meBaby"); // add to the top

function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function changeColor() {
    change.style.backgroundColor = getRandomColor();
}

setInterval(changeColor, 10000);

However, when I try to change to linear gradient it is not possible, sorry I don't know where is my mistake. I even remove the var color = '#'; to var color; to see whether it would work but nothing. See the code below

var change = document.getElementById("meBaby"); // add to the top

function getRandomColor() {
    var letters = ['linear-gradient(120deg, #f6d365 0%, #fda085 100%)',
    'linear-gradient(to top, #fdcbf1 0%, #fdcbf1 1%, #e6dee9 100%)',
    ];
    var color;
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * letters.length)];
    }
    return color;

}

function changeColor() {
    change.style.backgroundColor = getRandomColor();
}
changeColor();
setInterval(changeColor, 10000);

I console.log(changeColor()); but it is undefined I don't know why. Any help would be really appreciated.

Share Improve this question asked Jun 3, 2019 at 15:49 Elias PradoElias Prado 1,8572 gold badges19 silver badges36 bronze badges 8
  • I'm dying to know why you think this should work... But console.log(changeColor()) shows undefined because there is no return statement in changeColor. – Niet the Dark Absol Commented Jun 3, 2019 at 15:52
  • 2 Yes, that's why I am asking @Niet. Stack overflow is here for this. :) – Elias Prado Commented Jun 3, 2019 at 15:54
  • 1 background-color doesn't implement linear gradients, you have to change background-image. – Teemu Commented Jun 3, 2019 at 15:54
  • 1 @NiettheDarkAbsol why should there be? – GrafiCode Commented Jun 3, 2019 at 15:55
  • I think it's because of the for, you only need 1 item from your letters. – l-portet Commented Jun 3, 2019 at 15:56
 |  Show 3 more ments

3 Answers 3

Reset to default 3

Because you are concatenating the variable color, which starts undefined (with any defined value).

Also, you are creating an array of linear gradients, and then concatenating multiple gradients.

Just debug your code line by line and you will notice this. F12 is your friend. Good developers stick to it forever. This is what you will see:

"undefinedlinear-gradient(120deg, #f6d365 0%, #fda085 100%)linear-gradient(to top, #fdcbf1 0%, #fdcbf1 1%, #e6dee9 100%)linear-gradient(to top, #fdcbf1 0%, #fdcbf1 1%, #e6dee9 100%)linear-gradient(to top, #fdcbf1 0%, #fdcbf1 1%, #e6dee9 100%)linear-gradient(120deg, #f6d365 0%, #fda085 100%)linear-gradient(120deg, #f6d365 0%, #fda085 100%)"

Is kinda weird the way you are creating gradients actually, but you can fix that with something like this:

function getRandomColor() {
    var letters = [
        'linear-gradient(120deg, #f6d365 0%, #fda085 100%)',
        'linear-gradient(to top, #fdcbf1 0%, #fdcbf1 1%, #e6dee9 100%)',
    ];
    return letters[Math.floor(Math.random() * letters.length)];
}

And finally, use the background CSS property, not the backgroundColor CSS property.

By the way, this will get two "not so random" gradients, as they will be predefined. If you truly want random gradients use something like this:

var change = document.getElementById("meBaby");
function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
function getRandomGradient() {
    return 'linear-gradient('+(Math.random()*360)+'deg, '+getRandomColor()+' 0%, '+getRandomColor()+' 100%)';
}

function changeColor() {
    change.style.background = getRandomGradient();
}

changeColor();
setInterval(changeColor, 1000);
<div id="meBaby">TEST</div>

you can create a function for generate random hex color and set color , and generate random angle and set .

function getRandomColor(){
return  "#000000".replace(/0/g,function(){
    return (~~(Math.random()*16)).toString(16);});
}


setInterval(function(){
document.getElementById("meBaby").style.background = 'linear-gradient('+(Math.random()*360)+'deg,'+ getRandomColor()+ ' 0%,'+getRandomColor()+ ' 100%)';
}, 1000);
#meBaby{
 height:100px;
 width:500px;
}
<div id="meBaby"></div>

update : you can also set random direction like :

function getRandomColor(){
return  "#000000".replace(/0/g,function(){
    return (~~(Math.random()*16)).toString(16);});
}


function getRandomDirection(){
    var directions=['top left','top center','top right','center left','center center','center right','bottom left','bottom center','bottom right'];
   return directions[Math.floor(Math.random() * directions.length)];
}

setInterval(function(){
document.getElementById("meBaby").style.background = 'linear-gradient(to '+getRandomDirection()+','+ getRandomColor()+ ' 0%,'+getRandomColor()+ ' 100%)';
}, 1000);
#meBaby{
 height:100px;
 width:500px;
}
<div id="meBaby"></div>

read more about linear-gradient

There are a few mistakes on the linear-gradient approach:

  • 1) You have to set the background property, not the backgroundColor property.

  • 2) The for loop have no sense now, you will choose an option from the array, not the 6 hexadecimal characters of a color.

Example:

var change = document.getElementById("meBaby");

function getRandomColor()
{
    var letters = [
      'linear-gradient(120deg, #f6d365 0%, #fda085 100%)',
      'linear-gradient(to top, #fdcbf1 0%, #fdcbf1 1%, #e6dee9 100%)',
      'linear-gradient(to right, #ffffff 0%, #555555 100%)'
    ];

    var color = letters[Math.floor(Math.random() * letters.length)];
    return color;
}

function changeColor()
{
    change.style.background = getRandomColor();
}

changeColor();
setInterval(changeColor, 5000);
#meBaby {
    height: 50px;
    text-align: center;
}
<div id="meBaby">TEST</div>


Update

This was not asked on the original question, but in case you need to generate a random linear-gradient without having a predefined set, then I will proceed like this:

var change = document.getElementById("meBaby");

function getRandom(min, max)
{
    return Math.floor(Math.random() * (max - min) + min);
}

function getRandomColor()
{
    var color = "#";

    for (var i = 0; i < 6; i++)
    {
        color += getRandom(0, 16).toString(16);
    }

    return color;
}

function getRandomLinearGradient()
{
    var d = getRandom(0, 360);
    var c1 = getRandomColor(), c2 = getRandomColor();
    return `linear-gradient(${d}deg, ${c1}, ${c2})`;
}

function changeColor()
{

    change.style.background = getRandomLinearGradient();
    console.log("New background is: ", change.style.background);
}

changeColor();
setInterval(changeColor, 5000);
.as-console {background-color:black !important; color:lime;}

#meBaby {
    height: 50px;
    text-align: center;
}
<div id="meBaby">TEST</div>

Note, you can use Number.toString() with a radix of 16 to get a hexadecimal representation of a number. Also, I have used template literals on the getRandomLinearGradient() method, you should check browser patibility before using it.

发布评论

评论列表(0)

  1. 暂无评论