I want to create a script where a user can set the gradient of a div by inputting color codes in two different text fields.
This is my code:
<style>
#gradient {
background: #0A284B;
background: -webkit-gradient(linear, left top, left bottom, from(#0A284B), to(#135887));
background: -webkit-linear-gradient(#0A284B, #135887);
background: -moz-linear-gradient(top, #0A284B, #135887);
background: -ms-linear-gradient(#0A284B, #135887);
background: -o-linear-gradient(#0A284B, #135887);
background: linear-gradient(#0A284B, #135887);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0A284B', endColorstr='#135887');
zoom: 1; }
</style>
<script>
function myFunction()
{
color1 = document.getElementById("color1").value;
color2 = document.getElementById("color2").value;
document.getElementById("gradient").style.background="-webkit-gradient(linear, left top, left bottom, from("+color1+"), to("+color2+"))";
document.getElementById("gradient").style.background="-webkit-linear-gradient("+color1+", "+color2+")";
document.getElementById("gradient").style.background="-moz-linear-gradient(top, "+color1+", "+color2+")";
document.getElementById("gradient").style.background="-ms-linear-gradient("+color1+", "+color2+")";
document.getElementById("gradient").style.background="-o-linear-gradient("+color1+", "+color2+")";
document.getElementById("gradient").style.background="linear-gradient("+color1+", "+color2+")";
document.getElementById("gradient").style.filter="progid:DXImageTransform.Microsoft.Alpha(startColorstr='"+color1+"', endColorstr='"+color2+"')";
}
</script>
<input type="text" id="color1" onkeyup="myFunction()" value="#E9EDF6"></input>
<input type="text" id="color2" onkeyup="myFunction()" value="#AABBDD"></input>
<div id="gradient" style="height:500px">
I have gradient
</div>
The function works fine in Firefox and IE10, but not in older IE versions.
I am guessing it’s because the last background call overwrites the others which are meant for older IE versions.
So how would you go about this?
Should I create a function which first checks the browser used before calling the color change function?
You may want to take a look at the amazing Ultimate CSS Gradient Generator.
As you can see, it generate more code than what you do, with comments at the end of each line indicating which browsers are affected by that line:
Specifically, the last line is what you need, used for IE6-IE9.
You may want to include first line too, for older browsers (IE5.5…) that do not handle Gradients.
EDIT
Add the filter part in javascript too, after the other lines:
And, according to this answer, be sure to set
overflow: autoor to set an height to your object.EDIT #2
You are right, it will break with the other properties (with in CSS does not affect it).
Then check if it’s IE, and use this JS: