Generating a random color not working - javascript

I was working on a simple project, to have the background of a webpage change every time you click on it. I succeeded in such, tested it a few times, save, tested again, and then left.
I go home and load it.. And it no longer works. I am using the same browser, I have no idea how anything could have changed.. I must have messed up a few ways almost impossible it feels like.. But alas, I'm sitting here dumb-founded..
Could anyone take a look at my simple program and tell me what is wrong? (Again, the program purpose is to change the webpage's background color to a random color whenever you click on the page.)
Here is the code:
<!DOCTYPE HTML PUBLIC>
<html>
<head>
<title>Random Colors</title>
<script language="javascript">
function randomColor() {
var h0 = Math.floor(Math.random()*99);
var h1 = Math.floor(Math.random()*99);
var h2 = Math.floor(Math.random()*99);
var h3 = Math.floor(Math.random()*99);
var h4 = Math.floor(Math.random()*99);
var h5 = Math.floor(Math.random()*99);
return '#'.toString(16)+h0.toString(16)+h1.toString(16)+h2.toString(16);+h3.toString(16)+h4.toString(16)+h5.toString(16);
}
</script>
</head>
<body onclick="document.bgColor=randomColor();">
</body>
</html>
Thanks in advance if anyone can help.

Having '#'.toString(16) makes no sense, the string '#' can't be converted to a string in hexadecimal form...
You have an extra semicolon after h2.toString(16).
return '#'+h0.toString(16)+h1.toString(16)+h2.toString(16)+h3.toString(16)+h4.toString(16)+h5.toString(16);
I think that you want to keep each digit in the range 0-15 instead of 0-98:
var h0 = Math.floor(Math.random()*16);

Try this out. Built off of what #Guffa did
function randomColor() {
var h0 = Math.floor(Math.random()*16);
var h1 = Math.floor(Math.random()*16);
var h2 = Math.floor(Math.random()*16);
var h3 = Math.floor(Math.random()*16);
var h4 = Math.floor(Math.random()*16);
var h5 = Math.floor(Math.random()*16);
return '#' + h0.toString(16) + h1.toString(16) + h2.toString(16) + h3.toString(16) + h4.toString(16) + h5.toString(16);
}
Here's the fiddle --> http://jsfiddle.net/Jh5ms/1/

Is there a reason you're using Math.random so many times?
function pad6(s) {
s = '' + s;
return '000000'.slice(s.length) + s;
}
function randomColor() {
var rand = Math.floor(Math.random() * 0x1000000);
return '#' + pad6(rand.toString(16)).toUpperCase();
}
randomColor(); // "#7EE83D"
randomColor(); // "#19E771"

As pointed out by Guffa, your first error was attempting to convert '#' to a hexadecimal representation.
This should do the trick:
function randomColor() {
var ret = Math.floor(Math.random() * (0xFFFFFF + 1)).toString(16);
return ('#' + new Array((6 - ret.length) + 1).join('0') + ret);
}
window.onload = function() {
document.querySelector('button').onclick = function() {
document.querySelector('body').style.backgroundColor = randomColor();
};
};
Here is a demonstration.
Here is another demonstration showing how you could implement it into your current page. I also took the liberty of changing your event handler to be unobtrusive.

Adding to Guffa fixing the Math.random()*99 problem, I would put all this in a loop like this:
var theColor = "#";
for (var i = 0; i < 6; i++) {
theColor += Math.floor(Math.random() * 16).toString(16);
}
return theColor;
Here's a jsFiddle

another answer in your format - pass this to whatever you want to change backgroundcolor
http://jsfiddle.net/FpLKW/2/
<div onclick="test(this);">
</div>
function test (ele) {
var h0 = Math.floor(Math.random()*10);
var h1 = Math.floor(Math.random()*10);
var h2 = Math.floor(Math.random()*10);
var h3 = Math.floor(Math.random()*10);
var h4 = Math.floor(Math.random()*10);
var h5 = Math.floor(Math.random()*10);
var x = '#' + h0.toString(16) + h1.toString(16) + h2.toString(16) + h3.toString(16) + h4.toString(16) + h5.toString(16);
ele.style.backgroundColor=x;
}

Related

Changing linear-gradient with Javascript not working

I'm trying to change the linear gradient with JavaScript in my project. My problem is that after running the code nothing happens. If I try to use the linear-gradient string directly in my CSS class container, everything works fine but it doesn't work with changing it via JavaScript. Here's the code I'm trying to run:
function init() {
var Lohn = "undefined";
var Datum = "undefined";
var Pausenstueck = "undefined";
var Zakstueck = "undefined";
var Ueberstundenstueck = "undefined";
var StundeKoord = "undefined";
var Tagesdauer = "undefined";
let UebersichtTemplate = document.createElement("dd");
let UebersichtDD = document.getElementById("Uebersicht_Window_child");
UebersichtTemplate.innerHTML = "<span class='textRight'>" + Lohn + "</span><span class='text'>" + Datum + "</span>";
let a = document.importNode( UebersichtTemplate,true);
a.classList.add("percentage", "percentage-" + Math.round(StundeKoord*Tagesdauer));
let colorString = "linear-gradient(to right, #9c9e9f 0%,#9c9e9f " + Pausenstueck + Zakstueck + Ueberstundenstueck + " 100%);"
UebersichtDD.appendChild(a);
a.style.backgroundImage = '-webkit-linear-gradient(to right, #9c9e9f 0%,#9c9e9f 50%, #F53323 50%, #F53323 100%)';
}
document.addEventListener("DOMContentLoaded", init);
<body>
<div id="Uebersicht_Window_child"></div>
</body>
I already tried using double quotes instead of single quotes but it also doesn't work. leaving the "-webkit-" doesn't solve my problem either... I absolutely don't know the problem. Hope you guys could help me :)
Thank you!
There is one major issue: You never actually insert the dd element that you imported into the document:
From Document​.import​Node():
The Document object's importNode() method creates a copy of a Node or
DocumentFragment from another document, to be inserted into the
current document later.
(Emphasis mine)
There are a couple of other issues, mainly around code structure and style - but they may not be pertinent to the core question - but also syntax problems with creating the colorString that may have been contributing.
function init() {
var Lohn = "undefined";
var Datum = "undefined";
var StundeKoord = "undefined";
var Tagesdauer = "undefined";
// -----------------------------
var Pausenstueck = "#9c9e9f 50%";
var Zakstueck = "#F53323 50%";
var Ueberstundenstueck = "#F53323 100%";
let UebersichtTemplate = document.createElement("dd");
UebersichtTemplate.innerHTML = "<span class='textRight'>" + Lohn + "</span>" +
"<span class='text'>" + Datum + "</span>";
let a = document.importNode( UebersichtTemplate, true );
a.classList.add( "percentage", "percentage-" + Math.round(StundeKoord*Tagesdauer) );
a.style.backgroundImage = `-webkit-linear-gradient(top right, #9c9e9f 0%, ${Pausenstueck}, ${Zakstueck}, ${Ueberstundenstueck} )`;
// insert the imported node.
document.body.appendChild(a);
}
document.addEventListener("DOMContentLoaded", init);
<body>
<div id="Uebersicht_Window_child"></div>
</body>

How to solve a linear equation with algebra.js?

I'm trying to solve/evaluate an equation using algebra.js by nicolewhite and can't seem to get it right.
Here's the code i'm using:
<!DOCTYPE html>
<html>
<head>
<script src="//algebra.js.org/javascripts/algebra-0.2.6.min.js"></script>
</head>
<body>
<script>
var Fraction = algebra.Fraction;
var Expression = algebra.Expression;
var Equation = algebra.Equation;
var x1 = algebra.parse("1/5 * x + 2/15");
var x2 = algebra.parse("1/7 * x + 4");
var eq = new Equation(x1, x2);
console.log(eq.toString());
var answer = eq.solveFor("x");
console.log("x = " + answer.toString());
</script>
</body>
I'm not sure linking the source js works here but it just gives me a blank page anywhere i try that code. I have defined the three variables as stated by the algebra author so I'm not sure what i'm doing wrong.
You are getting a blank page because you are not setting the answer to any html element. Your code is sending the output to the console so you should be able to see it there.
Try this to show the result on your page.
var Fraction = algebra.Fraction;
var Expression = algebra.Expression;
var Equation = algebra.Equation;
var x1 = algebra.parse("1/5 * x + 2/15");
var x2 = algebra.parse("1/7 * x + 4");
var eq = new Equation(x1, x2);
console.log(eq.toString());
var answer = eq.solveFor("x");
console.log("x = " + answer.toString());
const output = document.createElement('p');
document.body.appendChild(output);
output.textContent = "x = " + answer.toString();

Avoiding color blindness penalty programmatically

I learned as a web developer that if the color contrast on a website is terrible, then I make very little money but I want to change that, however I ran into a problem. I have a section on my site where a user can select a color and the box is filled with that color. Let's say the color is already chosen. The box will then be like this in code for a black box:
<div ID="box" style="background:#000000;width:16px;height:16px">Text?</div>
The thing is the #000000 will change to another value based on the user's selection from running javascript. I feel that to make all CSS processors including google happy, I need to specify a foreground color so that its readable on any background color but I don't know the math behind this.
<script>
var x=(insert chosen color value);
var y=(some calculated value);
document.getElementById('box').style.background='#'+v;
document.getElementById('box').style.color='#'+y;
</script>
How do I determine the formula for foreground color regardless of the background color I choose to use so that the text is always readable?
OR
should I use a different HTML4 element to represent my color box?
and could I get away with this without having to make an image of just color boxes?
More added code
Run this code to get a sample of the strip of colours I use for my colour box.
<div ID="BOX" style="width:100%"></div>
<script>
var body=document.getElementById('BOX');
for (n=0;n<15;n++){
var box=document.createElement('DIV');
box.style.width='20px';
box.style.height='20px';
v=n.toString(16);
box.style.background='#'+v+v+v+v+v+v;
body.appendChild(box);
}
</script>
This is my old function for check and create a color contrast (I use this in a color picker).
This is the line you can change for test the function:
var hexcolor = '#333333'; // <--- change this for test
Fiddle
HTML:
<div id="bckgrd" >
<div id="txt">
TEST CODE
</div>
</div>
THE CSS:
html, body {
background-color:#ff0000;
}
#bckgrd {
display:inline-block;
width:100%;
font-size:18px;
}
THE JAVASCRIPT:
function colorContrast(color) {
var r = hexToRgb(color).r;
var g = hexToRgb(color).g;
var b = hexToRgb(color).b;
var rB = 255, gB = 255, bB = 255;
var rN = 0, gN = 0, bN = 0;
var cB = Math.abs(r - rB) + Math.abs(g - gB) + Math.abs(b - bB);
var br1 = (299*r + 587*g + 114*b);
var br2 = (299*rB + 587*gB + 114*bB);
var dB = Math.abs(br1 - br2);
var cN = Math.abs(r - rN) + Math.abs(g - gN) + Math.abs(b - bN);
br2 = (299*rN + 587*gN + 114*bN);
var dN = Math.abs(br1 - br2);
if ((cB>500) && (dB>125)){
return '#ffffff';
} else if ((cN>500) && (dN>125)){
return '#000000';
} else {
if ( ((0.2*cB) + (0.8*dB)) > ((0.2*cN) + (0.8*dN)) ) {
return '#FFFFFF';
} else {
return '#000000';
}
}
}
function hexToRgb(hex) {
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
var hexcolor = '#333333'; // <--- change this for test
$('#txt').css('color', hexcolor);
$('#bckgrd').css('background-color', colorContrast(hexcolor));

Capitalize select option using Javascript

I have a dropdown menu.
I've been trying to capitalize the text inside my select option, but I couldn't make it work.
JS
$.each(responseData.assignments, function(i, v) {
var chapterNum = v.contentLabel;
var assessmentType = v.assessmentType.toLowerCase().replace(/_/g, " ");
var sameAssignmentType = $('#assignment-type-dd option').filter(function(){
return $(this).text() == assessmentType;
})
if(!sameAssignmentType.length){
$('#assignment-type-dd').append('<option value="' + assessmentType + '">' +
assessmentType + '</option>');
}
});
I've tried chaining this code to my assessmentType :
.charAt(0).toUpperCase() + this.slice(1)
But as soon as I do that it give error :
Uncaught TypeError: this.slice is not a function
Can someone please give me a little hint here ? Thanks.
This should work (CSS approach)
#assignment-type-dd option {
text-transform: capitalize;
}
If you need the entire options text to be uppercase use this.
#assignment-type-dd option {
text-transform: uppercase;
}
And if you really hate CSS or you need the Capitalized text to be passed to server or do some other manipulation, use the below JavaScript code
var capitalizeMe = "";
$("#assignment-type-dd option").each(function() {
capitalizeMe = $(this).text();
$(this).text(capitalizeMe.charAt(0).toUpperCase() + capitalizeMe.substring(1));
});
Play it here
Instead of using this.slice(1), try using assessmentType.slice(1).
you need to format it as
string.charAt(0).toUpperCase() + string.slice(1)
One solution could be to use a CSS rule:
select option {
text-transform:capitalize;
}
We can manipulate font setting by CSS alternation also. Try this
<style>
select option {
text-transform:capitalize;
}
</style>
This seems like a problem CSS is best-suited for.
.select {
text-transform: uppercase;
}
You don't need jQuery for this, unless you are trying to capitalize the first letter of each word. In which case a pure JavaScript solution (assuming you are targeting h2 elements) would be:
var a = document.getElementsByTagName('h2');
for (i = 0; i < a.length; i++) {
var words = a[i].innerHTML.split(" ");
for (j = 0; j < words.length; j++) {
if (words[j][0] != "&") {
words[j] = "<span class='first-letter'>" + words[j][0] + "</span>" + words[j].substring(1);
}
}
a[i].innerHTML = words.join(" ");
}
http://jsfiddle.net/ryanpcmcquen/2uLLqy8r/
Otherwise pure css will work: text-transform: capitalize;
https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform
If it is about just showing it then the css text-transform should work.
If you want to do it programatically in Javascript, I suggest creating a function and calling it as needed:
function stringCapitalize(str){
if (str){
str = str.charAt(0).toUpperCase() + str.slice(1);
return str;
}
}
stringCapitalize("moemen"); // returns "Moemen"
If you think that you will use it regularly during this application, then add it to the built-in String.prototype:
String.prototype.stringCapitalize = function () {
if (this){
str = this;
str = str.charAt(0).toUpperCase() + str.slice(1);
return str;
}
}
"moemen".stringCapitalize() // returns "Moemen"
var name = prompt("what is your name");
var firstchar = name.slice(0, 1);
var firstcharuppercase = firstchar.toUpperCase();
var restofName = name.slice(1,name.length);
var capitlisedName = firstcharuppercase + restofName;
alert(" Hello " + capitlisedName);

Cocos2d-JS 3.0 migration

I'm moving from cocos2d-html5 version 2.2 to cocos2d-js 3.0 and I have a problem with this code (which works perfectly in version 2.2):
menuButtons = cc.Menu.create();
for (var a = 1; a < 6; a++){
var label = cc.LabelTTF.create("BUTTON " + a, "Arial", 20);
var tmpBtn = cc.MenuItemLabel.create(label, function (e) {
cc.log("TEST TAG: " + e.tag);
//StartSomethingOther(e);
}, this);
tmpBtn.setPosition(50, a * 30);
tmpBtn.tag = a;
menuButtons.addChild(tmpBtn,2,1);
}
menuButtons.setPosition(10, 10);
this.addChild(menuButtons, 1);
Any "button" is pressed the console always output "TEST TAG: 1" instead of putting the correct number.
Any tip to solve the problem?
Change the .tag with .title or even better a ['data-'] identifier like in this example:
menuButtons = cc.Menu.create();
for (var a = 1; a < 6; a++){
var label = cc.LabelTTF.create("BUTTON " + a, "Arial", 20);
var tmpBtn = cc.MenuItemLabel.create(label, function (e) {
cc.log("TEST TAG: " + e['data-tag']);
//StartSomethingOther(e);
}, this);
tmpBtn.setPosition(50, a * 30);
tmpBtn['data-tag'] = a;
menuButtons.addChild(tmpBtn,2,1);
}
menuButtons.setPosition(10, 10);
this.addChild(menuButtons, 1);
You're overwriting tag property here:
menuButtons.addChild(tmpBtn,2,1);
the third parameter sets tmpBtn.tag to 1.
If You want to continue to use tag property simply change:
tmpBtn.tag = a;
menuButtons.addChild(tmpBtn,2,1);
with:
menuButtons.addChild(tmpBtn,2,a);
If You don't want to use tag property, see Francesco's answer

Categories