How to insert resulting value of randomizer into html input value? (JavaScript) - javascript

I'm working on a background-gradient generator that can be manipulated by either selecting one of two HTML color inputs and choosing color manually (which is then displayed live in the background) or by clicking a "randomize" button and generating two random rgb colors to be displayed.
Github repository here.
The problem is, when you click "randomize", the value of the color input fields remains the same while the background changes. I want to make it so that the values of each random rgb color generated are then added to the inner html "value" of the input boxes so that the boxes display exactly what two colors were selected. I'm having trouble figuring out the logic of doing this.
Here is the JS of the color randomizer function if that helps:
function randomRGB() {
var rgbValues = [];
for(var i = 0; i < 3; i++) {
rgbValues.push(Math.floor(Math.random() * 256));
}
return 'rgb(' + rgbValues[0] + ',' + rgbValues[1] + ',' + rgbValues[2] + ')';
}
function setRandom() {
body.style.background = 'linear-gradient(to right, ' + randomRGB() + ', ' + randomRGB() + ')';
css.textContent = body.style.background + ';';
}
And here is the HTML:
<!doctype html>
<html lang="en">
<head>
<title>Gradient Background</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body id = "gradient">
<div class="container">
<h1>Background Generator</h1>
<div class="inputs">
<input class = "color1" type="color" name="color1" value="#B5DDFF">
<input class = "color2" type="color" name="color2" value="#D998FF" id=""><br>
</div>
<button class="random">Randomize</button>
<h2>Current CSS Background</h2>
<h3></h3>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="script.js"></script>
</body>
</html>
Please let me know if there's anything I can clarify, I'm definitely a beginner when it comes to JS and I may not have explained it in the best way.

Considering that your inputs are under a .inputs container, as I see in your github repository:
function setRandom() {
const firstRndRGB = randomRGB();
const secondRndRGB = randomRGB();
const inputs = document.getElementsByClassName('inputs');
inputs[0].value = firstRndRGB;
inputs[1].value = secondRndRGB;
body.style.background = 'linear-gradient(to right, ' + firstRndRGB + ', ' + secondRndRGB + ')';
css.textContent = body.style.background + ';';
}
EDIT:
As it has to be insterted into a type="color" input, which only accepts Hex formatted colors, we must also convert the RGB format into a Hex format using regex like this:
function getHexFromRGB(x){
return '#' + x.match(/\d+/g).map(y = z => ((+z < 16)?'0':'') + (+z).toString(16)).join('');
}
And then just do
inputs[0].value = getHexFromRGB(firstRndRGB);
inputs[1].value = getHexFromRGB(secondRndRGB);

So all you need is to use those rbg strings and convert them into hex format so you can assign them to each input's value
function randomRGB() {
var rgbValues = [];
for(var i = 0; i < 3; i++) {
rgbValues.push(Math.floor(Math.random() * 256));
}
return 'rgb(' + rgbValues[0] + ',' + rgbValues[1] + ',' + rgbValues[2] + ')';
}
function setRandom() {
const firstRndRGB = randomRGB();
const secondRndRGB = randomRGB();
const inputs = document.querySelectorAll('.inputs input');
inputs[0].value = toHEX(firstRndRGB);
inputs[1].value = toHEX(secondRndRGB);
document.body.style.background = 'linear-gradient(to right, ' + firstRndRGB + ', ' + secondRndRGB + ')';
//css.textContent = body.style.background + ';';
}
function toHEX(rgbString){
rgbString = rgbString.split("(")[1].split(")")[0];
rgbString = rgbString.split(",");
rgbString = rgbString.map(x => {
x = parseInt(x).toString(16);
return (x.length==1) ? "0"+x : x;
});
rgbString = "#"+rgbString.join("");
return rgbString;
}
setRandom();
document.getElementById('randomize').addEventListener('click', ()=>{
setRandom()
});
<body id = "gradient">
<div class="container">
<h1>Background Generator</h1>
<div class="inputs">
<input class = "color1" type="color" name="color1">
<input class = "color2" type="color" name="color2" id=""><br>
</div>
<button id='randomize' class="random">Randomize</button>
<h2>Current CSS Background</h2>
<h3></h3>
</div>
</body>

