Is there a way to use Linear gradient along with HSLA? - javascript

Im trying to set my background colour based off a formula and HSLA but i want to use it as a Linear gradient.This is what i have, but returns no colour for the last else if statement
if (oneCallDataFromApi && oneCallDataFromApi.current.temp) {
if (kelvinToCelcius(oneCallDataFromApi.current.temp) >= 10) {
var lightness = (100 - (kelvinToCelcius(oneCallDataFromApi.current.temp)));
document.body.style.backgroundColor = `hsla(20,100%,${lightness}%,0.9)`;
} else if (kelvinToCelcius(oneCallDataFromApi.current.temp) < 10) {
lightness = (50 + (kelvinToCelcius(oneCallDataFromApi.current.temp)));
document.body.style.backgroundColor = `linear-gradient(179.31deg, 180,50%,${lightness}%) 9.28%, #F4AC4E 167.45%)`;
}
Edit:
By changing "document.body.style.backgroundColor" to simply "document.body.style.background" worked for me lol

By changing "document.body.style.backgroundColor" to simply "document.body.style.background" worked for me lol

Would be easier, and i mean soooo much easier, if you used css gradient instead of javascript gradient tools or whatever.
such as something cool like this
html{
background: rgb(2,0,36);
background: linear-gradient(90deg, rgba(2,0,36,1) 1%, rgba(9,121,114,1) 31%, rgba(0,212,255,1) 63%);
}
p{
color:white;
}
<html>
<p>Hello there, I'm Lorem</p>
</html>
You can use this website for all your gradient needs

Related

Combine RGB color values in JavaScript to form a blend

So, in JavaScript, if I have a percentage of red and green right, say 35% red, 65% green, how can I combine them? I am not completely sure on the terminology of this, and it is possible that it is simpler than I think.
I see that on http://www.rapidtables.com/web/color/RGB_Color.htm
they have a value that ranges from 0-255. Is it easy to assign a value from 0-255 for both red and green to mix?
If it is not incredibly different, does adding alpha to the mix work too?
I want the color to be able show up in a canvas, but once I have the mixed value this should work fine. So I need a legitimate value that I can put into fillStyle.
var c=document.getElementById("myCanvas");
ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.fillStyle="the blended color";
ctx.fill();
RGB (Red, Green, Blue) have indeed values from 0-255 for each color.
So I assume that converting the percentage in a value within that range should work fine?
As you perform the following code for each color you can combine all values to get an RGB value.
color = (percentage / 100.00) * 255.00
Example snippet
function percentageToRGB(r,g,b) {
var r = parseInt((r/100)*255);
var g = parseInt((g/100)*255);
var b = parseInt((b/100)*255);
return "rgb("+ r +","+ g +","+ b +")";
}
document.getElementById("block").style.background = percentageToRGB(35, 65, 0);
#block {
width: 200px;
height: 100px;
text-align: center;
border: 1px solid black;
line-height: 100px;
}
<div id="block">
Hello
</div>

Generate 3 main colors gradient based on numeric array in Javascript or jQuery

