Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to generate random gradient javascript

// Generate random Gradient on click
var myButton = document.querySelector('.classNamehere');
myButton.addEventListener('click', randomGradient);
function randomGradient() {

        var angle = Math.floor(Math.random() * 360);

  // You can add/remove colors simply by calling or removing the colorCode() function
        var gradient = `linear-gradient(${angle}deg,
        #${colorCode()},
        #${colorCode()},
        #${colorCode()})`;

        const element = document.querySelector("whateverElement").style.background = gradient;

		// uncomment the console log to see the generated gradient
        // console.log(gradient);

    }

// this function generates random color(HEX) and returns it
function colorCode() {
        var hexCode1 = "";
        var hexValues1 = "0123456789abcdef";

        for (var i = 0; i < 6; i++) {
            hexCode1 += hexValues1.charAt(Math.floor(Math.random() * hexValues1.length));
        }
        return hexCode1;
    }
 
PREVIOUS NEXT
Tagged: #generate #random #gradient #javascript
ADD COMMENT
Topic
Name
8+3 =