Reputation: 1005
So I have a script that converts RGB to HEX, and vise versa. But when I load the page the background is black. So I went to the corresponding part in my code, which is below.
function update() {
var red = parseInt($(".r").val(), 10);
var green = parseInt($(".g").val());
var blue = parseInt($(".b").val());
red = red || 255;
green = green || 255;
blue = blue || 255;
var rgb = RGB2HTML(red, green, blue);
$(".hex").val(rgb);
$("body").css("background", rgb);
}
And I changed
red = red || 0;
green = green || 0;
blue = blue || 0;
To
red = red || 255;
green = green || 255;
blue = blue || 255;
So now when I do 0, 157, 255
I get this
So I go back to the default 0
. And when I enter the same RGB I get this
So my first question is, how can I choose my own background for initial launch without messing up the whole script. My second question is when I enter a HEX with the #
prefix. The script wont run. This is what I expect. But when I do RGB to HEX, it puts a #
in the HEX field. So I want to prevent that from happening. Here's a demo for the black background. Any ideas?
Upvotes: 0
Views: 54
Reputation:
At the bottom of your JavaScript, you have:
$(function () {
$('.r, .g, .b').keyup(update);
update();
});
This is running update();
which sets the background color. You can probably remove that line and add a color to the body
in the CSS to your preferred color.
body {
color:#f00;
transition: 1s;
}
Secondly, when you change an RGB value, the hex value is being updated with a # inside the input because you are explicitly setting that. In update()
you call RGB2HTML()
which performs and sets the hex input to:
return '#' + hex(red) + hex(green) + hex(blue);
Remove that, then you can add it in the last line of update() so the input doesn't get it but it is included when setting the background.
$("body").css("background", "#" + rgb);
In terms of your pink / blue issue, the reason it is not working is because you are setting different colors. When it reaches:
red = red || 255;
red becomes 255 not 0 as entered. In the other instance, r was still 0. A color with r=0 is different than r=255. You can do an isNaN check to check if the resulting integer is valid as opposed to how you are doing it now.
Upvotes: 2
Reputation: 7958
Change it to do this instead to fix the first issue:
red = isNaN(red) ? 255 : red;
green = isNaN(green) ? 255 : green;
blue = isNaN(blue) ? 255 : blue;
For the second issue change RGB2HTML to not return '#':
function RGB2HTML(red, green, blue) {
return hex(red) + hex(green) + hex(blue);
}
and then change $("body").css("background", rgb);
to prepend '#':
$("body").css("background", '#' + rgb);
Upvotes: 1