JavaScript rounding to 1 decimal place on inline style attribute - javascript

I have function which is generating random RGBA color and if I log it to the console it is rounding to on decimal place(that is what I want), but if you open console and try this as inline style attribute on body element you can see that it's not rounding to one decimal place ? Where is the problem ?
JSFIDDLE(backgroundColor)
setInterval(function foo (){
document.body.style.backgroundColor = ("rgba(" + Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + "," + Math.random().toFixed(1)) + ")";
},1000);
JSFIDDLE(console.log)
JS
setInterval(function foo (){
console.log(("rgba(" + Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + "," + Math.round(Math.random() * 255) + "," + Math.random().toFixed(1)) + ")");
},1000);
If you compare these two fiddles you can see the difference.So why are they different? It is same function and it should be same, right ?

The browser internally stores the alpha value as 1 byte, not as a float. When for example you say you need a 0.5 alpha, the browser converts that into 1 byte integer using this:
Math.floor(255 * 0.5)
When you query the result back, it wil convert that integer back to 0-1 range by dividing with 255.
This will result in an incorrect alpha. I've tested this using this:
rgba(134,78,73,0.5) //the color outputed by javascript
rgba(134, 78, 73, 0.498039) //the color that was read back from the style
0.498039 = Math.floor(255 * 0.5) / 255; (of course with some rounding)

Related

How to ROUND Decimal in JQUERY [duplicate]

This question already has answers here:
jQuery - Round to 2 decimal places and calculate with that number
(4 answers)
Closed 4 years ago.
$(document).ready(function() {
$('select').on('change', function() {
$('.total_result').text(
$('select[name=attendance]').val() * 0.25 + $('select[name=tardiness]').val() * 0.10 + $('select[name=rules]').val() * 0.05 + $('select[name=case]').val() * 0.05 + $('select[name=productivity]').val() * 0.15 + $('select[name=qa]').val() * 0.15 + $('select[name=utilization]').val() * 0.05 + $('select[name=schedule]').val() * 0.05 + $('select[name=fcr]').val() * 0.10 + $('select[name=aht]').val() * 0.05)
;
});
});
I have an issue with my final code. I need to round the decimal.
I'm using onchange that will auto calculate.
Much appreciated. TIA
.toFixed(2); method is Used to round value.
in you example it will be like
$(document).ready(function() {
$('select').on('change', function() {
$('.total_result').text(($('select[name=attendance]').val() * 0.25 + $('select[name=tardiness]').val() * 0.10 + $('select[name=rules]').val() * 0.05 + $('select[name=case]').val() * 0.05 + $('select[name=productivity]').val() * 0.15 + $('select[name=qa]').val() * 0.15 + $('select[name=utilization]').val() * 0.05 + $('select[name=schedule]').val() * 0.05 + $('select[name=fcr]').val() * 0.10 + $('select[name=aht]').val() * 0.05).toFixed(2));
});
});
Reference LINK

javascript background image not changing

I need to change the background image of an img element, so I can show an sprite (a card sprite, in this case)
I have this code:
document.getElementById("cardImg").style.background = "url(cards.jpg)" + (-349 / 13 * card) + "px " + (-36 * Math.floor(Math.random() * 4));
Where the card variable is a number that goes from 0 to 12
This is part of a bigger function, but when I execute that function the image does not change sometimes, and sometimes it does.
And I have thired to do things like changing url(cards.jpg) to url(cards.jpg?v=Math.random())but it does not change anything
Thanks for your help
let card = 1;
console.log("url(cards.jpg)" + (-349 / 13 * card) + "px " + (-36 * Math.floor(Math.random() * 4)));
The error here is very obvious.
You should have a space seperating ...jpg) -26... from url(cards.jpg)-26.846153846153847px -36.
You do not have a unit (e.g., px, em, etc) at the last number.
See this fiddle for reference.
Example https://jsfiddle.net/trupti11/0yofLkfu/
JS
var cards = "https://i.imgur.com/kABxZg1";
var posX = 200;
var posY = 500;
document.getElementById("cardImg").style.background = "url(" + cards + ".jpg) "+posX+"px "+ posY+"px";

Shift a color in order to obtain a specific contrast ratio

