Getting a random background color in javascript - javascript

I am new to java-script . I need to get a random background color whenever i call a particular function.
I found the following code on the web but i don't quite understand how it works.
Code:
function getRandomColor () {
var hex = Math.floor(Math.random() * 0xFFFFFF);
return "#" + ("000000" + hex.toString(16)).substr(-6);
}
How is the above code working.I understand how Math.random() works but what does hex.toString(16)).substr(-6) basically signify?
Can some one please clarify it to me how the above code works.

function getRandomColor () {
var hex = Math.floor(Math.random() * 0xFFFFFF);
return "#" + ("000000" + hex.toString(16)).substr(-6);
}
hex.toString(16) converts hex into string number representation in base 16.
Syntax:
number.toString(radix)
radix: Base to use for representing a numeric value. Must be an integer between 2 and 36.
2 - The number will show as a binary value
8 - The number will show as an octal value
16 - The number will show as an hexadecimal value
substr(-6) just takes the last 6 characters, which cuts off the "000000" because they're not part of the last 6 characters.

hex.toString(16) converts hex into string number representation in base 16. Then it appends 000000 at the beginning of the string to make sure it will be at least of length 6. and substr(-6) takes last 6 chars of the resulting string. This way you always get # + 6 hex chars. Which represents color.

The code first picks a random number and using the "& 0xFFFFFF" technique it ensures the range is something like 0 to 16777215.
Once we have that random number we convert to hexadecimal using the ".toString(16)" method, the 16 signifying we want hexadecimal conversion.
Now, we can think we have a 6 digit random number in hex to use for our color but know that the ".toString(16)" method does not do any padding for us.
For example, if the random number is 255 which is FF in hex, is not usable as it since it is not precisely 6 digits long.
One technique is to do a string length check and add the corresponding number of 0's to the beginning of the 'FF' to get '0000FF'.
Here we see another technique where you see a fixed number of 0's added to the string and then a fixed length is chopped of the end, ensuring you get 6 digits and correctly padded.
I've always used the string length check or specific padding functions (I don't know if javascript has one) - I only answered the question so as to fully appreciate the technique shown in this question.

/* a complete html page to apply this */
<html>
<body>
<button type="button" onclick="setbodybgcolor()">Random Background</button>
<script>
function setbodybgcolor(){
document.body.style.backgroundColor=getRandomColor ();
}
function getRandomColor () {
var hex = Math.floor(Math.random() * 0xFFFFFF);
return "#" + (hex.toString(16)).substr(-6);
}
/* we can do this also
function setbodybgcolor(){
var hex=Math.floor(Math.random()*16777215).toString(16);
document.body.style.backgroundColor="#"+hex;
}*/
</script>
</body>
</html>

Related

Javascript: Convert Unicode Character to hex string [duplicate]

I'm using a barcode scanner to read a barcode on my website (the website is made in OpenUI5).
The scanner works like a keyboard that types the characters it reads. At the end and the beginning of the typing it uses a special character. These characters are different for every type of scanner.
Some possible characters are:
█
▄
–
—
In my code I use if (oModelScanner.oData.scanning && oEvent.key == "\u2584") to check if the input from the scanner is ▄.
Is there any way to get the code from that character in the \uHHHH style? (with the HHHH being the hexadecimal code for the character)
I tried the charCodeAt but this returns the decimal code.
With the codePointAt examples they make the code I need into a decimal code so I need a reverse of this.
Javascript strings have a method codePointAt which gives you the integer representing the Unicode point value. You need to use a base 16 (hexadecimal) representation of that number if you wish to format the integer into a four hexadecimal digits sequence (as in the response of Nikolay Spasov).
var hex = "▄".codePointAt(0).toString(16);
var result = "\\u" + "0000".substring(0, 4 - hex.length) + hex;
However it would probably be easier for you to check directly if you key code point integer match the expected code point
oEvent.key.codePointAt(0) === '▄'.codePointAt(0);
Note that "symbol equality" can actually be trickier: some symbols are defined by surrogate pairs (you can see it as the combination of two halves defined as four hexadecimal digits sequence).
For this reason I would recommend to use a specialized library.
you'll find more details in the very relevant article by Mathias Bynens
var hex = "▄".charCodeAt(0).toString(16);
var result = "\\u" + "0000".substring(0, 4 - hex.length) + hex;
If you want to print the multiple code points of a character, e.g., an emoji, you can do this:
const facepalm = "🤦🏼‍♂️";
const codePoints = Array.from(facepalm)
.map((v) => v.codePointAt(0).toString(16))
.map((hex) => "\\u{" + hex + "}");
console.log(codePoints);
["\u{1f926}", "\u{1f3fc}", "\u{200d}", "\u{2642}", "\u{fe0f}"]
If you are wondering about the components and the length of 🤦🏼‍♂️, check out this article.

