Words in string break in the middle, JS & CSS - javascript

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

Related

trying to make a wordle game, but the letters are going up to down, instead of right to left, i don't know how to tackle it

I am making a 4x4 wordle game, and I used js to make the squares and input letters. When I input letters they go top to bottom instead of left to right and I'm not really sure how to fix it. I don't know how to modify the key events to go from the first column to the second, this is the code that deals with it, but I don't know why it isn't working, i feel like the code that is affecting it is this, but im not sure
if (col < gameWidth) {
let currsquare = document.getElementById(row.toString() + '-' + col.toString());
currsquare.innerText = e.code[3];
col++;
}
var gameHeight = 4; //number of guesses
var gameWidth = 4; //length of the word
var row = 0; //current guess (attempt #)
var col = 0; //current letter for that attempt
var gameOver = false;
var word = "RAAA";
window.onload = function() {
initialize();
};
function initialize() {
const darkModeToggle = document.getElementById("dark-mode-toggle");
darkModeToggle.addEventListener("click", () => {
document.body.classList.toggle("dark");
});
const instructionsToggle = document.getElementById("info");
const instructionsContainer = document.getElementById("instructions-container");
// Hide the instructions by default
instructionsContainer.style.display = "none";
// Show or hide the instructions when the button is clicked
instructionsToggle.addEventListener("click", () => {
if (instructionsContainer.style.display === "none") {
instructionsContainer.style.display = "block";
} else {
instructionsContainer.style.display = "none";
}
});
// Create the game board
for (let i = 0; i < gameHeight; i++) {
let row = document.createElement("div");
row.classList.add("row");
for (let j = 0; j < gameWidth; j++) {
let square = document.createElement("span");
square.id = i.toString() + "-" + j.toString();
square.classList.add("square");
square.innerText = "";
row.appendChild(square);
}
document.getElementById("board").appendChild(row);
}
// Listen for Key Press
document.addEventListener("keyup", (e) => {
if (gameOver) return;
if ("KeyA" <= e.code && e.code <= "KeyZ") {
if (col < gameWidth) {
let currsquare = document.getElementById(row.toString() + '-' + col.toString());
currsquare.innerText = e.code[3];
col++;
}
} else if (e.code == "Backspace") {
if (col > 0) {
col--;
let currsquare = document.getElementById(row.toString() + '-' + col.toString());
currsquare.innerText = "";
}
} else if (e.code == "Enter") {
update();
row += 1; // start new row
col = 0; // reset current index to 0 for new row
}
if (!gameOver && row == gameHeight) {
gameOver = true;
document.getElementById("answer").innerText = word;
}
});
}
function update() {
let correct = 0;
for (let column = 0; column < gameWidth; column++) {
let currsquare = document.getElementById(row.toString() + '-' + column.toString());
let letter = currsquare.innerText;
// Is it in the correct position?
if (word[row*gameWidth + (column % gameWidth)] == letter) {
currsquare.classList.add("correct");
correct += 1;
} // Is it in the word?
else if (word.includes(letter)) {
currsquare.classList.add("present");
} // Not in the word
else {
currsquare.classList.add("absent");
}
}
if (correct == gameWidth) {
gameOver = true;
document.getElementById("congrats").style.display = "block";
}
if (!gameOver && row == gameHeight - 1) {
gameOver = true;
document.getElementById("answer").innerText = word;
}
}
this is the updated html
<html>
<head>
<title>Wordle</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale = 1.0">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.15.3/css/all.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
<link rel="stylesheet" href="wordle.css">
</head>
<body>
<h1 id="title">Wordle</h1>
<i id = "info" class="fas fa-info-circle"></i>
<i id="dark-mode-toggle" class="fas fa-circle"></i>
<hr>
<br>
<div id="board">
</div>
<br>
<div id="instructions-container">
<p>The goal is to guess the word </p>
</div>
<img id="congrats" src="https://res.cloudinary.com/mkf/image/upload/v1675467141/ENSF-381/labs/congrats_fkscna.gif" alt="Congratulations">
<script src="wordle.js"></script>
</html>
This is the updated css
body {
font-family: Arial, Helvetica, sans-serif;
text-align: center;
--correct:#6baa64;
--background-color:white;
--text-color:black;
color: var(--text-color);
background-color: var(--background-color);
}
body.dark{
font-family: Arial, Helvetica, sans-serif;
text-align: center;
--correct:#6baa64;
--background-color:black;
background-color: var(--background-color);
--text-color:white;
color:white;
}
hr {
width: 500px;
}
#title {
font-size: 36px;
font-weight: bold;
letter-spacing: 2px;
}
#board {
width: 350px;
height: 420px;
margin: 0 auto;
margin-top: 3px;
display: flex;
flex-wrap: wrap;
}
.square {
border: 2px solid lightgray;
width: 60px;
height: 60px;
margin: 2.5px;
color: black;
font-size: 36px;
font-weight: bold;
display: flex;
justify-content: center;
align-items: center;
}
.correct {
background-color: var(--correct);
color: white;
border-color: white;
}
.present {
background-color: #C9B458;
color: white;
border-color: white;
}
.absent {
background-color: #787C7E;
color: white;
border-color:white;
}
#congrats {
display: none;
}
#dark-mode-toggle {
position: fixed;
top: 10px;
right: 250px;
}
#question{
position: fixed;
top: 10px;
right: 200px;
}
#info{
position: fixed;
top: 10px;
right: 300px;
}
You dont need display: flex; in board but you need to add display: flex; to row
#board {
width: 350px;
height: 420px;
margin: 0 auto;
margin-top: 3px;
}
.row {
display: flex;
}

