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()">
Related
My goal is to try to animate text. Every example on how to animate text looks at a singular string. I'd like to animate an array of string values, one after the other.
The problem I'm getting is that although I'm creating the elements needed successfully, only the .word3 class is actually being rendered. I'm not sure why this is and after banging my head against the wall, I'm not sure how to fix it.
I've used a lot of stack overflow resources to overcome things like using setTimeout in a for loop which lead to using an iife.. Here is the code that I've settled on for the time being. Using async caused a lot of issues as async needs to be at the top level apparently and I often got the 'unexpected reserved keyword error'.
There must be a simple way to do this?
All help is appreciated, thanks!
const wrapper = document.querySelector(".wrapper");
const buttonCreate = document.querySelector(".create-element");
const buttonAnimate = document.querySelector(".animation");
buttonCreate.addEventListener("click", createElement);
let i = 0;
let j = 0;
let sampleArray = ["Just", "another", "cool", "heading"];
function createElement() {
// debugger
// Create text wrapper in main body and add class
const newDiv = document.createElement("div");
newDiv.classList.add("text-wrapper");
wrapper.insertAdjacentElement("afterbegin", newDiv);
// Modifying text-wrapper html to include p tag with dynamic class
function word() {
sampleArray.map((word, i) => {
newDiv.innerHTML += `<p class="word${i}"></p>`;
let element = document.querySelector(`.word${i}`);
console.log(element);
let j = 0
let interval = setInterval(() => {
element.innerText += word[j];
j++;
if(j === word.length) {
clearInterval(interval)
}
}, 200)
});
};
word();
return;
}
html {
box-sizing: border-box;
}
*,*::before, *::after {
box-sizing: inherit;
}
body {
margin: 0;
}
.wrapper {
width: 100%;
background-color: #333;
color: #FFA;
text-align: center;
height: 100vh;
display: flex;
flex-direction: row;
gap: 10rem;
align-items: center;
justify-content: center;
font-size: 4rem;
position: relative;
}
.text-wrapper {
position: absolute;
top: 0;
width: 100%;
display: flex;
gap: 3rem;
flex-direction: column;
justify-content: center;
justify-content: space-around;
}
.button {
font-size: 3rem;
border-radius: 6px;
background-color: #47cefa;
}
.button:hover {
cursor: pointer;
background-color: #BCEF4D;
}
<section class="wrapper">
<button class="button create-element">Create Element</button>
<button class="button animation">Start Animation</button>
</section>
Instead of setInterval in a loop of the array, just create a recursive function that calls setTimeout and calls itself and increments the array counter until the end of the array.
The lay out of my answer is off because I'm not exactly sure on what your expected layout is
const wrapper = document.querySelector(".text-wrapper");
const buttonAnimate = document.querySelector(".animation");
buttonAnimate.addEventListener("click", animation);
let i = 0;
let sampleArray = ["Just", "another", "cool", "heading"];
function animation() {
if (i < sampleArray.length) {
let el = document.createElement("p");
el.innerHTML = sampleArray[i];
wrapper.appendChild(el);
i++;
setTimeout(animation, 200);
}
}
.wrapper {
width: 100%;
background-color: #333;
color: #FFA;
text-align: center;
height: 100vh;
display: flex;
flex-direction: row;
gap: 10rem;
align-items: center;
justify-content: center;
font-size: 4rem;
position: relative;
}
.text-wrapper {
position: absolute;
top: 0;
width: 100%;
display: flex;
gap: 3rem;
flex-direction: column;
justify-content: center;
justify-content: space-around;
}
.button {
font-size: 3rem;
border-radius: 6px;
background-color: #47cefa;
}
.button:hover {
cursor: pointer;
background-color: #BCEF4D;
}
<section class="wrapper">
<button class="button animation">Start Animation</button>
<div class="text-wrapper"></div>
</section>
I'm creating a small landing page that, at the end, is going to pick a random city stored between a choice that the user inputs choose where to go for the next trip. When the user inputs the city name inside the input field, everything is ok, a new list element is created inside the ordered list and the name is pushed into the array (for later on randomly choose between one). But when I'm trying to remove the city name with the close function, the list element correctly disappears, but inside the array, instead of removing the selected item, it removes the object on position 0. I'm trying to figure out what's wrong with my code. Below, the code that I've written so far:
const submitBtn = document.querySelector(".addCity");
const cityList = document.querySelector(".city-ol");
let createdLi = document.getElementsByTagName("li");
const lis = document.querySelectorAll(".city-ol li");
let array = [];
submitBtn.addEventListener("click", newElement);
function newElement() {
let li = document.createElement("li");
let inputValue = document.querySelector(".inputTextField");
let t = document.createTextNode(inputValue.value);
li.appendChild(t);
if (inputValue.value === "") {
alert(
"Attenzione, il campo di inserimento della città è vuoto. Inserire una città."
);
} else {
cityList.appendChild(li);
array.push(inputValue.value);
inputValue.value = "";
}
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
let div = this.parentElement;
div.style.display = "none";
array.splice(close[i], 1);
};
};
};
body {
font-family: "Poppins", sans-serif;
height: 900px;
text-align: center;
}
#landing-section {
height: 100%;
}
.container {
height: 100%;
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(6, 1fr);
gap: 5px;
justify-content: center;
align-content: center;
}
.header {
/* background-color: #935ee9; */
grid-column: 1 / -1;
border: 1px solid #000000;
}
.main-head {
font-size: 3rem;
text-transform: uppercase;
margin-bottom: 0;
}
.main-para {
font-size: 1.2rem;
margin-top: 10px;
}
.cityInput {
display: flex;
justify-content: center;
align-items: center;
/* background-color: #a8d051; */
grid-column: 1 / 2;
grid-row: 2 / 3;
border: 1px solid #000000;
}
.inputTextField {
width: 200px;
}
.cityList {
display: flex;
justify-content: center;
align-items: center;
/* background-color: #a98649; */
grid-column: 1 / 2;
grid-row: 3 / -1;
width: 100%;
border: 1px solid #000000;
}
.city-ol {
font-size: 1.5rem;
width: 100%;
}
.city-ol li:nth-child(odd) {
background: #f9f9f9;
}
li {
margin: 5px 20px;
}
.close {
position: relative;
top: 3px;
float: right;
}
.close:hover {
background-color: #DCDCDC;
color: white;
}
.cityImage {
/* background-color: #14d50e; */
grid-column: 2 / -1;
grid-row: 2 / -1;
border: 1px solid #000000;
}
<section id="landing-section">
<div class="container">
<div class="header">
<h1 class="main-head">Make That Trip</h1>
<p class="main-para">Are we ready to choose our next trip?</p>
</div>
<div class="cityInput">
<input class="inputTextField" type="text" value="" data-type="city" placeholder="Inserisci la meta">
<button class="addCity">Aggiungi</button>
</div>
<div class="cityList">
<table>
<ol class="city-ol">
</ol>
</table>
</div>
<div class="cityImage">City Image</div>
</div>
</section>
Problem FIX can be put 2 ways
When you are adding any any new element all 'close' on dom are added to close[]
Here element is present on DOM, Which get audited during add Element
let div = this.parentElement;
div.style.display = "none";
FIX: Remove it from DOM
let elm = this.parentElement;
elm.remove();
During loop execution i variable will be incrementing as 1 2 3... but it wont be same during function execution
FIX : Delecare i using let
for (let i = 0; i < close.length; i++) {
Thanks to all of your answers I was able to figure out and fix the problem, I will explain it below:
Here I've isolated the text content of the list without the span, so that it matches exactly to the array objects
let textNode = div.childNodes[0],
text = textNode.textContent;
And here, finally, I've set the array.indexOf() to be equal to the isolated text above and then I've checked with an if statement, if the value of index is greater of -1 then trigger the array.splice() method
let index = array.indexOf(text);
if (index > -1) {
array.splice(index, 1);
};
i create a counter.
dk = parseInt(document.querySelector('.dm').innerText);
for (var i = 0; i <= dk; i++) {
(function(i) {
setTimeout(function() {
document.querySelector('.dm').innerText = i;
}, i * 100);
})(i);
}
console.log(dk);
.counter { display: flex; }
.dm {
background: tomato;
padding: 15px;
font-size: 5em;
font-weight: 700;
width: 100px;
height: auto;
text-align: center;
margin: 0 2px;
}
<div class="counter">
<div class="dm">40</div>
<div class="dm">30</div>
</div>
problem is only first div counter is working.
can we parse element of innerHTMl by html dom like classname...i try but result is Nan.
i want run all counter if i add same classname with different inner values.
Your problem is that you are using document.querySelector().
When you use document.querySelector('.dm') it will return only the first element matching this selector, you need to use document.querySelectorAll('.dm') to get all the matching elements.
But with multiple elements you will need a loop to do that, because querySelectorAll() will return a nodeList which is a collection(array).
This is how should be your code:
var elements = document.querySelectorAll('.dm');
Array.from(elements).forEach(function(el, ind){
let dk = parseInt(elements[ind].innerText)
for (var i = 0; i <= dk; i++) {
(function(i) {
setTimeout(function() {
elements[ind].innerText = i;
}, i * 100);
})(i);
}
});
Demo:
var elements = document.querySelectorAll('.dm');
Array.from(elements).forEach(function(el, ind){
let dk = parseInt(elements[ind].innerText)
for (var i = 0; i <= dk; i++) {
(function(i) {
setTimeout(function() {
elements[ind].innerText = i;
}, i * 100);
})(i);
}
});
.counter { display: flex; }
.dm {
background: tomato;
padding: 15px;
font-size: 5em;
font-weight: 700;
width: 100px;
height: auto;
text-align: center;
margin: 0 2px;
}
<div class="counter">
<div class="dm">40</div>
<div class="dm">30</div>
</div>
Your question is not very clear, but if I understood correctly, you want both timer to run simultaneous, right?
If so, then the code below should help.
Use the querySelectorAll() to get all elements with same class, then loop through them to get the value and make it increase like you was doing.
const dms = document.querySelectorAll('.dm');
for (let j = 0; j < dms.length; j++){
let dk = dms[j].innerText;
for(let i = 0; i <= dk; i++){
setTimeout(function() {
dms[j].innerText = i;
}, i * 100);
}
console.log(dk);
}
.counter{
display: flex;
}
.dm {
background: tomato;
padding: 15px;
font-size: 5em;
font-weight: 700;
width: 100px;
height: auto;
text-align: center;
margin: 0 2px;
}
<div class="counter">
<div class="dm">40</div>
<div class="dm">30</div>
</div>
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
html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<section id="boxBig">
<div class="box" id="perspective">
<div class="object" id="seekSlider"></div>
</div>
</section>
<section id="layout">
<div class="stats">
<input id="stats1" type="text" value="perspective-origin">
<input id="stats2" type="text" value="perspective">
<input id="stats3" type="text" value="perspective">
<input id="stats4" type="text" value="preserve-3d">
<input id="stats5" type="text" value="rotatez">
</div>
</section>
</body>
</html>
css
.object {
align-self: center;
margin: auto;
width: 100px;
height: 100px;
background: green;
}
#boxBig {
margin: 0 auto;
width: 200px;
height: 200px;
background: red;
display: flex;
flex-direction: row;
align-item: center;
justify-content: center;
}
.box {
width: 150px;
height: 150px;
background: blue;
align-self: center;
display: flex;
flex-direction: row;
justify-content: center;
}
#perspective {
perspective: 0px;
-webkit-perspective: 0px;
}
#seekSlider {
width: 100%;
}
#layout {
flex-direction: row;
flex-wrap: nowrap;
display: flex;
justify-content: center;
align-content: center;
background: orange;
}
.buttons {
flex: 2;
order: 0;
background: yellow
}
.stats {
flex: 1;
order: 0;
background: lightgreen
}
javascript
"use strict";
function Gid(id) {
return document.getElementById(id);
}
var px = 0;
var seekSlider = Gid('seekSlider');
var i = 0;
var stats1 = Gid('stats1');
var stats2 = Gid('stats2');
var stats3 = Gid('stats3');
var stats4 = Gid('stats4');
var stats5 = Gid('stats5');
var stats6 = Gid('stats6');
var stats7 = Gid('stats7');
var stats8 = Gid('stats8');
var stats9 = Gid('stats9');
var stats10 = Gid('stats10');
is the any good way to write this with an array? i tried this is one of the function there are ten there mostly the same so i didnt post
function perspectiveOrigin() {
var seekSlider = Gid('seekSlider');
var boxBig = Gid('boxBig');
var box = document.getElementsByClassName('box');
var perspective = Gid('perspective');
px += 10;
seekSlider.style.perspectiveOrigin = px + "%" + "" + px + "%";
var result = 'perspecspective-origin:' + px + '%';
stats1.value = result;
console.log(seekSlider.style.perspectiveOrigin);
}
so on..and i tried to make finial status for the element ,like status including its rotates and perspective
You could create an array like so:
var stats = [];
Then you can use one of the following depending on your own preference:
stats.push(Gid('stats1'));
stats.push(Gid('stats2'));
stats[0] = Gid('stats1');
stats[1] = Gid('stats2');
Next you want to iterate through the array:
with push method do:
for (var stat in stats) {
perspectiveOrigin(stats[stat]);
}
With other method you can also use:
for (var i=0; i < stats.length; i++) {
perspectiveOrigin(stats[i]);
}
You'll also need to change your function a little bit:
perspectiveOrigin() to perspectiveOrigin(stat)
and then in this function change:
stats1.value = result; to stat.value = result;
I haven't tested any of this, but let me know if you have any problems =]