Using javascript to change rgb value of background onclick - javascript

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})`

Related

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";

JavaScript rounding to 1 decimal place on inline style attribute

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)

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/

RGB colours in ThreeJS

I have a set of points stored in a giant string, with newline characters \n separating one point from the next. Each point is stored as x y z r g b, where r g b are values ranging from 0-255.
According to the ThreeJS docs, it is possible to do this:
var color = new THREE.Color("rgb(255,0,0)");
However, my points still show up as all white in my ThreeJS viewer. What am I doing wrong?
Code is as follows:
var cloud = data.split('\n');
for (var i=0; i<cloud.length; i++) {
var colour = 'rgb(' + pt[3] + ',' + pt[4] + ',' + pt[5] + ')';
model.vertices.push( new THREE.Vector3(x, y, z) );
colours.push( new THREE.Color(colour) );
}
I realised what my mistake was: I forgot to parse points 3 to 5 as floats.
This fixed it:
var colour = 'rgb(' + parseFloat(pt[3]) + ',' + parseFloat(pt[4]) + ',' + parseFloat(pt[5]) + ')';

JavaScript Changing BG Color

I made a div with background-color set to rgb(0,0,0); and I want to change it's color on click with javascript. I made a function to do that.
function change(){
var x = 1;
var y = x + 100;
document.getElementById("box").style.backgroundColor = "rgb(" + y + "," + y + "," + y + ")"; }
It works fine but I can change the div's color just once. What I want to do is get div's color value and set it to x and run the function again. So the bg will go like black->grey->white on each click. Depending on the y variable.
I can get the div's value but it'll get it in "rgb(0,0,0);" format. I don't know what to do after getting this. How do I manipulate just integers in rgb(0,0,0); ?
You can store current x value in data attributes:
function change(box) {
var x = +box.getAttribute('data-x'), // +box.dataset.x for modern browsers
y = x + 100;
box.style.backgroundColor = "rgb(" + y + "," + y + "," + y + ")";
box.setAttribute('data-x', y);
}
HTML
<div id="box" onclick="change(this)"></div>
Demo: http://jsfiddle.net/Wuz75/
Instead of trying to analyse the color, since your colors will be static, just make an array of colors, and keep track of the index.
var colors = [
"rgb(0,0,0)",
"rgb(100,100,100)",
"rgb(255,255,255)"
],
c = 0;
Then in your function, use c to get the next color, and then increment, or reset to 0.
function change() {
document.getElementById("box").style.backgroundColor = colors[c];
c = ++c % colors.length;
}
So whenever you run the function, it'll switch between colors in the Array.
Or you can use :
function change(x) {
var el = document.getElementById('color');
var rgb = el.style.backgroundColor.replace(/rgb|\(|\)|\s/g, '').split(',');
if ( rgb == "" ) { rgb = [0,0,0] };
for (var a = 0; a < rgb.length; a++ ) {
rgb[a] = parseInt(rgb[a]) + x;
}
el.style.backgroundColor = 'rgb('+rgb.join(',')+')';
}
Here is a demo : http://jsbin.com/ozepaz/1/edit

Categories