Build a multiplication table

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>

How do you target specific divs in JavaScript after using a for loop to create them?

Since this is an Etch-a-Sketch ripoff, I need to be able to color the divs out of order but, the for loop I have set up loops through every square and colors them all after only touching one of them.
JavaScript:
const container = document.getElementById("container");
function makeRows (rows, columns) {
container.style.setProperty('--grid-rows', rows);
container.style.setProperty('--grid-cols', columns);
for (c = 0; c < (rows * columns); c++) {
let cell = document.createElement("div");
//cell.innerText = (c + 1);
container.appendChild(cell).className = "grid-item";
}
}
//Draw Board
makeRows(16, 16);
//Paint on board
const paint = document.querySelector("div.grid-item");
paint.addEventListener('mouseover', function(){
let paintBrush = document.getElementsByClassName('grid-item');
for (let i = 0; i < paintBrush.length; i++)
{
paintBrush[i].style.backgroundColor = "black";
}
console.log("AHH HELP AHH");
});
CSS:
:root {
--grid-cols: 0;
--grid-rows: 0;
}
#container {
display: grid;
padding: 10em;
height: 40vh;
width: 50vh;
margin-left: auto;
margin-right: auto;
grid-template-rows: repeat(var(--grid-rows), 1fr);
grid-template-columns: repeat(var(--grid-cols), 1fr);
}
.grid-item {
padding: 1em;
border: 1px solid #ddd;
text-align: center;
}
I think you can get all elements by class name (and then loop through them to add the listeners individually.
See demo below
const container = document.getElementById("container");
function makeRows(rows, columns) {
container.style.setProperty('--grid-rows', rows);
container.style.setProperty('--grid-cols', columns);
for (c = 0; c < (rows * columns); c++) {
let cell = document.createElement("div");
//cell.innerText = (c + 1);
container.appendChild(cell).className = "grid-item";
}
}
//Draw Board
makeRows(16, 16);
//Paint on board
const paint = document.getElementsByClassName("grid-item");
for (var idx = 0; idx < paint.length; idx++) {
paint[idx].addEventListener('mouseover', function() {
this.style.backgroundColor = "black";
});
}
:root {
--grid-cols: 0;
--grid-rows: 0;
}
#container {
display: grid;
padding: 10em;
height: 40vh;
width: 50vh;
margin-left: auto;
margin-right: auto;
grid-template-rows: repeat(var(--grid-rows), 1fr);
grid-template-columns: repeat(var(--grid-cols), 1fr);
}
.grid-item {
padding: 1em;
border: 1px solid #ddd;
text-align: center;
}
<div id="container"></div>

How can I remove all borders from a group of elements except for the one created?

