Build a multiplication table - javascript

I am having trouble with coding a calculator that asks the user to enter the starting and ending values. The program must use nested for loops. Including row and column labels.
This is what the final table will look like. I will greatly appreciate a link to a relating video or a hint to solve this problem. For example, the output from 1 to 3 might look like this:
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
The output from 3 to 5 might look like this:
3 4 5
3 9 12 15
4 12 16 20
5 15 20 25
The multipliers should appear on top and to the left of the table.
There is one example that I tried to modify for my task.
var result = 'x ';
for (var i = 0; i < 11; i++) {
for (var j = 0; j < 11; j++) {
if(i == 0 && j > 0){
result += '[' + j + ']';
}
else if(j == 0 && i>0){
result += '[' + i + '] ';
}
else if(i>0 && j>0){
result += (i*j) + ' ';
}
}
result += '\n'
}
console.log(result);
Output:
x [1][2][3][4][5][6][7][8][9][10]
[1] 1 2 3 4 5 6 7 8 9 10
[2] 2 4 6 8 10 12 14 16 18 20
[3] 3 6 9 12 15 18 21 24 27 30
[4] 4 8 12 16 20 24 28 32 36 40
[5] 5 10 15 20 25 30 35 40 45 50
[6] 6 12 18 24 30 36 42 48 54 60
[7] 7 14 21 28 35 42 49 56 63 70
[8] 8 16 24 32 40 48 56 64 72 80
[9] 9 18 27 36 45 54 63 72 81 90
[10] 10 20 30 40 50 60 70 80 90 100
I noticed the multipliers are in brackets and the X appears in the top left corner. Is it achieved by using if statements? In my assignment, there must be an empty cell instead of the X. This is what I came up with:
let result = "x";
for(let row = number1; row <= number2; row++){
result += row + "<tr>";
for( let column = number1; column <= number2; column++){
result += "<td>" + row * column +"</td>";
}
result += "<br>"
result += "</tr>"
}
document.getElementById("output").innerHTML = result;
}
My program generates a testing table with a start value equal to 2 and an end value equal to 5, and looks like this:
x 4 6 8 10
6 9 12 15
8 12 16 20
10 15 20 25
It is clear that some logic in the formula within the code isn't right.
I am attempting to use a document.getElementById() to output the result table. That is one of the requirements. Having some comments explaining the use of table element tags is greatly appreciated.
The program must take start and end values, not just from 1 to 10.
I appreciate everyone's answers. Some comments within the code that explain what does what and what I am doing wrong are also welcome.
p.s.
I made some corrections to my code. Now it displays ok. One thing is not right. It starts calculation with a number greater than the start number by 1 (eg for input values 2 to 6 it will display 3 to 6). Any ideas?
function displayExpressions(){
let number1 = getNumber();
// console.log(number1)
let number2 = getExpressionsNumber();
// console.log(number2)
if (number1 ==0 || number2 == 0){
document.getElementById("error").innerText = "Enter a number!"
}
else{
let result = " "
for(let row = number1; row <= number2; row++) {
result += "<tr>";
for( let column = number1; column <= number2; column++){
if( row == number1 && column > number1){
result += "<th>" + column + "</th>";
}
else if(column == number1 && row > number1){
result += "<th>" + row + "</th>";
}
else if (row == number1 && column == number1){
result = "<td>" + "x" + "</td>";
}
else{
result += "<td>" + row * column +"</td>";
document.getElementById("output").innerHTML = result;
}
}
result += "</tr>";
}
document.getElementById("output").innerHTML = result;
}
}
I thank everyone who helped. Here is a working example.
'use strict';
window.addEventListener('load', function () {
document.getElementById('number1').addEventListener('focus', inputFocus);
document.getElementById('number2').addEventListener('focus', inputFocus);
document.getElementById('btn').addEventListener('click', main);
document.getElementById('number1').focus();
});
function inputFocus() {
document.activeElement.select();
document.getElementById('error').innerText =
'Enter ' + document.activeElement.id + ' value.';
}
function getNumber() {
let multiplier = document.getElementById('number1').value;
multiplier = Number(multiplier);
return multiplier;
}
function getExpressionsNumber() {
let expressionsNumber = document.getElementById('number2').value;
expressionsNumber = Number(expressionsNumber);
return expressionsNumber;
}
// I have a good feeling that checkInput() does not work at all and is most likely redundant.
function checkInput() {
let number = document.activeElement.value;
console.log(number);
if (isNaN(number) || number.trim().lenght == 0) {
document.getElementById('error').innerText = 'Enter a number!';
return false;
}
return true;
}
function main() {
console.log('Main is called...'); // testing to see if this function is being called.
console.log(checkInput()); // testing if this function returns true...
if (checkInput()) {
document.getElementById('error').innerText = ''; // set the error message to emptry string... good.
displayExpressions(); // call the function to display the output...
}
}
function multiplication(number, expressionsNumber) {
let result = number * expressionsNumber;
return result;
}
function displayExpressions(){
let number1 = getNumber();
// console.log(number1)
let number2 = getExpressionsNumber();
// console.log(number2)
if (number1 <=0 || number2 <= 0){
document.getElementById("error").innerText = "Enter a natural number!"
}
else if(number1 >= number2 ){
document.getElementById("error").innerText = "End value must be grater than Start value!"
}
else{
let result = " "
for(let row = number1; row <= number2 + 1; row++) {
result += "<tr>";
for( let column = number1; column <= number2 + 1; column++){
if( row == number1 && column > number1){
result += "<th>" + (column-1) + "</th>";
}
else if(column == number1 && row > number1){
result += "<th>" + (row - 1) + "</th>";
}
else if (row == number1 && column == number1){
result = "<th>" + "x" + "</th>";
}
else{
result += "<td>" + (row - 1) * (column-1) +"</td>";
document.getElementById("output").innerHTML = result;
}
}
result += "</tr>";
}
document.getElementById("output").innerHTML = result;
}
}
*{
box-sizing: border-box;
}
.fcontainer{
display: flex;
}
div.fcontainer{
justify-content: space-between;
flex-basis: 50%;
margin: 15px;
}
body {
margin: 40px;
background-color: rgb(230, 255, 247);
font-family: 'Roboto', sans-serif;
font-size: calc(10px + (24 - 10) * (100vw - 300px) / (1600 - 300));
}
h1, h2 {
text-align: center;
}
img {
display: block;
width: 300px;
margin: 0 auto;
}
a {
text-decoration: none;
}
p {
margin: 10px 0px;
}
button {
margin: 10px 0px;
}
div.calc {
margin: 0 auto;
display: block;
width: 600px;
background-color: rgb(33, 209, 150);
padding: 20px;
border-radius: 5px;
text-align: center;
}
div.calc p {
text-align: left;
margin-left: 55px;
}
.calc input {
width: 80%;
text-align: right;
border-radius: 3px;
border: none;
}
div.cal h2,
h3 {
text-align: center;
}
#assignment6 div{
margin-top: 10px;
}
div.calc div input,
div.calc div label{
width: 45%;
display: inline-block;
text-align: right;
}
.calc button {
margin-left: 355px;
border-radius: 5px;
border:2px solid #008CBA;
color: black;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
transition-duration: 0.4s;
cursor: pointer;
}
.calc button:hover {
background-color: #008CBA;
color: white;
}
.calc button:active {
transform: scale(0.98);
/* Scaling button to 0.98 to its original size */
box-shadow: 3px 2px 22px 1px rgba(0, 0, 0, 0.24);
/* Lowering the shadow */
}
/* Assignment Listings Page start */
#mainPage{
background-image: url(../images/keyboard.jpg);
background-repeat: no-repeat;
background-position: center;
background-size: cover;
height: 350px;
}
#header{
flex-direction: column;
background-color: #9b9ea1;
color: #fff;
max-width: 50%;
margin: 0 auto;
align-self: center;
}
#header h1{
margin: 1em;
}
#main div{
padding: 10px;
background-color: #9b9ea1;
margin: 15px;
width: fit-content;
}
#main a{
padding: 5px;
margin: 5px;
color: #fff;
}
/* Assignment Listings Page end */
/* assignment 3 */
section.fcontainer{
display: flex;
flex-wrap: wrap;
justify-content: space-around;
flex-direction: row;
align-items: stretch;
margin: 0 auto;
max-width: 2600px;
padding: 10px;
border: 1 solid black;
}
section.fcontainer div{
background-color: blanchedalmond;
flex-basis: 45%;
padding: 15px;
margin: 0 15px;
}
/* Assignment Events. Activity 4. Shape area calculator Start*/
body>div{
background-color: gray;
padding: 10px;
color: #fff;
}
div.formulaImage {
flex-basis: 33%;
padding-right: 10px;
}
div.inputForm{
flex-basis: 33%;
display: flex;
flex-direction: column;
justify-content: space-between;
margin-left: 10px;
margin-right: -10px;
}
.inputForm div{
padding-bottom: 5px;
text-align:left;
}
.formulaImage img{
object-fit: cover;
width: 100%;
}
.fcontainer label{
display: inline-block;
width: 50%;
vertical-align: top;
}
.fcontainer input{
display: inline-block;
width: 33%;
text-align: right;
height: 1.2em;
}
.fcontainer output{
display: inline-block;
width: 33%;
text-align: center;
}
#buttonRight{
text-align: end;
margin-right: 80px;
}
#weeklyWageCalculatorButton{
margin-left: 19.5em;
}
/* assignment 5 */
div.formulaImage{
flex-basis: 50%;
}
#assignment5_4{
justify-content: space-evenly;
}
#inputFields div{
padding-top: 5px;
}
#media (max-width: 800px) {
.fcontainer {
flex-direction: column;
}
section.fcontainer div {
flex-basis: 100%;
margin:15px 15px;
width: 100%;
}
div.inputForm{
margin-top: 20px;
}
div.calc {
width: 250px;
}
#weeklyWageCalculatorButton{
margin-left: 0em;
}
#mainPage{
justify-content: center;
}
#header{
max-width: 65%;
}
#btn{
margin: 0;
}
}
#yards{
margin-right: 0;
}
#error{
font-size: smaller;
color: red;
}
/* activity 2, lesson 7 table styles */
table{
border: 1px solid white;
border-collapse: collapse;
}
td{
padding: 10px;
text-align: center;
border: 1px solid white;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../css/styles.css">
<script defer src="./activity2.js"></script>
<style>
table{
border: 1px solid black;
margin: 0 auto;
}
td, th{
width: 50px;
height: 50px;
border: 1px solid black;
}
th{
border: 2px solid black;
}
</style>
</head>
<body>
<div class="calc" id="assignment6">
<h2>Multiplication Table</h2>
<div>
<label for="number1">Start</label>
<input type="number" name="number1" id="number1" min="0" placeholder="0" onchange="">
</div>
<div>
<label for="number2">End</label>
<input type="number" name="number2" id="number2" min="0" placeholder="0" onchange="">
</div>
<p id="error"></p>
<table id="output"></table>
<p><button id="btn">Calculate</button></p>
</div>
</body>
</html>

if you are building a table, then this is MUCH easier with ".insertRow" and ".insertCell"
function buildit(number1, number2) {
let tbody = document.querySelector('tbody');
let result = '';
let row = tbody.insertRow();
row.insertCell().textContent = 'X';
for (let y = number1; y <= number2; y++) {
// first Row, add the "X" numbers
if (y === number1) {
for (let x = number1; x <= number2; x++) {
row.insertCell().textContent = x;
}
}
// create new Row
row = tbody.insertRow();
// and add the "Y" number first
row.insertCell().textContent = y;
for (let x = number1; x <= number2; x++) {
row.insertCell().textContent = x * y;
}
}
}
buildit(3, 6);
th,
td {
text-align: right;
}
tbody tr:first-child,
tbody tr td:first-child {
color:red;
}
<table>
<tbody>
</tbody>
</table>

Although the example can handle different dimensions, for the sake of simplicity we are making a 10 x 10 table in this explanation.
Use 2 for loops -- the outer loop makes one row then the inner loop makes 10 cells.
Note that the loops start at 0 index so the iterations are at 10+1 to compensate.
Inside of each cell is the product of the current row index and the current cell index.
If the product of row and cell index is 0 then no cell is made.
Go back to the outer loop once the row has 10 cells and start the next row.
Repeat this process until there are 10 rows.
Details are commented in example below
// Reference the <table>
const table = document.querySelector('table');
/**
* Renders a given htmlString to a
* given DOM object.
* #param {object<DOM>} node - The tag
* to render HTML to
* #param {string<HTML>} html - The string
* that will be rendered as HTML
*/
const xHTML = (node, html) => {
node.insertAdjacentHTML('beforeEnd', html);
};
/**
* Renders a table with a given number
* of rows and columns. Each cell's
* contents are a product of row and
* column indexes.
* #param {number} rQty - Number of rows
* #param {number} cQty - Number of columns
*/
const mTable = (rQty, cQty) => {
// Make one <tr>...
for (let r = 0; r < rQty + 1; r++) {
xHTML(table, `<tr></tr>`);
/*
If the product of r and c is 0 ?
make nothing :
otherwise make a <td>(r x c)</td>
*/ // Do this >cQty< times
for (let c = 0; c < cQty + 1; c++) {
let cell = r * c === 0 ? '' : `<td>${r*c}</td>`;
xHTML(table.rows[r], cell);
}
/* Once there is >cQty< cells in
row, go to the outer loop to
make next row and so on */
}
};
mTable(10, 10);
html {
font: 2ch/1 Consolas
}
table {
table-layout: fixed;
border-collapse: collapse;
}
td {
width: 10%;
border: 0.5px solid #000;
text-align: center
}
<table></table>

Related

Words in string break in the middle, JS & CSS

I'm currently trying to write hangman game in JS (i'm novice in WEB techs) and I've encountered my first obstacle. My placeholder string for the word to guess, that is a string of hyphens and spaces, breaks through the end of the div containing it.
For example
If there is 7 dashes placeholder at the end of the line it
breaks into 6 dashes that stay at the top line and one dash which goes
to the bottom line.
It looks awful. How can I prevent this behavior and maintain my guess sentance as one string?
var word = 'Some text you have to guess and which should not break in the middle of any word';
word = word.toUpperCase();
var word1 = '';
var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for (i = 0; i < word.length; i++)
{
if (word.charAt(i) != ' ') word1 += '-';
else word1 += ' ';
}
function showHiddenWord() {
document.getElementById('WordBox').innerHTML = word1;
}
showHiddenWord();
window.onload = start;
function start(){
var div_content = '';
for(i = 0; i < 35; i++)
{
var element = 'l'+i;
div_content += '<div class="letter" onclick="check('+i+')" id="'+element+'">'+letters.charAt(i)+'</div>';
}
document.getElementById('alfabet').innerHTML = div_content;
showHiddenWord();
}
String.prototype.Swappo = function(place, sign) {
if (place > this.length - 1) return this.toString();
else return this.substr(0, place) + sign + this.substr(place+1);
}
function check(nr) {
var chosen = false;
for(i = 0; i < word.length; i++)
{
if (word.charAt(i) == letters.charAt(nr)) {
word1 = word1.Swappo(i,letters.charAt(nr));
chosen = true;
}
}
if (chosen == true){
var element = 'l'+nr;
document.getElementById(element).style.background = "#003300";
document.getElementById(element).style.color = "#00C000";
document.getElementById(element).style.border = "3px solid #00C000";
document.getElementById(element).style.cursor = "default";
document.getElementById(element).style.boxShadow = "none";
showHiddenWord();
}
}
#container
{
margin-left: auto;
margin-right: auto;
margin-top: 5em;
display: grid;
grid-template-columns: 1fr 1fr;
width: 900px;
}
#WordBox
{
grid-area: 1 / 1 / 1 / 3;
text-align: center;
font-size: 2.4em;
min-height: 100px;
}
#alfabet
{
grid-area: 2 / 2 / 3 / 3;
min-height: 280px;
display: grid;
grid-template-columns: repeat(7, auto);
grid-row-gap: .5em;
grid-column-gap: .5em;
justify-content: center;
align-items: center;
}
.letter
{
width: 30px;
height: 30px;
text-align: center;
padding: 5px;
border: 3px solid gray;
cursor: pointer;
border-radius: 12px;
}
<div id="container">
<div id="WordBox"></div>
<div id="alfabet"></div>
</div>
Sorry if I miss any other necessary part of the code. I will gladly take any help since I can't find any via google.
You can simply add white-space: nowrap; to #WordBox like this :
var word = 'Some text you have to guess and which should not break in the middle of any word';
word = word.toUpperCase();
var word1 = '';
var lettersToSwap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for (i = 0; i < word.length; i++)
{
if (word.charAt(i) != ' ') word1 += '-';
else word1 += ' ';
}
function showHiddenWord() {
document.getElementById('WordBox').innerHTML = word1;
}
showHiddenWord();
#container
{
margin-left: auto;
margin-right: auto;
margin-top: 5em;
display: grid;
grid-template-columns: 1fr 1fr;
width: 900px;
}
#WordBox
{
grid-area: 1 / 1 / 1 / 3;
text-align: center;
font-size: 2.4em;
min-height: 100px;
white-space: nowrap;
}
<div id="container">
<div id="WordBox"></div>
</div>
And if you want to keep line break and avoid dashed word to break you may consider wrapping them inside span and make them inline-block by updating your js like this :
var word = 'Some text you have to guess and which should not break in the middle of any word';
word = word.toUpperCase();
var word1 = '';
var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for (i = 0; i < word.length; i++) {
if (word.charAt(i) != ' ') word1 += '-';
else word1 += ' ';
}
function showHiddenWord() {
var r = '';
for (var i = 0; i < word1.length; i++) {
if (word1.charAt(i) != ' ') r += word1.charAt(i);
else r += '</span><span>';
}
r = "<span>" + r + "</span>";
document.getElementById('WordBox').innerHTML = r;
}
showHiddenWord();
window.onload = start;
function start() {
var div_content = '';
for (i = 0; i < 35; i++) {
var element = 'l' + i;
div_content += '<div class="letter" onclick="check(' + i + ')" id="' + element + '">' + letters.charAt(i) + '</div>';
}
document.getElementById('alfabet').innerHTML = div_content;
showHiddenWord();
}
String.prototype.Swappo = function(place, sign) {
if (place > this.length - 1) return this.toString();
else return this.substr(0, place) + sign + this.substr(place + 1);
}
function check(nr) {
var chosen = false;
for (i = 0; i < word.length; i++) {
if (word.charAt(i) == letters.charAt(nr)) {
word1 = word1.Swappo(i, letters.charAt(nr));
chosen = true;
}
}
if (chosen == true) {
var element = 'l' + nr;
document.getElementById(element).style.background = "#003300";
document.getElementById(element).style.color = "#00C000";
document.getElementById(element).style.border = "3px solid #00C000";
document.getElementById(element).style.cursor = "default";
document.getElementById(element).style.boxShadow = "none";
showHiddenWord();
}
}
#container {
margin-left: auto;
margin-right: auto;
margin-top: 5em;
display: grid;
grid-template-columns: 1fr 1fr;
}
#WordBox {
grid-area: 1 / 1 / 1 / 3;
text-align: center;
font-size: 2.4em;
min-height: 100px;
}
#WordBox span {
margin: 0 5px;
display: inline-block;
}
#alfabet {
grid-area: 2 / 2 / 3 / 3;
min-height: 280px;
display: grid;
grid-template-columns: repeat(7, auto);
grid-row-gap: .5em;
grid-column-gap: .5em;
justify-content: center;
align-items: center;
}
.letter {
width: 30px;
height: 30px;
text-align: center;
padding: 5px;
border: 3px solid gray;
cursor: pointer;
border-radius: 12px;
}
<div id="container">
<div id="WordBox"></div>
<div id="alfabet"></div>
</div>
use CSS word-break:
#WordBox {
    word-break: keep-all;
}
keep-all Breaks are prohibited between pairs of letters.
CSS Syntax:
word-break: normal|break-all|keep-all|initial|inherit;
Please find the doc:
https://www.w3schools.com/cssref/css3_pr_word-break.asp