There is a column from a table that contains numeric values unordered. Each td needs to be painted using solid colors in a way that the column forms a unordered gradient.
I created a numeric array which contains those values ordered and now I need to generate the gradient array based on that, so each value of the array will have a corresponding solid color.
Lower numbers must be red, medium numbers must be yellow and higher numbers must be green. All those colors smoothly transiting from itself to the next one.
So basically, the ordered array will have a ordered gradient, but when I paint the column the gradient will become unordered, because the columns values aren't ordered.
What I'm trying to reach is "crescent rank" gradient in that column.
How can I do that with javascript or jQuery?
Modified Answer After Update to Question
I still think I can help you with this. I forked and modified my original JSFiddle to show how this is applied. The CSS stays relatively the same.
It sounds like you want to have specific values for each level of gradient, but I still think the moving "bar" concept works best when applying multi-stop gradients. IE going from one color to a different to another different. This is because it is MUCH less work if you need to modify the gradient colors since you can just change out the background linear-gradient code in the CSS, as well as it gives you the smoothest and realest gradient no matter how many rows you have. The JSFiddle still has the input boxes so you can see each "step" of the gradient. As I said before you can go to a site like www.colorzilla.com/gradient-editor/ and modify the gradient to your needs and even add an in-between color stop if say you don't like the transition from yellow to green.
Here is the jQuery code you would need to input all your values from a table into a multidimensional array. After it is in the array, you can then order each column in the array (since each column is it's own array in the array) and move the background based on the "rank" or index in that array. Since my understanding is that you wanted to sort based on lowest value to highest value, and not say 0 to 100.
//jQuery for table
$("#someTable td").wrapInner("<span class='tdData'></span>");
$(".tdData").wrap("<div class='css3gradient'></div>");
var colVal = [];
var numCol = $("#someTable").find('tr')[0].cells.length;
var numRows = $("#someTable tr").length - 1; //subtract if header
var itemCount = 0;
var gradientWidth = $(".css3gradient").css("width").replace(/[^-\d\.]/g, '')-$(".tdData").css("width").replace(/[^-\d\.]/g, '');
//initialize array
for (var i = 0; i < numCol; i++) {
colVal[i] = new Array();
}
//fill multidimensional array
$("table tr td").each(function () {
curCol = itemCount % numCol;
colVal[curCol].push($(this).text());
itemCount++;
});
//sort values in array and assign value for gradient
for (i = 0; i < numCol; i++) {
//sort values as numbers
colVal[i] = colVal[i].sort(function (a, b) {
return a - b;
});
//match each value in the array in order with value in table
$.each(colVal[i], function (index, value) {
$("#someTable td:nth-child(" + (i + 1) + ")").each(function () {
if ($(this).text() == colVal[i][index]) {
//Multiply current index with
///Divide the total width of gradient box with
////Subtract total number of rows with one to make zero the first left position
////and the last number the final position
$(this).find(".css3gradient").css({ backgroundPosition: '-' + (index * (gradientWidth / (numRows - 1))) + 'px 0' });
}
});
});
}
Feel free to comment again if I've misunderstood something. This has been a really fun problem to solve, and I hope I helped or gave you at least a step in the right direction.
Original Answer
I made a JSFiddle for you that should get you started. Explanation below.
From what I understand, you want to have a background within a div/span/input change colors based on the value in that div/span/input. You would like lower numbers to represent red, and the a gradient to change the color from red > yellow > green, with green being the max color. You would also like this to be controlled by jQuery.
To do that we can stack a couple of divs, and utilize positioning and overflows to “hide” any excess of the div we are using for the background.
First, I’d recommend using a CSS Gradient Generator like the one at http://www.colorzilla.com/gradient-editor/ to generate your CSS code.
Next, lets look at the structure of your data. You’ll want to have 3 elements to get this to work.
The inner element which holds the data. For my example I used an input element so you can change the values and test.
The next element you want is a div which you can use as the “background”. This element will be positioned absolutely so we can move it left to right to get the gradient we want.
Finally you’ll want the outer wrapped div so you can utilize the overflow css rule to hide the excess from the background div.
So for a reference, here is what the html looks like for this particular task:
<div class=“data”><div class=“css3gradient”><input /></div></div>
If you don’t have access to the HTML, a quick fix is to use the .wrap() jQuery function. For instance, if you just had an outer div and input, you could “wrap” the input with
$(“.data input”).wrap(“<div class=“css3gradient”></div>”);
For the gradient div, mathematically, it can get a bit wonky trying to make it “line up”. For my example I just went with a total width to display the data of 100px, and a total width for the gradient background of 1100px;. The reason for the extra 100px on the background is because when you move the element over by 10, you need the extra width to fill the remaining div. IE zero position takes up 0-100, second position takes up 200-300, and the final tenth position takes up 1000-1100. You can apply this method to any width you have by making the width of the gradient div be (x * 10) + x.
This also looks at the data from the standpoint that you go from 0 to 100 as if you are doing %s.
So for my CSS this is what it looks like:
.css3gradient{
width:1100px;
height:100px;
position:absolute;
background: #ff0000; /* Old browsers */
background: -moz-linear-gradient(left, #ff0000 0%, #ffff00 50%, #00ff00 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, right top, color-stop(0%,#ff0000), color-stop(50%,#ffff00), color-stop(100%,#00ff00)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(left, #ff0000 0%,#ffff00 50%,#00ff00 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(left, #ff0000 0%,#ffff00 50%,#00ff00 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(left, #ff0000 0%,#ffff00 50%,#00ff00 100%); /* IE10+ */
background: linear-gradient(to right, #ff0000 0%,#ffff00 50%,#00ff00 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ff0000', endColorstr='#00ff00',GradientType=1 ); /* IE6-9 */
}
.data {
width: 100px;
height: 50px;
vertical-align: middle;
position: relative;
overflow: hidden;
border: 1px solid #000;
margin: 3px;
}
.data input {
width: 100px;
height: 50px;
background: transparent;
border: 0;
text-align: center;
}
Finally, the fun part. We have to actually move this background based on the value in the input. I’m not sure if you have some sort of input or dynamic way your changing the values within each element. At any rate, this jQuery will get you started.
$(".data input").each(function(){
var dataValue = $(this);
//call this initially set the background based on the value
changeColor(dataValue.val());
//this is what allows the background to change dynamically when you type into the input element
dataValue.bind("keyup change input",function(){
changeColor(dataValue.val());
});
function changeColor(e) {
var mulitplyColor = e * 10;
dataValue.parent(".css3gradient").css({backgroundPosition: '-' + mulitplyColor + 'px 0'});
}
});
Hope this helps!

X sections within a div

I saw this
And thought it would be cool if I can dynamically change the colors and width of the colors with JS. The problem is I can use divs, but prefer not to. I've already tried gradients, but it didn't seem to work as expected. Any ideas on how to go about this? Additionally I'm not asking you to code this for me, rather a step of help. When I use it the div way and say set it to 33%, only 33% of the gradient shows. Not the 33% that corresponds to the color.
.a{
background-image:
linear-gradient(
to right,
#fffdc2,
#009dff 15%,
#000 15%,
#000 85%,
#fffdc2 85%
);
position: fixed;
z-index: 1031;
top: 0;
height: 4px;
transition:all 1s;
}
Gradient is definitely the way to go. Use percentage positions for the colour stops.
For example, try this function:
function generateCSSGradient(colours) {
var l = colours.length, i;
for( i=0; i<l; i++) colours[i] = colours[i].join(" ");
return "linear-gradient( to right, "+colours.join(", ")+")";
}
var cols = [
["red","0%"],
["red","40%"],
["yellow","40%"], // note same percentage - this gives a crisp change
["yellow","60%"],
["green","60%"],
["green","80%"],
["blue","80%"],
["blue","100%"]
];
yourElement.style.background = generateCSSGradient(cols);
You can adjust and vary the colours however you want - add more, move them, change them, anything goes!

CSS transitions & timing seem off

First I am open to any ideas / suggestions. I desire to keep the home page as is as far as using the variety of scenic images. The problem I run into is of course what is readable font color on one image is not very readable on another. So I googled some ideas and found a darkened area / backdrop to be the most professional. Great now it works well for all light images but not dark images. So I came up with the idea of switching font color and background depending on the image (dark or light). The trouble I am having is that the font / background switch about 1-2 seconds before the image does??? Further I think I would like to add a cross fade or some animation effect to make the switch soother. Here is the site:
http://alexandredairy.com/staging/
Again I am open to any ideas / suggestions
So the first thing I did was to name the images with a dark or light prefix so the css can switch accordingly. So I have twenty or so images named like so:
Dark_Cover1_PastrDairy.jpg or Light_Cover1_PastrPoultry.jpg
My CSS is:
/*Back ground shading so we can read text*/
.lighttextbackground
{
color:#000;
background-color:rgba(255, 255, 255, 0.35);
box-shadow:0px 0px 10px 10px rgba(255, 255, 255, 0.35);
}
.lighttextbackground a
{
color:#000;
}
.lighttextbackground p
{
color:#000;
}
.darktextbackground
{
color:#fff;
background-color:rgba(0, 0, 0, 0.35);
box-shadow:0px 0px 10px 10px rgba(0, 0, 0, 0.35);
}
.darktextbackground a
{
color:#fff;
}
.darktextbackground p
{
color:#fff;
}
A typical HTML element that I want the effect on is:
<div id="pageslogan" class="slogan lighttextbackground">
....code...
</div>
As for the jquery I am posting just the function(s) I think relevant. I can definately post more if needed or you can browse the site and get everything using developer tools (F12).
function changeImageHandler(){
var imgSRC;
$("#inner ul>li").eq(currImg).addClass("active");
$("#inner ul>li").eq(prevImg).removeClass("active");
loadComplete = false;
image.addClass("topImg").css({"z-index":1});
imgSRC = imageSRCLink.eq(currImg).attr("href");
imageHolder.append("<img class='bottomImg' src="+imgSRC+" alt=''>");
$(".bottomImg").css({display:"none", "z-index":0}).bind("load", loadImageHandler);
$("#imgSpinner").css({display:"block"}).stop().animate({opacity:1}, 500, "easeOutCubic");
imgName = imageSRCLink.eq(currImg).attr("href").split('/')[2];
TextReadabilityHandler(imgName.substring(0, 5));
discription.eq(currImg).css({left:$(document).width()*dragDirection, display:"block"}).animate({left:0}, 1000, "easeInOutCubic");
discription.eq(prevImg).animate({left:$(document).width()*dragDirection*-1}, 1000, "easeInOutCubic", function(){
discription.eq(prevImg).css({display:"none"})
});
}
About 3/4 the above function you see TextReadabilityHandler which is where the switch takes place:
function TextReadabilityHandler(_imgNameSwitch)
{
if(_imgNameSwitch == 'Light')
{
$("#pagetitle").attr('class', 'sitetitle lighttextbackground');
$("#pagemenu").attr('class', 'sf-menu lighttextbackground');
$("#pageslogan").attr('class', 'slogan lighttextbackground');
}
else if (_imgNameSwitch == 'Dark_')
{
$("#pagetitle").attr('class', 'sitetitle darktextbackground');
$("#pagemenu").attr('class', 'sf-menu darktextbackground');
$("#pageslogan").attr('class', 'slogan darktextbackground');
}
else
{ alert(_imgNameSwitch); }
}
So I was thinking to do a crossfade while the image switches. Where I am stumped is how to implement. As I have it written the html element is updated with a new class and that change is applied instantly. How / where would I implement a .fadeOut() / .fadeIn()??
Thank You
As a side note I tried submitting my site to csscreator.com for critical review / suggestions on the design with no feedback. Any suggestion where I can get the design critiqued would be helpful.
Edit
Thank you user3037493 and Zeaklous.
You both broke through the road block I was up against. Here is what your answers triggered in my brain.
I added a custom namespace (for readability)
/* Text Readability switching */
var txtread =
{
onReady: function(_imgname)
{
txtread.fadeoutText(_imgname);
txtread.fadeinText();
},
fadeoutText: function(_imgname)
{
$("#pagetitle").fadeOut(1250);
$("#pagemenu").fadeOut(1250);
$("#pageslogan").fadeOut(1250);
$("#sitecopy").fadeOut(1550, txtread.TextReadabilityHandler(_imgname));
},
fadeinText: function()
{
$("#pagetitle").fadeIn(1250);
$("#pagemenu").fadeIn(1250);
$("#pageslogan").fadeIn(1250);
$("#sitecopy").fadeIn(1250);
},
TextReadabilityHandler: function(_imgNameSwitch)
{
if(_imgNameSwitch == 'Light')
{
$("#pagetitle").attr('class', 'sitetitle lighttextbackground');
$("#pagemenu").attr('class', 'sf-menu lighttextbackground');
$("#pageslogan").attr('class', 'slogan lighttextbackground');
}
else if (_imgNameSwitch == 'Dark_')
{
$("#pagetitle").attr('class', 'sitetitle darktextbackground');
$("#pagemenu").attr('class', 'sf-menu darktextbackground');
$("#pageslogan").attr('class', 'slogan darktextbackground');
}
else
{ alert(_imgNameSwitch); }
}
}
and then I modified the these two lines in ChangeImageHandler.
imgName = imageSRCLink.eq(currImg).attr("href").split('/')[2];
TextReadabilityHandler(imgName.substring(0, 5));
to
imgName = imageSRCLink.eq(currImg).attr("href").split('/')[2];
txtread.onReady(imgName.substring(0, 5));
So the whole thing looks like this:
function changeImageHandler(){
var imgSRC;
$("#inner ul>li").eq(currImg).addClass("active");
$("#inner ul>li").eq(prevImg).removeClass("active");
loadComplete = false;
image.addClass("topImg").css({"z-index":1});
imgSRC = imageSRCLink.eq(currImg).attr("href");
imageHolder.append("<img class='bottomImg' src="+imgSRC+" alt=''>");
$(".bottomImg").css({display:"none", "z-index":0}).bind("load", loadImageHandler);
$("#imgSpinner").css({display:"block"}).stop().animate({opacity:1}, 500, "easeOutCubic");
imgName = imageSRCLink.eq(currImg).attr("href").split('/')[2];
txtread.onReady(imgName.substring(0, 5));
discription.eq(currImg).css({left:$(document).width()*dragDirection, display:"block"}).animate({left:0}, 1000, "easeInOutCubic");
discription.eq(prevImg).animate({left:$(document).width()*dragDirection*-1}, 1000, "easeInOutCubic", function(){
discription.eq(prevImg).css({display:"none"})
});
}
and now I have my fade in / out effect and while the text blocks are faded out I do a quickie class change by making the copyright fadeout take a bit longer (ensuring vast majority of content is gone) then executing the return function to switch classes as seen in my custom namespace here:
$("#sitecopy").fadeOut(1550, txtread.TextReadabilityHandler(_imgname));
Of course nothing works perfectly and for some reason I haven't figured out yet one element is not fading in / out?? That is off topic here so I posted a new SO question here for that one.
Element refusing to fade out or in
sorry, i dont have enough reputation to comment on your question, and this answer is really just a comment.... white text with black background is going to be easier to read. here is a JSfiddle http://jsfiddle.net/Kyle_Sevenoaks/ZnfED/1/
basically, the css for your .slogan p you would make the color to be white and add this text shadow
{text-shadow:
-1px -1px 0 #000,
1px -1px 0 #000,
-1px 1px 0 #000,
1px 1px 0 #000;}
edited to add: to have the textbackground change before the image, call TEXTREADABILITYHANDLER at the beginning of the changeImageHandler function and maybe try putting a delay on the imgSpinner.animate per http://api.jquery.com/delay/
You could try doing it yourself as this SO answer and corresponding example describe, but depending on the image it is liable to be incorrect more so than if you went with an actual plugin
Background Check is what I would likely recommend. It's not exactly what you are requesting, but it changes the background of elements as well as the text on top of it. One added, you can use it simply by declaring
BackgroundCheck.init({
targets: '.ui', // Select the divs to have the background changed
images: '.thumbnail' // Select the list of images to be analyzed
});

Changing the colour inside characters/Font

Firstly, I need to say I am not a web developer, but I have managed to create a HTML5 and CSS3 web site by learning from as many tutorials as possible, also hacking code together from Google searches.
On my web site I would like to display environmental information: Temperature, Humidity, Air Pressure, etc.
I would like to know if the following is possible and if someone can point me in the right direction?
What I would like to do is display the value of the Temp. and have the colour inside the digits related to the Temp.
So for example:
If the Temp is below 10'C, then colour inside the digits is dark blue
If the Temp is between 10'C - 20'C, then the colour inside the digits is dark blue at the bottom and fades to light blue at the top of the digits
If the Temp is between 20'C - 30'C, then the colour inside the digits is light blue at the bottom and fades to orange at the top of the digits
If the Temp is between 30'C - 40'C, then the colour inside the digits is orange at the bottom and fades to red at the top of the digits
If the Temp is above 40'C then the colour inside the digits is red
I hope it makes sense
Thank-you in advance
Gregg
You can use some classes having different background colors like.
in css
.cssclassname1{
background-color:blue;
}
.cssclassname2{
background-color:blue;
}
in html
<div class="cssclassname1">below 10</div>
<div class="cssclassname2">above 10</div>
Hope this helps...
i have tried something but i cant define all ur condiotions
demo
HTML
<p>If the Temp is below 10C, then colour inside the digits is dark blue.<br>
If the Temp is above 40C then the colour inside the digits is red</p>
JS
$.fn.wrapInTag = function(opts) {
var o = $.extend({
words: [],
tag: '<strong>'
}, opts);
return this.each(function() {
var html = $(this).html();
for (var i = 0, len = o.words.length; i < len; i++) {
var re = new RegExp(o.words[i], "gi");
html = html.replace(re, o.tag + '$&' + o.tag.replace('<', '</'));
}
$(this).html(html);
});
};
$('p').wrapInTag({
words: ['10C', 'dark blue'],
tag: '<span>'
});
$('p').wrapInTag({
words: ['40C', 'red'],
tag: '<span1>'
});
You can get a good effect using background-clip: text.
This is only supported by webkit and mozilla, though.
I have prepared a demo for Chrome. The CSS is
.text {
font-size: 100px;
background-image: linear-gradient(0deg, red, orange, yellow, lightblue, blue);
background-size: 100% 400%;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
-webkit-animation: colors 10s infinite linear;
-webkit-text-stroke: 1px black;
}
#-webkit-keyframes colors {
0% {background-position-y: 300%;}
100% {background-position-y: 0%;}
}
In this demo, the background is clipped by the text, so that it will show only inside the numbers. To let it show we need also to make the text transparent. (and to make it a little nicer, we set a stroke around the font.
Then, we create a gradient background with the colors that you want, and just for fun we animate it.
In your code, the background-position would be set according to the temperature.
Notice that with that system, you can do it continous. (that is, a slightly different color for every temperature
demo
Js Fiddle Example here
(If your browser lacks webkit support, try this example instead.)
Probably the simplest way to control what the text looks like is to use css to define different styles (or colors as you've said) and then use javascript to set the class of a span tag around the temperature value text.
Some Sample HTML
<html>
<head>
<script src="[path to your .js file]"></script>
<link rel="stylesheet" href="[path to your .css file]" />
</head>
<body onload="initialize();">
<p>The temperature today is <span id="tempVal"></span></p>
</body>
</html>
Your javascript file:
var curTemp; // this will contain the current temperature
var curClassName; // the name of the class for that temperature (reflects css code below)
var valueContainer;
function initialize()
{
valueContainer = document.getElementById("tempVal");
}
//... calculate or set the current temperature value here ...
if (curTemp < 10)
curClassName = "freezing";
else if (curTemp >= 10 && curTemp < 20)
curClassName = "cold";
else if (curTemp >= 20 && curTemp < 30)
curClassName = "warm";
else if (curTemp >= 30 && curTemp <= 40)
curClassName = "hot";
else if (curTemp > 40)
curClassName = "scorching";
valueContainer.innerHTML = curTemp + "C";
valueContainer.setAttribute("class", curClassName);
This just leaves your CSS file. Now currently, the only way to achieve this gradient effect without using a canvas element is to use some webkit properties. These are not universally supported, so for maximum portability, I would simply use different solid colors rather than gradients, but here's the webkit example.
#tempVal
{
font-weight: bold;
}
.freezing
{
color: blue;
}
.cold
{
background: -webkit-linear-gradient(top, lightblue, blue);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.warm
{
background: -webkit-linear-gradient(top, orange, lightblue);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.hot
{
background: -webkit-linear-gradient(top, red, orange);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.scorching
{
color: red;
}
Check out the example here
If your numbers aren't coming up with a gradient color, it's because your browser doesn't support the webkit features.

Categories