I'm trying to dynamically make all borders disappear except the newest created container's border I have tried the commented out section of the JavaScript. Can someone please provide an explanation/example of how this can be done?
function countButtonLinks() {
var elementGroups = document.getElementById('containsAll');
if(elementGroups.children.length == 0) {
var numID = 1;
}
if(elementGroups.children.length == 1) {
var numID = 2;
}
if(elementGroups.children.length == 2) {
var numID = 3;
}
if(elementGroups.children.length == 3) {
var numID = 4;
}
if(elementGroups.children.length == 4) {
var numID = 5;
}
if(elementGroups.children.length == 5) {
var numID = 6;
}
return numID;
}
function createContainer() {
if(document.getElementById('containsAll').children.length < 6) {
var elementA = document.createElement("span");
var elementAInnerTxt = document.createElement("div");
elementA.id = 'elem' + countButtonLinks();
elementAInnerTxt.id = 'elemInner' + countButtonLinks();
elementA.className = 'elem1';
elementAInnerTxt.className = 'elemInner1';
elementA.appendChild(elementAInnerTxt);
document.getElementById('containsAll').appendChild(elementA);
}
}
.containsAll {
width: 91%;
height: 75%;
position: absolute;
float: left;
margin-top: 1%;
margin-left: 1%;
background-color: transparent;
z-index: 91;
border: 1px #000000 solid;
border-radius: 7px;
padding: 5px;
}
.elem1 {
max-width: 100%;
max-height: 100%;
min-width: 100px;
min-height: 60px;
float: left;
background-color: transparent;
border: 1px #333333 solid;
border-radius: 5px;
}
.elemInner1 {
max-width: 100%;
max-height: 100%;
min-width: 100px;
min-height: 60px;
float: left;
background-color: transparent;
padding: 5px;
}
.buttonClass {
width: 100px;
height: 50px;
}
<button class="buttonClass" type="button" onclick="createContainer();">Click Me</button>
<div id="containsAll" class="containsAll"></div>
Please, no JQuery.
function countButtonLinks(){
var elementGroups = document.getElementById('containsAll');
// you don't need to use 'var numID'
return elementGroups.children.length + 1;
}
function createContainer(){
if(document.getElementById('containsAll').children.length < 6){
// add code here
for(var i=0;i<document.getElementById('containsAll').children.length;i++){
document.getElementById('containsAll').children[i].style.border = '0 none';
}
var elementA = document.createElement("span");
//...
Simply call the existing children of the element and remove the border before inserting
another element:
function countButtonLinks(){
var elementGroups = document.getElementById('containsAll');
var groupLength = elementGroups.children.length;
return groupLength++;
}
function createContainer() {
var containsAll = document.getElementById('containsAll'),
childrenLength = containsAll.children.length;
if (childrenLength >= 6) {
return; // Bail immediately since we only need to add a new element if the children's length is less than 6
}
// Call previous children
for ( var i = 0; i < childrenLength; i++ ) {
let child = containsAll.children[i];
// You can add a new class here that will remove the border
// but in this example, we'll use the style attribute to remove the border
child.style.border = 0;
}
// Now, add the new element
var elementA = document.createElement("span");
var elementAInnerTxt = document.createElement("div");
elementA.id = 'elem' + countButtonLinks();
elementAInnerTxt.id = 'elemInner' + countButtonLinks();
elementA.className = 'elem1';
elementAInnerTxt.className = 'elemInner1';
elementA.appendChild(elementAInnerTxt);
containsAll.appendChild(elementA);
}
Also, if you're going to use an element multiple times inside a function, make it a habit to store that element in a variable so you don't repeatedly calls the document.getElementById function.
You can accomplish this using the CSS :last-child selector
var container = document.getElementById('container');
function count_button_links()
{
return container.children.length + 1;
}
function new_container()
{
if (count_button_links() > 6) return false;
let span = document.createElement('span');
span.id = 'el_' + count_button_links();
span.className = 'box';
container.appendChild(span);
}
#container {
width: 100%;
background-color: transparent;
border: 1px solid #000;
border-radius: 7px;
padding: 5px;
display:flex;
height:200px;
}
.box {
flex:0 0 100px;
height:60px;
background-color: transparent;
border-radius: 5px;
}
.box:last-child{
border:1px solid #333;
}
button {
width: 100px;
height: 50px;
}
<button type="button" onclick="new_container();">Click Me</button>
<div id="container"></div>

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()">

Categories

Resources