MDN says that the input type="color" takes a value in lower-case hexadecimal notation. In the view there must be printed rgb value. Rename randomRGB() with randomColor() and return both of them.
function randomColor() {
var rgb = [];
var hex = [];
for (var i = 0; i < 3; i++) {
var randomColorPart = Math.floor(Math.random() * 256);
var randomColorPartHEX = randomColorPart.toString(16);
if (randomColorPartHEX.length < 2) {
randomColorPartHEX = '0' + randomColorPartHEX;
}
rgb.push(randomColorPart);
hex.push(randomColorPartHEX);
}
return {
'rgb': 'rgb(' + rgb.join() + ')',
'hex': '#' + hex.join(''),
}
}
function setRandom() {
var randomColor1 = randomColor();
var randomColor2 = randomColor();
var bgLinearGradient = 'linear-gradient(to right, ' + randomColor1.rgb + ', ' + randomColor2.rgb + ')';
body.style.background = bgLinearGradient;
css.textContent = bgLinearGradient+ ';';
color1.value = randomColor1.hex;
color2.value = randomColor2.hex;
}

Related

Uncaught Reference Error when trying to pass a function through a button in JavaScript?

I'm trying to write a navigation bar at the top of my web app to change a parameter in backend, but when I call the function it always return an unexpected end of input or an uncaught reference error that says my function was not defined on click. Can someone please help me figure out what I'm doing wrong?
JS File:
let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
console.log('ok');
type = randomstring;
console.log(type);
}
let str = '<div class="topnav">';
for(let count = 0; count < typearray.length; count++){
str = str +
'<button onclick ="changeType("'+typearray[count]+'")" title = " '+ typearray[count] + '">' +typearray[count] +'</button>';
}
str = str + '</div>' +
'</div>';
console.log(str);
document.getElementById('navbar').innerHTML = str;
HTML File(includes the rest of the program)
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1">
<meta charset="utf-8">
<style>
#map {
height: 75%;
width: 75%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<script src = getlocation.js></script>
<!-- this implements the navbar-->
<div id="navbar"></div>
<script type = "module" src = navbar.js></script>
<!-- this implements the map-->
<div id="map"></div>
<script src = index.js> </script>
<!-- this implements the list-->
<div id="list"></div>
<script type = "module" src = rankedstores.js></script>
<script src="https://maps.googleapis.com/maps/api/js?key=000000000000000000
&callback=initMap"></script>
</body>
</html>
Looks like you just had some errors when building str. Try this
let typearray = ["supermarkets_and_groceries", "churches", "cafes"];
let str = '<div class="topnav">';
for (let count = 0; count < typearray.length; count++) {
str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
}
str += "</div>";
console.log(str);
use properly Template literals (Template strings)
str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
console.log('ok');
type = randomstring;
console.log(randomstring);
}
let str = '<div class="topnav" />';
for(let count = 0; count < typearray.length; count++){
str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
}
str = str + '</div>' +
'</div>';
console.log(str);
document.getElementById('navbar').innerHTML = str;
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1">
<meta charset="utf-8">
<style>
#map {
height: 75%;
width: 75%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<script src = getlocation.js></script>
<!-- this implements the navbar-->
<div id="navbar"></div>
<script type = "module" src = navbar.js></script>
<!-- this implements the map-->
<div id="map"></div>
<script src = index.js> </script>
<!-- this implements the list-->
<div id="list"></div>
<script type = "module" src = rankedstores.js></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD2c7P_IihiITITslXAk-wWy9z067xjFQU
&callback=initMap"></script>
</body>
</html>
use properly Template literals (Template strings)
str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
Just for understanding purpose:
The problem here is that a html attribute value has to be wrapped around single or double quotes. With your code, the quotes that wrap around the value of the button's onlick attribute end not there where you want because you start with double quotes but wrap the function with double quotes as well so the element at the end looks like this:
<button onclick="changeType(" supermarkets_and_groceries")"="" title=" supermarkets_and_groceries">supermarkets_and_groceries</button>
to fix this either use double and single quotes:
str = str +
"<button onclick='changeType(" + '"' + typearray[count] + '"' + ")' title = ' " + typearray[count] + "'>" + typearray[count] + "</button>";
or use template literals (already mentioned by the other answers):
str = str + `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
template literals explanation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Modified Code Snippet
let typearray = ["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(event) {
type = event.target.getAttribute("type");
console.log(type);
}
let navHtml = document.createElement("div");
for (let count = 0; count < typearray.length; count++) {
let btn = document.createElement("button");
btn.setAttribute("type", typearray[count]);
btn.setAttribute("title", typearray[count]);
btn.innerText = typearray[count];
btn.addEventListener("click", changeType);
navHtml.appendChild(btn);
}
document.getElementById("navbar").appendChild(navHtml);

Code execution speed is slower and slower in time

In my project I need to see sensors data in textarea window
and after some time to save those data in txt file.
I use this code :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
var updateInterval = 50;
var updateChart = function(count) {
count = count || 1;
Val1 = Math.floor((Math.random() * 100) + 1);
Val2 = Math.floor((Math.random() * 100) + 1);
Val3 = Math.floor((Math.random() * 100) + 1);
$(document).ready(function() {
var $textarea = $('textarea');
$textarea.scrollTop($textarea[0].scrollHeight);
});
var d = new Date();
$("#output").append(document.createTextNode(d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + " - , " + Val1 + ", " + Val2 + ", " + Val3 + "\n"));
}
setInterval(function() {
updateChart()
}, updateInterval);
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
</script>
</head>
<body>
<form onsubmit="download(this['name'].value, this['text'].value)">
Filename: <input type="text" name="name" value=" .txt">
<textarea id='output' cols="40" rows="10" name="text" style="border:solid 2px blue;">
Time ,Val1, Val2, Val3
</textarea>
<input type="submit" value="SAVE">
</form>
</body>
</html>`
The problem is in the fact: my code execution speed is slower and slower if time
between start and file saving moment is longer !
If I use 20 samples/sec this amount of slowdown is not acceptable.
Is it possible to get faster code and much less dependent of time (txt file size) ?

Product colorize with a texture image (jquery)

I want to use product colorize from nikorablin but in his script use rgb colors and i want to use img (textures)
Here is the script
/*
* productColorizer - jQuery Plugin
* version: 1.2 October 2012
* #requires jQuery v1.6 or later
*
* Examples at http://nikorablin.com/sandbox/productColorizer/
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
*/
(function($){
$.fn.productColorizer = function(options) {
// defaults
var defaults = {
transparency: 0.55,
swatchTransparency: 0.75,
secondaryTransparency: 0.55,
swatchClass: '.swatch'
};
// extend defaults
var options = $.extend(defaults, options);
return this.each(function() {
// init objects
var o = options;
var obj = $(this);
var swatch = obj.find(o.swatchClass);
var swatches = obj.find(o.swatchClass + " a");
var mask = obj.find('.mask');
// set swatch colors with the rel values
$(swatches).each(function(){
var color = "rgba(" + $(this).attr('rel') + "," + o.swatchTransparency + ")";
$(this).html('<span>'+$(this).html()+'</span>');
$(this).find('span').css('background', color);
if($.browser.msie) {
color = $(this).attr('rel');
var colors = color.split(",");
color = "#" + colorToHex(colors);
$(this).find('span').css({'background-color': color});
}
});
// set background color of mask with rel values and transparency
$(swatches).click(function(e) {
e.preventDefault();
$(swatches).removeClass('active');
$(this).addClass('active');
var color = "rgba(" + $(this).attr('rel') + "," + o.transparency + ")";
var mask = $(this).attr('href');
if($(mask).attr('role')) {
$(mask).empty();
var R = Raphael(mask.substring(1), $(mask).width(), $(mask).height());
var style = {
fill: "rgb(" + $(this).attr('rel') + ")",
opacity: o.secondaryTransparency,
"stroke-width": 0
};
R.path($(mask).attr('role')).attr(style);
} else {
$(mask).css({"background-color": color}, 1000);
if($.browser.msie) {
color = $(this).attr('rel');
var colors = color.split(",");
color = colorToHex(colors);
$(mask).css({'background': 'transparent', 'zoom': 1, 'filter': 'progid:DXImageTransform.Microsoft.gradient(startColorstr=#80' + color + ',endColorstr=#80' + color + ')'});
}
}
});
// create tooltips showing color name on swatch hover
$(swatches).hover(function(e) {
e.preventDefault();
var offsetX = $(this).offset().left - $(this).parent().offset().left;
var offsetY = $(this).offset().top - $(this).parent().offset().top + 25;
var text = $(this).attr('title');
if(!$.browser.msie) $(this).removeAttr('title');
$(this).after('<div class="colorizer-tooltip"><div class="colorizer-pointer-up"><div class="colorizer-pointer-up-inner"></div></div><span class="colorizer-tooltip-text">' + text + '</span></div>');
var offsetToolTip = ($('.colorizer-tooltip').width()/2)-12;
$('.colorizer-tooltip').css({'left': offsetX-offsetToolTip, 'top':offsetY});
}, function() {
var text = $('.colorizer-tooltip-text').html();
$(this).attr('title', text);
$(".colorizer-tooltip").remove();
});
//rgb to hex
function colorToHex(color) {
var red = parseInt(color[0]);
var green = parseInt(color[1]);
var blue = parseInt(color[2]);
var rgb = blue | (green << 8) | (red << 16);
return rgb.toString(16);
};
});
}
})(jQuery);
and html
<a rel="255,211,8" href="#mask" title="Yellow">Yellow</a>
I want to use something like this
<a rel="http://www.ex.etc/img.jpg" href="#mask" title="ImgTexture">Img</a> (example how i want to use)
Or with <a rel="img_src" href="htttp://etc.etc/img.jpg" alt="#mask" title="imgtexture"></a>
I am newbie at propgraming .. how i have to change the jquery ?
Thx
Download archive with all js and css files.
Add them to you HTML page:
<html>
<head>
<title>Color</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="js/raphael-min.js"></script>
<script type="text/javascript" src="js/jquery.productColorizer.js"></script>
<link rel="stylesheet" type="text/css" href="js/jquery.productColorizer.css" />
<script type="text/javascript">
$(document).ready(function(){
$('.product').productColorizer();
});
</script>
</head>
<body>
<div class="product">
<div class="swatch">
<a rel="32,223,95" href="#mask" title="Green">Green</a>
<a rel="255,211,8" href="#mask" title="Yellow">Yellow</a>
<a rel="255,101,8" href="#mask" title="Orange">Orange</a>
<a rel="16,200,255" href="#mask" title="Blue">Blue</a>
<a rel="142,8,255" href="#mask" title="Purple">Purple</a>
<a rel="245,25,45" href="#mask" title="Red">Red</a>
</div>
</div>
</body>
</html>
As shown here:
And you will see the result:

