-1

How can I change the first color only in CSS linear gradient using Javascript?

div {
    background: -webkit-linear-gradient(top, #F6F6F6, #E9E9E9)
}

as you can see I want to change the color "#F6F6F6" only.

the script must be in Javascript not jquery.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Haithomy
  • 73
  • 2
  • 8

2 Answers2

0

Just remove the class from the div and add a new class with the new attributes.

Fiddle : https://jsfiddle.net/reko91/suuwe4wc/4/

I would add another class that applies to all divs, in this case 'divs' and the linearGradient class too.

<div class='divs linearOne'>
</div>

Only added JQuery for button click

var divs = document.getElementsByClassName('divs');

var toggle = false; //used to toggle between

document.getElementById('clickme').addEventListener("click", function (event) {
  if(!toggle){ 
      divs[0].classList.remove('linearOne')
      divs[0].classList.add('linearTwo');
      toggle = true;
    } else {
      divs[0].classList.add('linearOne')
      divs[0].classList.remove('linearTwo');
      toggle=false;
      }

})
.linearOne {
  width:100px;
  height:100px;
  background: -webkit-linear-gradient(top, #F6F6F6, #E9E9E9)
}

.linearTwo {
  width:100px;
  height:100px;
  background: -webkit-linear-gradient(top, #000000, #F6F6F6)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='divs linearOne'>

</div>

<button id='clickme'>
Toggle Gradient
</button>
thatOneGuy
  • 9,977
  • 7
  • 48
  • 90
0

If your <div> has an id, using JavaScript to change the background to (1) another gradient, (2) some color, or (3) no background at all is really as simple as this :

document.getElementById('anotherGradient').style.background = "-webkit-linear-gradient(top, #00E9E9, #F6F600)";
document.getElementById('greyBackground').style.background = "#E9E9E9";
document.getElementById('noBackground').style.background = "none";
div {
    background: -webkit-linear-gradient(top, #F6F6F6, #E9E9E9)
}
<div id="anotherGradient">
    This DIV should have a different gradient
</div>
<div id="greyBackground">
    This DIV should have a grey background but no gradient
</div>
<div id="noBackground">
    This DIV should not have any background at all
</div>
<div>
    This DIV should have the original gradient
</div>
<div>
    This DIV should have the original gradient
</div>
(see also this Fiddle)
John Slegers
  • 45,213
  • 22
  • 199
  • 169