Is there a way, given two colors (let's call them first color and second color) to figure out what color the second color must be changed to in order to obtain a contrast ratio of 4.5? In other words, what amount do we need to shift the second color in order to obtain a contrast ratio of 4.5? The luminance and ratio code are as follows:
Luminance Code:
function getLuminance (rgb){
for (var i =0; i<rgb.length; i++) {
if (rgb[i] <= 0.03928) {
rgb[i] = rgb[i] / 12.92;
} else {
rgb[i] = Math.pow( ((rgb[i]+0.055)/1.055), 2.4 );
}
}
var l = (0.2126 * rgb[0]) + (0.7152 * rgb[1]) + (0.0722 * rgb[2]);
return l;
};
Ratio Code:
var ratio = 1;
var l1 = getLuminance([first_color_red.value/255, first_color_green.value/255, first_color_blue.value/255]);
var l2 = getLuminance([second_color_red.value/255, second_color_green.value/255, second_color_blue.value/255]);
if (l1 >= l2) {
ratio = (l1 + .05) / (l2 + .05);
} else {
ratio = (l2 + .05) / (l1 + .05);
}
The problem i'm facing is with the luminance calculation - just based on a ratio, it seems like it is not possible to figure out the R, G and B values as they would be three unknowns (depends on which path each of the colors takes - is it greater than 0.03928 or not...).
We can add in more constraints by considering the color brightness and color difference calculations as shown below:
Color Brightness Code:
The threshold for brightnessDifference is that it is greater than or equal to 125.
fY=((first_color_r.value * 299) + (first_color_g.value * 587) + (first_color_b.value * 114)) / 1000;
sY=((second_color_r.value * 299) + (second_color_g.value * 587) + (second_color_b.value * 114)) / 1000;
brightnessDifference = Math.abs(fY-sY);
Color Difference Code:
The threshold for colorDifference is that it is greater than or equal to 500.
colorDifference = (Math.max (second_color_r.value, first_color_r.value) - Math.min (second_color_r.value, first_color_r.value)) +
(Math.max (second_color_g.value, first_color_g.value) - Math.min (second_color_g.value, first_color_g.value)) +
(Math.max (second_color_b.value, first_color_b.value) - Math.min (second_color_b.value, first_color_b.value));
I have read the following post: How to pick good contrast RGB colors programmatically?
However, calculating complementary colors may not always solve the problem! It may not even result in a contrast ratio of 4.5 ... Any ideas on how this may be accomplished?

Using javascript to change rgb value of background onclick

I'm trying to implement a very simple JavaScript program: every time you click the button, the RGB values of the background color are randomized.
Here's the Javascript:
function change() {
var x = Math.floor(Math.random() * 256); // range is 0-255
var y = Math.floor(Math.random() * 256);
var z = Math.floor(Math.random() * 256);
var thergb = "'rgb(" + x + "," + y + "," + z + ")'";
console.log(thergb);
document.body.style.background=thergb;
}
I'm pretty sure the problem is in how I hack together the thergb variable, but there are no errors in the console so I'm not quite sure. I log the console just to make sure it's giving me an actual random rgb, which it is.
Here's the full JSFiddle: http://jsfiddle.net/L92bY/
You have wrapped it in ' .. why ?
If you remove that it works..
var thergb = "rgb(" + x + "," + y + "," + z + ")";
Demo at http://jsfiddle.net/gaby/L92bY/9/
(you also needed to define the change function in the head tag and not in the onLoad event..)
The CSS syntax for an rgb() value does not include single quotes.
Change 'rgb(x,y,z)' to rgb(x,y,z).
Two things:
You need to choose one of the "nowrap" options for where the fiddle server puts your code.
You need to get rid of the single-quote characters around your "rgb()" expression.
var thergb = "rgb(" + x + "," + y + "," + z + ")";
Personally I'd set "backgroundColor" instead of just "background", but it works (in Firefox at least) to set "background".
Fixed fiddle.
Working fiddle (just corrected your code): http://jsfiddle.net/L92bY/18/
The syntax for the CSS color as rgb is rgb(r,g,b) (no extra apostrophe "'") = not 'rgb(r,g,b)'
function change() {
var x = Math.floor(Math.random() * 256); // range is 0-255
var y = Math.floor(Math.random() * 256);
var z = Math.floor(Math.random() * 256);
var thergb = "rgb(" + x + "," + y + "," + z + ")";
console.log(thergb);
document.body.style.background=thergb;
}
PS: If this is not working for you you are calling this javascript function BEFORE it was declared.
You could probably also just simplify where your code went wrong by using string template literals.
var thergb = `rgb(${x}, ${y}, ${z})`

Assigning a variable to the value of style property not working

I must be overlooking something, but the below code is not working for me (sorry for something so basic):
(function(){
document.body.addEventListener("click", function(){
var test = "rgb(" + parseInt((9.3 * Math.random())) + "," + parseInt((9.1 * Math.random())) + "," + parseInt((102 * Math.random())) + ");";
this.style.backgroundColor = test;
console.log(test); // corretly outputs rgb(12, 20, 30)
}, false);
})();
Using a string as the value works and assigning a variable to a string containing an rgb value also works, but using test as the value doesn't work, and doesn't show any console errors. Why is this?
It does not correctly output rgb(12, 20, 30), it outputs rgb(12, 20, 30);
You are setting
this.style.backgroundColor = "rgb(12, 20, 30);";
There is a semicolon which is causing the value to be invalid. You need to remove the semicolon from the string
+ ");";
^
It should be
+ ")";
You don't need to pass ; at the end
var test =
"rgb("
+ parseInt((9.3 * Math.random()))
+ ","
+ parseInt((9.1 * Math.random()))
+ ","
+ parseInt((102 * Math.random())) + ")";
Remove ; from + ");"
DEMO
Also your colour range is not big enough to notice a difference, 12, 30 and 7 will look similar. try this:
(function () {
document.addEventListener('click', function () {
var r = Math.round(Math.random() * 255),
g = Math.round(Math.random() * 255),
b = Math.round(Math.random() * 255);
document.body.style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')';
});
})();
Here is a working fiddle:
http://jsfiddle.net/kmturley/7zNv6/

Categories