Using JavaScript to Edit CSS Gradient

Using JavaScript to edit CSS gradient

Start with something like the following:

var dom = document.getElementById('mainHolder');
dom.style.backgroundImage = '-moz-linear-gradient('
+ orientation + ', ' + colorOne + ', ' + colorTwo + ')';

If you need to support more browsers than Firefox, this will need to be done in combination with either browser-sniffing or some Modernizr-like feature detection.

Below is an example of how this can be done, using feature-detection similar to Modernizr (tested in Firefox, Chrome, Safari, Opera).

// Detect which browser prefix to use for the specified CSS value
// (e.g., background-image: -moz-linear-gradient(...);
// background-image: -o-linear-gradient(...); etc).
//

function getCssValuePrefix()
{
var rtrnVal = '';//default to standard syntax
var prefixes = ['-o-', '-ms-', '-moz-', '-webkit-'];

// Create a temporary DOM object for testing
var dom = document.createElement('div');

for (var i = 0; i < prefixes.length; i++)
{
// Attempt to set the style
dom.style.background = prefixes[i] + 'linear-gradient(#000000, #ffffff)';

// Detect if the style was successfully set
if (dom.style.background)
{
rtrnVal = prefixes[i];
}
}

dom = null;
delete dom;

return rtrnVal;
}

// Setting the gradient with the proper prefix
dom.style.backgroundImage = getCssValuePrefix() + 'linear-gradient('
+ orientation + ', ' + colorOne + ', ' + colorTwo + ')';

Setting linear-gradient with javascript

I little change your code, maybe that what you need:

  

<style>

body {

padding: 0;

margin: 0;

font-family: 'Kosugi Maru', sans-serif;

background-image: linear-gradient(45deg, rgb(140, 202, 165),

rgb(198, 159, 197), rgb(248, 160, 133), rgb(52, 219, 216));

}

</style>

<script>

function generateGradient(one, two, three) {

let lessOne = one;

let moreOne = one + 120;

let lessTwo = two;

let moreTwo = two + 120;

let lessThree = three;

let moreThree = three + 120;

if ((moreOne + 120) > 255) {

moreOne = moreOne - 255;

}

if ((moreTwo + 120) > 255) {

moreTwo = moreTwo - 255;

}

if ((moreThree + 120) > 255) {

moreThree = moreThree - 255;

}

document.getElementsByTagName("body")[0].style.backgroundImage = 'linear-gradient(45deg, rgb(' + lessOne + ',' + lessTwo + ',' + lessThree + '), rgb(' + one + ',' + two + ',' + three + '), rgb(' + moreOne + ',' + moreTwo + ',' + moreThree + '))';

}

generateGradient(10, 100, 245)

</script>

How can I change a CSS gradient via JavaScript?

With jQuery it'll be :

$('.gradient').css({'background-image': 'linear-gradient(to top,  #2E2E28 0%, #4D4C48 100%)'});

For safari :

$('.gradient').css({'background-image': '-webkit-linear-gradient(top,  #2E2E28 0%, #4D4C48 100%)'});

See here for a live example.

Seems to work cross-browser.

Edit :

I did a small plugin which can help you with the different colors :

;(function($) {
var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);

var methods = {
init: function (settings) {

settings = $.extend( {
'colors' : ['red', 'blue'],
'direction' : 'top'
}, settings);

return this.each(function(){
if($.isArray(settings.colors) && settings.colors.length >= 2) {
$(this).css({
'background':
methods.gradientToString(settings.colors, settings.direction)
});
} else {
$.error('Please pass an array');
}

});

},
gradientToString: function (colors, direction) {

var nbColors = colors.length;

//If no percent, we need to calculate them
if(colors[0].percent === undefined) {

//Passed only colors as an array we make it an object
if(colors[0].color === undefined) {
var tmp = [];
for(i=0; i < nbColors; i++)
tmp.push({'color':colors[i]});

colors = tmp;
}

var p = 0,
percent = 100 / (nbColors - 1);

//calculate percent
for(i=0; i< nbColors; i++) {
p = i === 0 ? p : (i == nbColors-1 ? 100 : p + percent);
colors[i].percent = p;
}
}

var to = isSafari ? '' : 'to';

//build the string
var gradientString = isSafari ? '-webkit-linear-gradient(' : 'linear-gradient(';

gradientString += to +' '+ direction;

for(i=0; i < nbColors; i++)
gradientString += ', '+ colors[i].color + ' ' + colors[i].percent + '%';

gradientString += ')';
return gradientString;

}

};

$.fn.gradientGenerator = function () {
return methods.init.apply( this, arguments );
};
})(jQuery);

Use it like this for example :

$('.gradient').gradientGenerator({
colors : ['#2E2E28', '#4D4C48']
});