How to create grid and place elements randomly inside column?

I have a responsive grid that is created with js and css. Inside each column in the grid I want to place elements (the red squares), but the squares should be placed randomly and only inside some of the columns. There is 50 columns, so let's say I want to place 20 squares randomly inside columns so that the squares can't overlap. How do I achieve this in the best way?
js
var grid = document.getElementById("grid");
for(var i = 0; i < 50; i++) {
var square = document.createElement("div");
square.className = 'square';
grid.appendChild(square);
var child = document.createElement("div");
child.className = 'child';
square.appendChild(child);
}
fiddle
First add an ID to each square, then the idea is to generate a random number between 0 and 49 to be able to access those squares. Each time you add a square, you have to store its index to check whether it has already been added. Only stop until 20 squares is added.
var field = document.getElementById("field");
for (var i = 0; i < 50; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
field.appendChild(square);
}
var squaresPlaced = []; // Stores the squares index placed
while (squaresPlaced.length < 20) { // Stop only if 20 squares is added
var randomIndex = parseInt(49 * Math.random()); // Generate a random number between 0 and 49
// Only add the square if it doesn't exist already
if (squaresPlaced.indexOf(randomIndex) === -1) {
squaresPlaced.push(randomIndex);
document.getElementById('square' + randomIndex).style.borderColor = 'red';
}
}
html,
body {
margin: 0;
height: 100%;
}
#field {
width: 60vw;
height: 60vw;
margin: 0 auto;
font-size: 0;
position: relative;
}
#field>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
#field>div.circle {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #f00;
border-radius: 100px;
}
<div id="field"></div>
ANSWER UPDATE
is it possible to prevent a circle to appear next to another?
Yes, it's enough to change how to generate random numbers. Change this line:
if(arr.indexOf(randomnumber) > -1) continue;
to:
if(arr.indexOf(randomnumber) > -1 || arr.indexOf(randomnumber + 1) > -1
|| arr.indexOf(randomnumber - 1) > -1) continue;
Also if I want to add more shapes, can I just create and append another shape and then clone that in the foreach?
Yes. I added an oval figure.
My proposal is:
generate 20 random different numbers
clone and move the circle adjusting the size
hide all generated circles:
var field = document.getElementById("field");
for (var i = 0; i < 50; i++) {
var square = document.createElement("div");
square.className = 'square';
field.appendChild(square);
}
for (var i = 0; i < 50; i++) {
var circle = document.createElement("div");
circle.className = (Math.random() >= 0.5) ? 'circle' : 'oval';
field.appendChild(circle);
}
var arr = [];
while (arr.length < 20) {
var randomnumber = Math.ceil(Math.random() * 50) - 1;
if (arr.indexOf(randomnumber) > -1 || arr.indexOf(randomnumber + 1) > -1
|| arr.indexOf(randomnumber - 1) > -1) continue;
arr[arr.length] = randomnumber;
}
arr.forEach(function (rnd, idx) {
$('#field > .circle, #field > .removed, #field > .oval, #field > .ovalremoved').eq(rnd)
.css({border: '1px solid #0000cc'}).clone()
.css({width: '100%', height: '100%'})
.appendTo($('.square').eq(rnd));
})
html, body {
margin: 0;
height: 100%;
}
#field {
width: 60vw;
height: 60vw;
margin: 0 auto;
font-size: 0;
position: relative;
}
#field > div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
div.circle {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #f00;
border-radius: 100px;
}
div.oval {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #f00;
border-radius: 100px / 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="field"></div>

css word-spacing with mutiple characters

I want all the numbers to be in the center of the boxes ,I am curently using word-spacing but that dont work beacuse the numbers with 2 characters take up more space then the rest of the numbers. I have tried to add a space to the numbers with 1 character ("1 ") ("11") so it looks like that, but that dont work either.
$(document).ready(function () {
$("#roll").click(function () {
document.getElementById("roll").disabled = true;
document.getElementById("re").disabled = true;
document.getElementById("bl").disabled = true;
document.getElementById("winner").innerHTML = "";
var arr = [];
var r = Math.floor(Math.random() * 17) + 1
var moveTime;
if (r == '4') { //4 red
moveTime = 8390;
} else if (r == '15') { //0 green
moveTime = 8265;
} else if (r == '11') { //11 red
moveTime = 8140;
} else if (r == '5' || r == '16') { //5 black
moveTime = 8015;
r = 5;
} else if (r == '10') { //10 red
moveTime = 7890;
} else if (r == '6') { //6 black
moveTime = 7765;
} else if (r == '9') { //9 red
moveTime = 7640;
} else if (r == '7') { //7 black
moveTime = 7515;
} else if (r == '8') { //8 red
moveTime = 7390;
} else if (r == '1' || r == '17') { //1 black
moveTime = 7265;
r = 1;
} else if (r == '14') { //14 red
moveTime = 7140;
} else if (r == '2') { //2 black
moveTime = 7015;
} else if (r == '13') { //13 red
moveTime = 6890;
} else if (r == '3') { //3 black
moveTime = 6765;
} else if (r == '12') { //12 red
moveTime = 6640;
}
var slowDown = 10000000;
var $div = $('div').css('left', 0);
while (moveTime > 0) {
slowDown--;
arr.push($('div').animate({
left: moveTime + "px"
}, 3000).promise());
({
}, 3000);
if (slowDown > 0) {
slowDown--;
moveTime = 0;
}
slowDown--;
moveTime--;
}
Promise.all(arr).then(function () {
if (r == '1' || r == '3' || r == '2' || r == '7' || r == '6' || r == '5') {
var g = document.getElementById("prev").innerHTML;
var h = document.getElementById("prevnum").innerHTML;
g = g.substr(15);
document.getElementById("winner").innerHTML = "Black" + r + " won!";
var betcol = document.getElementById("betc").innerHTML;
if (betcol == "black") {
var betamount = document.getElementById("betamount").value;
var balance = document.getElementById("balance").innerHTML;
balance = balance.substr(9);
var sum = +balance + +betamount;
document.getElementById("balance").innerHTML = "Balance: " + sum;
} else {
var betamount = document.getElementById("betamount").value;
var balance = document.getElementById("balance").innerHTML;
balance = balance.substr(9);
var sum = +balance - +betamount;
document.getElementById("balance").innerHTML = "Balance: " + sum;
}
//document.getElementById("prev").innerHTML = "Previous rolls:" + " <img src=http://319scholes.org/wp-content/uploads/2012/01/jeremiah1.jpg> " + g;
if (r < 10){
//r = '<span class="black">'r'</span>'
}
document.getElementById("prevnum").innerHTML = '<span class="black">'+ r + '</span>' + " " + h;
} else if (r == '4'|| r == '11' || r == '10' || r == '9' || r == '8' || r == '14' || r == '12' || r == '13') {
var g = document.getElementById("prev").innerHTML;
var h = document.getElementById("prevnum").innerHTML;
g = g.substr(15);
document.getElementById("winner").innerHTML = "Red" + r + " won!";
var betcol = document.getElementById("betc").innerHTML;
if (betcol == "red") {
var betamount = document.getElementById("betamount").value;
var balance = document.getElementById("balance").innerHTML;
balance = balance.substr(9);
var sum = +balance + +betamount;
document.getElementById("balance").innerHTML = "Balance: " + sum;
} else {
var betamount = document.getElementById("betamount").value;
var balance = document.getElementById("balance").innerHTML;
balance = balance.substr(9);
var sum = +balance - +betamount;
document.getElementById("balance").innerHTML = "Balance: " + sum;
}
// document.getElementById("prev").innerHTML = "Previous rolls:" + " <img src=http://www.clker.com/cliparts/X/C/L/8/R/Z/red-box-hi.png> " + g;
if (r < 10){
// r = '<span class="red">'r'</span>'
}
document.getElementById("prevnum").innerHTML = '<span class="red">'+ r + '</span>' + " " + h;
}
document.getElementById("roll").disabled = false;
document.getElementById("re").disabled = false;
document.getElementById("bl").disabled = false;
});
});
});
$(document).ready(function () {
$("#re").click(function () {
document.getElementById("betc").innerHTML = "red";
});
});
$(document).ready(function () {
$("#bl").click(function () {
document.getElementById("betc").innerHTML = "black";
});
});
#game {
position: absolute;
float: left;
margin: 170px 0 0 -8400px;
width: 10000px;
height: 125px;
background: repeating-linear-gradient(90deg, #DF0000, #DF0000 125px, #000000 125px, #000000 250px);
}
#game h3{
text-align: center;
position: absolute;
margin: 27px 50px 0 -12px;
/* padding: 0 0 0 0; */
width: 10000px;
font-size: 60px;
color: white;
overflow: visible;
word-spacing: 70px;
}
span.green {
background-size: 125px 125px;
background-color: #2dde2d;
}
h1 {
text-align: center;
margin: 130px 0 0 0;
font-size: 90px;
}
#arr{
position: absolute;
margin: 130px -28px 0 48.2%;
transform: rotate(90deg);
}
h2 {
text-align: center;
font-size: 60px;
margin: 500px 0 0 0;
}
h3 {
font-size: 40px;
}
body {
overflow-x: hidden;
background-image: url(http://www.casino-capers.org/wp/wp-content/uploads/2015/01/Casino-Capers-Web-Background-2015.jpg);
}
button {
width: 300px;
height: 100px;
font-size: 20px;
margin: 350px 0 0 40%;
position: absolute;
}
#re {
width: 100px;
height: 100px;
font-size: 20px;
margin: 350px 0 0 30%;
background-color: red;
position: absolute;
}
#bl {
width: 100px;
height: 100px;
font-size: 20px;
margin: 350px 0 0 62%;
background-color: black;
color: white;
position: absolute;
}
#balance{
font-size: 50px;
margin: 80px 0 0 1%;
position: absolute;
}
#betc{
height: 0px;
width: 0px;
position: absolute;
font-size: 0px;
}
#betamount{
font-size: 25px;
margin: 0 0 0 10%;
position: absolute;
width: 60px;
}
h6{
font-size: 25px;
margin: 0 0 0 1%;
position: absolute;
}
#prevnum{
position: absolute;
margin: -91px 0 0 248px;
font-size: 23PX;
float: left;
color: white;
word-spacing: 30.5px;
width: 400px;
overflow: hidden;
height: 65px;
}
img {
height: 40px;
width: 40px;
border-radius: 50%;
display: inline-block;
}
.black {
background-color: black;
float: left;
width: 50px;
line-height: 50px;
border-radius: 50%;
color: white;
text-align: center;
margin: 5px;
}
.red {
background-color: red;
float: left;
width: 50px;
line-height: 50px;
border-radius: 50%;
color: white;
text-align: center;
margin: 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h3 id="prev">Previous rolls:</h3>
<h3 id="prevnum"></h3>
<h6>Bet amount:</h6>
<input id="betamount" type="text" betamount="betamount">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="roll">Roll</button>
<div id="game">
<h3>1 14 2 13 3 12 4 <span class="green">0</span> 11 5 10 6 9 7 8 1 14 2 13 3 12 4 <span class="green">0</span> 11 5 10 6 9 7 8 1 14 2 13 3 12 4 <span class="green">0</span> 11 5 10 6 9 7 8 1 14 2 13 3 12 4 <span class="green">0</span> 11 5 10 6 9 7 8 1 14 2 13 3 12 4 <span class="green">0</span> 11 5 10 6 9 7 8 1 14 2 13 3 </h3></div>
<img id="arr" src="http://flaviar.com/gui/site/img/post_arrow.png">
<button id="re">Red</button>
<button id="bl">Black</button>
<h2 id="balance">Balance: 1000</h2>
<h2 id="winner"></h2>
<p id="betc"></p>
</body>
</html>
I'm not sure if there is a reason for the current approach but I would suggest not trying to center the numbers to a background image and instead, I would put the numbers in a list.
You can center the text within the li and also give the li a set width. This way your numbers will always be in the center. Giving the ul a list-type of non will remove the bullets and setting the li to inline-block will put them all in one row. Using the nth-of-type pseudo-class you can then set every other li to have a different background. More info on nth-of-type
Here is a quick codepen I made to demonstrate: http://codepen.io/LukeBailey/pen/dOjPZY
Note: I've commented out the whitespace between each li so they touch. This is a qwerk of inline-block, where if the elements have whitespace in the markup it separate them. Article: 'Fighting the Space Between Inline Block Elements'

print multiple set of numbers from array

function numbersInBucket(setOfNumbers, numbersInArray) {
var numbers = [];
for (var i = numbersInArray; i > 0; i--){
numbers.push(i);
}
numbers.sort(function(){
return (Math.round(Math.random())-0.5);
}
);
return numbers.slice(0, setOfNumbers).sort(function(a, b){return a - b});
}
function print(numbers){
var html = "";
for (var i in numbers) {
html = html + '<li class="item">' + numbers[i] + '</li>';
}
document.getElementById("output").innerHTML = html;
}
function rowOfNumbers(){
for(var i = 0; i < 3; i++){
print(numbersInBucket(5, 75));
}
}
.container {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
ul li {
list-style: none;
display: inline-flex;
justify-content: center;
}
.item {
border: 5px solid #E7F7F5;
color: #E7F7F5;
margin: 20px;
border-radius: 100px;
font-size: 40px;
width: 100px;
height: 100px;
text-align: center;
line-height: 220%;
justify-content: space-between;
}
<div class="container">
<ul id="output"></ul>
</div>
<input class="button" type="button" value="click " id="reload" onclick="rowOfNumbers()">
Hello there;
How can I print multiple set of numbers. For example,
3 12 23 33 44, 2 5 13 22 36, 12 23 27 29 44. With my current code I can have one set of numbers as output the way I want it. But I would like multiple sets with different numbers. I try using a for loop with no luck. The set of numbers has to be inside an li tag. Can someone please set me in the right direction, I am trying to learn interactive web development.
On this line: document.getElementById("output").innerHTML = html; you are replacing the inner HTML of the element with a new set of elements. This means that you are emptying the element before appending newly generated elements, so they never increase in number.
A quick solution will be instead of overwriting the inner HTML, you append to it using: document.getElementById("output").innerHTML += html;.
See proof-of-concept example below:
function numbersInBucket(setOfNumbers, numbersInArray) {
var numbers = [];
for (var i = numbersInArray; i > 0; i--){
numbers.push(i);
}
numbers.sort(function(){
return (Math.round(Math.random())-0.5);
}
);
return numbers.slice(0, setOfNumbers).sort(function(a, b){return a - b});
}
function print(numbers){
var html = "";
for (var i in numbers) {
html = html + '<li class="item">' + numbers[i] + '</li>';
}
document.getElementById("output").innerHTML += html;
}
function rowOfNumbers(){
for(var i = 0; i < 3; i++){
print(numbersInBucket(5, 75));
}
}
.container {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
ul li {
list-style: none;
display: inline-flex;
justify-content: center;
}
.item {
border: 5px solid #E7F7F5;
color: #E7F7F5;
margin: 20px;
border-radius: 100px;
font-size: 40px;
width: 100px;
height: 100px;
text-align: center;
line-height: 220%;
justify-content: space-between;
}
<div class="container">
<ul id="output"></ul>
</div>
<input class="button" type="button" value="click " id="reload" onclick="rowOfNumbers()">

Javascript Statistics Calculator

I am trying to make a JS function that takes in:
- Count of entries
- Minimum of entries
- Maximum of entries
- Range of entries
- Sum of entries
- Average of entries
I am trying to use a loop alert to take in the user input but with no luck, here is my code so far:
<!DOCTYPE html>
<html>
<head>
<script>
function show_prompt() {
i = 1;
do {
var number = prompt("Please Enter a Number");
i++;
if (number % 2) {
document.write("Number: " + number);
document.write("<br>");
}
}
while (i <= 15);
}
show_prompt();
</script>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 55px;
text-decoration: none;
}
li a:hover {
background-color: #111;
}
.tasks {
color: white;
font-size: 250%;
text-align: center;
}
</style>
<body>
</body>
</html>
Many Thanks
James
I tried some codes. Try this snippet.https://jsfiddle.net/2fo8ctgv/2/
var i = 0,
answer=true,
nums=[],
min,
max,
avrg = 0,
sum = 0;
do{
var num;
if(num=prompt('number')){
nums.push(num)
i++;
} else {
answer = false;
}
} while(answer);
nums.forEach(function(c){sum+=c;});
nums.sort(function(a,b){return a-b});
min = nums[0];
max = nums[nums.length-1];
avrg=sum/i;
console.log(min,max,avrg,sum);

Categories

Resources