Colorpicker in javascript

Im currently making a simple color picker for school. Well it should be simple, however my programming in Javascript is really bad. It contains an array with the names, and a array with the codes. The codes will only contain 00, 33, 66, 99, ff, cc and the code is only 6 chars long as some of you know. With a loop i manage to print everything on screen, but now i want to make the background color the same color as the one im clicking. And i want the code of the one that im clicking in a textbox.
So heres my code:
DHTML with jQuery: Opdracht 4
<script type="text/javascript">
function showPicker(source) {
var hex = new Array('00', '33', '66','99','CC','FF');
var colorNames = new Array(
"black", // #000000
"weak blue", // #000033
"obsure dull blue", // #000066
"dark faded blue", // #000099
);
var count = 0;
document.writeln('<table width="1200" height="600">');
for(var x in hex) {
document.writeln('<tr>');
for(var y in hex) {
for(var z in hex) {
var color = hex[x] + "" + hex[y] + "" + hex[z];
document.writeln('<td bgcolor="#'+color+'" title="#'+color + ' ' + colorNames[count] + '" onclick="'+source+' (\''+color+'\',\''+colorNames[count]+'\')"></td>');
count++;
}
}
document.writeln('</tr>');
}
document.writeln('</table>');
}
showPicker('showFontColor');
</script>
</head>
<body>
<input type="text" id="color"/>
</body>
</html>
I tried a line in the onclick button, but i realised that wont work. Do you guys have any suggestions? And sorry if it looks a little messy, as I said I am a real nub in javascript.
EDIT:
Working code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DHTML with jQuery: Opdracht 4</title>
<link href="style.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function changeBg(color){
var currentColor = $('#printColor').val();
$('#input').css('background', currentColor);
}
function printColor(color) {
$('#printColor').val(color);
$("#input").on("click", function() {
$(this).css("background", "printColor");
});
}
function changeFG() {
var currentColor = $('#printColor').val();
$('#input').css('color', currentColor);
}
function showPicker(source) {
var hex = new Array('00', '33', '66','99','CC','FF');
var colorNames = new Array(
"black", // #000000
"weak blue", // #000033
"obsure dull blue", // #000066
);
var count = 0;
document.writeln('<table width="800" height="300">');
for(var x in hex) {
document.writeln('<tr>');
for(var y in hex) {
for(var z in hex) {
var color = hex[x] + "" + hex[y] + "" + hex[z];
document.writeln('<td bgcolor="#' + color + '" title="#' + color + ' ' + colorNames[count] + '" onclick="javascript:printColor(\'#'+color+'\')" ' + source + '(\'' + color + '\',\'' + colorNames[count] + '\')"></td>');
count++;
var source = function(color){
document.body.style.background = "#" + color;
}
}
}
document.writeln('</tr>');
}
document.writeln('</table>');
}
showPicker('showFontColor');
</script>
</head>
<body>
<div id="input">
<input type="text" id="printColor" name="printColor" />
Change Background / Foreground color!
<p> Lorem ipsum blablabla</p>
</div>
</body>
</html>
Without making too much changes to your code I think this is what you want.
I just changed your array into an object so that you can map the hex code of the color to the name and declared the changeBg function. Just fill in the rest of the colors.
<body>
<script type="text/javascript">
(function(){
var colorNames = {
"000000": "black",
"000033": "weak blue",
"000066": "obsure dull blue",
"000099": "dark faded blue"
//...rest of colors
};
window.changeBg = function(color){
document.body.style.background = "#" + color;
document.getElementById("color").value = colorNames[color];
}
var showPicker = function(source) {
var hex = new Array('00', '33', '66','99','CC','FF');
var count = 0;
document.writeln('<table width="1200" height="600">');
for(var x in hex) {
document.writeln('<tr>');
for(var y in hex) {
for(var z in hex) {
var color = hex[x] + "" + hex[y] + "" + hex[z];
document.writeln('<td bgcolor="#'+color+'" title="#'+color +'" onclick=changeBg(\''+color+'\')></td>');
count++;
}
}
document.writeln('</tr>');
}
document.writeln('</table>');
}
showPicker();
})();
</script>
<input type="text" id="color" readonly = true/>
</body>

JavaScript string doesn't get displayed on the page

pretty new to javascript and doing some examples from a book, can't understand why this isn't producing any text strings on the page when loaded.
function init()
{
var sum = 80 + 20;
var sub = sum - 50;
var mul = sum * 5;
var div = sum / 4;
var mod = sum % 2;
var inc = ++sum;
var dec = --sum;
var str = "Sum: " + sum;
str += "<br>Subtraction: " + sub;
str += "<br>Multiplication: " + mul;
str += "<br>Division: " + div;
str += "<br>Modulus: " + mod;
str += "<br>Increment: " + inc;
str += "<br>Decrement: " + dec;
document.getElementById( "Panel" ).innerHTML = str;
}
document.addEventListener("DOMContentLoaded" , init , false);
And the html5 code;
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="arithmetic.js"></script>
<title>Doing Arithmetic</title>
</head>
<body>
<div id="panel"> </div>
</body>
</html>
Your <div> has an id of panel, not Panel. The IDs need to match. So you can either change the JavaScript code:
document.getElementById( "panel" )
or the HTML:
<div id="Panel"> </div>
Replace
<div id="panel"> </div>
with
<div id="Panel"> </div>
and it will work. P in panel should be capital.

Categories

Resources