$('.change-color').on('click', function(e) {

e.preventDefault();
$('.gradient').gradientGenerator({
colors : [{color:'#4D4C48',percent:0}, {color:'#282827', percent:30}, {color:'#2E2E28', percent: 100}],
direction : 'left'
});

});

See it working here.

How to use a function to change background color with linear gradient?

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>

How to change div background-image with linear-gradient from Javascript

Please try this.

function abc1() {
var pos = document.getElementById("test");
pos.style.background="linear-gradient(to right, #85e085 90%, #ff9999 10%)";
}
<div 
id="test"
style="background: linear-gradient(to right,
#85e085 50%,
#ff9999 50%); width:200px;"
>
dsfhdh2346346
</div>
<input type="button" value="CHANGE" onClick="abc1()" />

How do we change linear-gradient of background image using javascript DOM?

I believe you missed the `` that's all

window.onload = ()=> {

document.querySelector('.image').addEventListener('mousemove',(e)=>{

const style = `linear-gradient(to top right,rgba(${e.offsetX},${e.offsetY},22,0.5),rgba(31, 22, 26, 0.8))`;

console.log(style);

document.querySelector('.image').style.backgroundImage = style;

});

}
<html>

<head></head>

<body>

<image width="200" height="200" class="image" src="" />

</body>

</html>

Change linear-gradient with JS/jQuery

As your code provided is not completed:

  1. What does the variable clr mean?
  2. When will the input value take effects on the background?

Here I would provide a sample code that I try to guess what you want to do as

I mean I want to change background: linear-gradient(red,blue) so that I can use input type="color" to change the color of the gradient

Here is the sample code to use a button to assign the background with gradient color.
Hope this can help you.

$("#btn_color").on('click', function(){

var color = $("#color").val();

var color2 = $("#color2").val();

var str = "linear-gradient(" + color + "," + color2 + ")";

$("body").css("background",str);

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<html>

<head>

<title>Title of the document</title>

</head>

<body>

<div id="part1" align=center>

<input type="color" id ='color'>

<input type="color" id ='color2'>

</div>

<button id="btn_color">Click me </button>

</body>

</html>

JavaScript body.style.background not working with linear-gradient in script.js but works fine in console

In order to do linear gradients via JavaScript like this, you would need to access the body.style.backgroundImage property. You can then pass in your linear-gradient string to build the gradient.

function changeBackgroundColor() {
body.style.backgroundImage = "linear-gradient(to right, "+ color_1.value +", "+ color_2.value +")";

A small note as well, whenever you're passing your string (in this case or any time you're setting CSS properties this way) you do not need to supply the trailing ; that CSS expects. So the line you have:

"linear-gradient(to right, "+ color_1.value +", "+ color_2.value +");";

Notice the first ; you have there. It should be dropped to leave you with this string:

"linear-gradient(to right, "+ color_1.value +", "+ color_2.value +")";

You can find some examples on MDN:

https://developer.mozilla.org/en-US/docs/Web/CSS/background-image

And on W3Schools:

https://www.w3schools.com/jsref/prop_style_backgroundimage.asp

Change color of gradient based on user selection

You can use template literals to have the color picker values dynamically inserted into the CSS.

Also, instead of looping over all the elements and then setting up event handlers for each of the input elements, you can leverage "event delegation" and only set up one event handler.

const picker1 = document.querySelector("input[name='color1']");
const picker2 = document.querySelector("input[name='color2']");

// No need to loop over all the input elements and set up an event
// handler for each. Just set up one event handler at a common ancestor
// of the elements you care about and let the event bubble up to be
// handled there
document.addEventListener("input", function(event){
// Now test to see if the event was triggered by an element you
// wish to handle
if(event.target.classList.contains("colorPicker")){
// Use template literals to insert JS values into a string:
document.body.style.background =
`linear-gradient(90deg, ${picker1.value}, ${picker2.value})`;
}
});
.body{
background:linear-gradient(90deg, blue, red);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="styles.css">
</head>
<body class="body">
<h1>Background Generator</h1>
<input type="color" name="color1" value="#996DAD" class="colorPicker">
<input type="color" name="color2" value="#23AD23" class="colorPicker">

<script src="script.js" charset="utf-8"></script>
</body>
</html>

Dynamically update Linear Gradient CSS

The issue is because you need to concatenate the values in to a string which you set as the value of style.backgroud. As you're already using template literals, try this:

slider.style.background = `linear-gradient(to left, ${gradColor1}, ${gradColor1})`

Note that if you want to specify a gradient you'll need two colours, like this:

var percentage1 = 50;

var color1 = "#C00";

var percentage2 = 100;

var color2 = "#000";

slider.style.background = `linear-gradient(to left, ${color1} ${percentage1}%, ${color2} ${percentage2}%)`;
#slider {

width: 200px;

height: 200px;

}
<div id="slider"></div>


Related Topics



Leave a reply



Submit