How do I round to 1 decimal on the bbc:microbit with javascript w/o toFixed(), the usual multiplication + divide gives trailing 9999 digits?

temperatureReading = Math.round(temperatureReading * 10) / 10
gives me 26.29999999999999999999 instead of 26.3
And 26.00000000001 instead of 26.0
I get alternating 2 values from the temperature sensor: 26.33 and 26.3200000
After the conversion I have: 26.2999999999999
The number of the repeating digits above is just an example. My display on the micro bit is not wide enough to see them all.
I use toString() to display the values.
Unfortunately, toFixed() and toPrecision() is not available on the micro:bit
Can the rounding be achieved by some other operations?
With the following code I can now get numbers with 1 decimal as a string:
let temperatureStr = Math.round(temperatureReading * 10).toString()
let temperature = temperatureStr.slice(0, temperatureStr.length - 1) + "." + temperatureStr.slice(temperatureStr.length - 1);
I first multiply the number by 10 and convert the result to a string. Then, I insert the decimal point before the last digit. This gives me the string I want to print.

Convert HEX to 4 digit integer

I am trying to convert a HEX string to 4 digit integer. I can change by the following command but I do not want to generate random integer value every time if same HEX string is passing. The integer number must be same. This is not happening in my case:
const reqq = crypto.createHash('md5').update(admin.companyName).digest('hex');
let valueNum = parseInt(reqq, 16);
let resultValue = Math.floor(Math.random(valueNum) * 9000);
admin.companyID = resultValue;
console.log(resultValue);
How can I make this work ?
Your code to convert the hex hash to a decimal number is correct. If you do not want a different companyName to lead to a different hash, you can remove the random call in resultValue. You can verify your hex conversion is correct by using a converter

Creating random number on fractional part between two numbers

I am working on the following code. How can I create random number between 150.570 and 150.720?
As you can see the integer-part (150) is always fixed and I just need to get random on fractional-part (between .570 to .720) only.
var gapLeft = Math.floor(Math.random() * 150.720) + 150.570 ;
console.log(gapLeft);
Here is your solution for this,
console.log(150.57+Math.random()*(0.72-0.57));

How to get an 8 decimal output?

I am trying to get an 8 decimal output from the following function.
The following function multiplies an input by 2 and then updates this input with the wagerUpdate variable. I would like this outputted number to have 8 decimal places.
For example: if input number is 0.00000001 (this code is for a bitcoin website), then I would like output number to be 0.00000002. For some reason the code below is not working properly as the output number is in the format of 2e-8 without the .toFixed(8) code. Please help if you are able to. Thank you so much.
<script>
function MultiplyWagerFunction() {
var wager = document.getElementById("wagerInputBox").value;
var wagerUpdate = wager*2;
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
}
</script>
If you remove the + before wagerUpdate.toFixed(8) it should work fine. wagerUpdate has already be converted to a number when you multiplied it by 2 so there should be no need for the unary +
var a = "0.00000001";
var b = a*2;
console.log(b.toFixed(8));
console.log(+b.toFixed(8));
^ see the difference.
The reason it doesn't work is because what you are doing is equivalent to:
+(b.toFixed(8))
because of the precedence of the operators (member access . is higher than unary +). You are converting b to a string with .toFixed and then converting it back into a number with + and then converting it back into a string again! (this time with the default toString behavior for numbers giving you exponential notation)
Just remove + from +wagerUpdate.toFixed(8); and you would be good.
Instead of:
document.getElementById("wagerInputBox").value = +wagerUpdate.toFixed(8);
try:
document.getElementById("wagerInputBox").innerHTML = +wagerUpdate.toFixed(8);
Why I say so is may be when you set value, browser tries to convert to best possible outcome. But, inner HTML should take the string equivalent!

Categories

Resources