js code running in console but not by live server - javascript

I am biginner coder in js. I am trying to make a counter till 100. The given code works fine in console but counter dosent work in browser by live server.
`JS
var count=1;
setInterval(()=>{
if(count!=100)
{
count++;
k.innerHTML=count
}
},10)
HTML
<html>
<head>
<style>
body{
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
height: 80vh;
}
</style>
</head>
<body>
<p onclick="hell()">counter</p>
<div><span id="oe">1</span>
<i class="fa-solid fa-play"></i>
</div>
</body>
</html>
Countdown reached 100. It works perfectly in browser.

try this :
let count=0;
let timer = 1;
let k = null;
let para = null;
document.addEventListener("DOMContentLoaded", onDomContentLoaded);
function onDomContentLoaded(e){
k = document.getElementById("oe");
para = document.getElementById("myParagraph");
para.addEventListener("click",hell);
}
function countFunction(){
if(count<100){
count++;
console.log(count);
k.innerHTML=count;
}
if(count===100){
clearInterval(timer);
count = 0;
}
}
function hell(){
if(count===0){
timer = setInterval(countFunction,10);
}
}
body{
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
height: 80vh;
}
<p id="myParagraph">counter</p>
<div><span id="oe">1</span>
<i class="fa-solid fa-play"></i>
</div>

Related

How to make an element NOT to steal focus from an input?

I have a simple input and an SVG-pic that sends the input-text to a server and instantly adds the text into a document.createElement('div')...etc
Is there a way to make my SVG-pic non-focusable so it doesn't steal focus from others (in my case - my input)
upd.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="wrapper">
<div>1</div>
<div>2</div>
<div>3</div>
<div>
<input id="senderInput" type="text">
<img src="../../img/Calendar.svg" alt="" onclick="imgClick(event)">
</div>
</div>
</body>
</html>
.wrapper {
max-width: 300px;
margin: 0 auto;
}
.wrapper > div {
width: 250px;
height: 150px;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
background-color: var(--divBG);
margin: 20px;
}
arr = ['#f00', '#aaa004', '#b70808', '#0855b7', '#681a73', '#d56e00']
document.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll('.wrapper > div').forEach(d => {
d.style.backgroundColor = arr[getRandomInt(6)]
})
});
function j(arg) {
return document.querySelector(arg)
}
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function imgClick(e) {
j('.wrapper > div').innerText = j('#senderInput').value
setTimeout(() => {
var dd = document.createElement('div')
dd.style.backgroundColor = arr[getRandomInt(6)]
dd.innerText = '234'
j('.wrapper').appendChild(dd)
}, 100);
j('#senderInput').focus()
}
Actually, the simple
event.preventDefault()
msgInput.focus()
worked fine, the problem solved

Refactoring redundant JS logic for "Instagram-Story pagination"

I'm working on a website which uses fullpage.js and has a section with several slides. The slides switch automatically every 10 seconds.
I wanted to create those bars like Instagram has them, that slowly fill up. When one bar is filled, the viewport changes to the next page and the next bar starts to fill itself. And when the user manually switches slides the according bar should start animating.
I didn't find anything online so I built it from scratch and after some attempts I got it working as I wanted. BUT the code ist horrible.
I am 100% sure it is possible to bring it down to a few lines but as I'm not skilled enough to refactor it that way. How could this function be solved in a better way, with less code? Any help would help me a lot to learn here.
Here's the relevant code I wrote (It won't work properly, because it's based on the URL, but I'm sure you'll get how it would work with the correct URL)
function locationHashChanged() {
if (location.hash === '#page2') {
document.getElementById("Loadingbar-2-1").setAttribute("style","animation-name:loadingbar;animation-duration:10s;animation-timing-function:linear;");
document.getElementById("Loadingbar-2-2").setAttribute("style","width:0%");
document.getElementById("Loadingbar-2-3").setAttribute("style","width:0%");
document.getElementById("Loadingbar-2-4").setAttribute("style","width:0%");
document.getElementById("Loadingbar-2-5").setAttribute("style","width:0%");
document.getElementById("Loadingbar-2-6").setAttribute("style","width:0%");
} else if (location.hash === '#page2/1') {
document.getElementById("Loadingbar-2-1").setAttribute("style","width:100%");
document.getElementById("Loadingbar-2-2").setAttribute("style","animation-name:loadingbar;animation-duration:10s;animation-timing-function:linear;");
document.getElementById("Loadingbar-2-3").setAttribute("style","width:0%");
document.getElementById("Loadingbar-2-4").setAttribute("style","width:0%");
document.getElementById("Loadingbar-2-5").setAttribute("style","width:0%");
document.getElementById("Loadingbar-2-6").setAttribute("style","width:0%");
} else if (location.hash === '#page2/2') {
document.getElementById("Loadingbar-2-1").setAttribute("style","width:100%");
document.getElementById("Loadingbar-2-2").setAttribute("style","width:100%");
document.getElementById("Loadingbar-2-3").setAttribute("style","animation-name:loadingbar;animation-duration:10s;animation-timing-function:linear;");
document.getElementById("Loadingbar-2-4").setAttribute("style","width:0%");
document.getElementById("Loadingbar-2-5").setAttribute("style","width:0%");
document.getElementById("Loadingbar-2-6").setAttribute("style","width:0%");
} else if (location.hash === '#page2/3') {
document.getElementById("Loadingbar-2-1").setAttribute("style","width:100%");
document.getElementById("Loadingbar-2-2").setAttribute("style","width:100%");
document.getElementById("Loadingbar-2-3").setAttribute("style","width:100%");
document.getElementById("Loadingbar-2-4").setAttribute("style","animation-name:loadingbar;animation-duration:10s;animation-timing-function:linear;");
document.getElementById("Loadingbar-2-5").setAttribute("style","width:0%");
document.getElementById("Loadingbar-2-6").setAttribute("style","width:0%");
} else if (location.hash === '#page2/4') {
document.getElementById("Loadingbar-2-1").setAttribute("style","width:100%");
document.getElementById("Loadingbar-2-2").setAttribute("style","width:100%");
document.getElementById("Loadingbar-2-3").setAttribute("style","width:100%");
document.getElementById("Loadingbar-2-4").setAttribute("style","width:100%");
document.getElementById("Loadingbar-2-5").setAttribute("style","animation-name:loadingbar;animation-duration:10s;animation-timing-function:linear;");
document.getElementById("Loadingbar-2-6").setAttribute("style","width:0%");
} else if (location.hash === '#page2/5') {
document.getElementById("Loadingbar-2-1").setAttribute("style","width:100%");
document.getElementById("Loadingbar-2-2").setAttribute("style","width:100%");
document.getElementById("Loadingbar-2-3").setAttribute("style","width:100%");
document.getElementById("Loadingbar-2-4").setAttribute("style","width:100%");
document.getElementById("Loadingbar-2-5").setAttribute("style","width:100%");
document.getElementById("Loadingbar-2-6").setAttribute("style","animation-name:loadingbar;animation-duration:10s;animation-timing-function:linear;");
}
}
window.onload = locationHashChanged;
window.onhashchange = locationHashChanged;
.loading-bars-container {
position: absolute;
left: 48px;
right: 48px;
bottom: 0.5em;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
}
.storyindicator {
position: relative;
z-index: 1000;
overflow: hidden;
width: 20%;
height: 4px;
margin-right: 0.25em;
margin-left: 0.25em;
border-radius: 4px;
background-color: #000;
}
.loadingbar-fill {
position: absolute;
left: 0;
top: 0;
bottom: 0;
background-color: grey;
}
<div class="loading-bars-container">
<div class="storyindicator">
<div id="Loadingbar-2-1" class="loadingbar-fill" style="width:100%"></div>
</div>
<div class="storyindicator">
<div id="Loadingbar-2-2" class="loadingbar-fill" style="width:100%"></div> </div>
<div class="storyindicator">
<div id="Loadingbar-2-3" class="loadingbar-fill" style="width:100%"></div> </div>
<div class="storyindicator">
<div id="Loadingbar-2-4" class="loadingbar-fill" style="animation-name:loadingbar;animation-duration:10s;animation-timing-function:linear;"></div> </div>
<div class="storyindicator">
<div id="Loadingbar-2-5" class="loadingbar-fill" style="width:0%"></div> </div>
<div class="storyindicator">
<div id="Loadingbar-2-6" class="loadingbar-fill" style="width:0%"></div> </div>
</div>
If you want the code to be shorter (sometimes it's totally OK for code to be verbose), I would propose this:
const animationStr = "animation-name:loadingbar;animation-duration:10s;animation-timing-function:linear;";
const barsCnt = 6;
function locationHashChanged() {
const num = location.hash.match(/^#page2(?:\/(\d))?$/)[1] || 0;
for (let i = 0; i < barsCnt; i++) {
const style = i < num
? "width:100%"
: i > num
? "width:0%"
: animationStr;
document.getElementById("Loadingbar-2-" + (i + 1)).setAttribute("style", style);
}
}
window.onload = locationHashChanged;
window.onhashchange = locationHashChanged;
I tested it, but there still may be some flaws, please check it.

Vanila JS counter

Trying to get all four counters to finish at the same time.
e.g.
Counter four should stay at zero until counter three reaches value of 14, then switch to 1.
Counter one should increment by following counter two and three.
https://jsfiddle.net/IhaveVoicesinMyhead/0j9q1b85/2/#&togetherjs=f3xchiJM9f
const counter = document.querySelectorAll('.counter');
const speed = 200;
counter.forEach(counter => {
const updateCount = () => {
const target = +counter.getAttribute('data-target');
const count = +counter.innerText;
const increment = target / speed;
if (count < target) {
counter.innerText = Math.ceil(count + increment);
setTimeout(updateCount, 80);
} else {
count.innerText = target;
}
}
updateCount();
});
.counters {
margin-top: 2em;
}
.counters .container-max-width {
display: flex;
position: relative;
flex-flow: row nowrap;
justify-content: center;
align-items: stretch;
background-color: #fff;
font-size: 1rem;
text-transform: uppercase;
}
.counters .container-max-width .counter {
font-size: 3.25em;
}
.counters .container-max-width span {
color: #848484;
padding: 0;
}
.counters .container-inner-width {
display: grid;
grid-gap: 200px;
grid-template-columns: repeat(4, 1fr);
padding: 85px 0 85px 0;
text-align: center;
}
<section class="counters">
<div class="container-max-width">
<div class="container-inner-width">
<div>
<div class="counter counter-one" data-target="4">0</div>
<span>counter one</span>
</div>
<div>
<div class="counter counter-two" data-target="10">0</div>
<span>counter two</span>
</div>
<div>
<div class="counter counter-three" data-target="15">0</div>
<span>counter three</span>
</div>
<div>
<div class="counter counter-four" data-target="1">0</div>
<span>counter four</span>
</div>
</div>
</div>
</section>
Here's a simple example of how you can create multiple timers that all end at the same time. I separated the logic behind it (countUp()) from the view (createTimer()), so you should be able to adapt the countUp() function to whatever needs you have. Just give it your desired final value, how long you want it to execute (in ms), and what you want it to do at each step.
const counter1 = document.getElementById('counter1')
const counter2 = document.getElementById('counter1')
function countUp({ to, onStep, duration, _currentValue = 0 }) {
onStep(_currentValue)
if (_currentValue === to) return
setTimeout(() => {
countUp({ to, onStep,duration, _currentValue: _currentValue + 1 })
}, duration / to)
}
function createTimer(to) {
const timerEl = document.createElement('div')
document.body.appendChild(timerEl)
const onStep = currentValue => {
timerEl.innerText = currentValue
}
countUp({ to, duration: 3000, onStep })
}
createTimer(1)
createTimer(10)
createTimer(20)
Note that this doesn't account for setTimeout() drift (setTimeout doesn't always execute the callback as soon as the you asked it to), so you shouldn't use this solution for longer-lasting or very precise timers. You can add some more math to it if you want to account for drift.

How to remove an appendChild element in JS

So basically, I want to remove the appendChild element once it has been clicked. I tried to use this.remove(), but it does not work. I manually added some divs with h2 inside of it. When I clicked the div then, my code worked. When I clicked it, it did go away.
Code snippet
var div_children = document.getElementById("append-div").children;
var length = div_children.length;
for (var x = 0; x < length; x++){
div_children[x].addEventListener("click", function(){
this.remove();
});
}
function myfunction(){
var new_div = document.createElement("DIV");
new_div.innerHTML = "<h2>New div</h2>";
document.getElementById("append-div").appendChild(new_div);
}
#append-div{
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
#append-div div{
background-color: lightblue;
display: flex;
flex-direction: row;
border-radius: 45px;
border: 1px solid black;
width:fit-content;
height:fit-content;
}
#append-div div h2{
margin:20px;
}
<!DOCTYPE html>
<html>
<head>
<link = rel="stylesheet" type = "text/css" href="styles.css">
<title>Test</title>
</head>
<body>
<button class = "click-me" onclick = "myfunction()">Click Me!</button>
<div id = "append-div"></div>
</body>
</html>
The issue you were having before in the removal is that the first part of the code runs without any children and it never runs again even after you create new ones.
There's no need to loop through the children to add the event listener.
Just add it to the child right after you create the element.
function myfunction() {
var new_div = document.createElement("DIV");
new_div.innerHTML = "<h2>New div</h2>";
new_div.addEventListener("click", function() {
this.remove();
});
document.getElementById("append-div").appendChild(new_div);
}
#append-div {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
#append-div div {
background-color: lightblue;
display: flex;
flex-direction: row;
border-radius: 45px;
border: 1px solid black;
width: fit-content;
height: fit-content;
}
#append-div div h2 {
margin: 20px;
}
<button class="click-me" onclick="myfunction()">Click Me!</button>
<div id="append-div"></div>
you could add the listener event when is created the element, as below:
function myfunction() {
var new_div = document.createElement("DIV");
new_div.innerHTML = "<h2>New div</h2>";
new_div.onclick = function () {
this.remove()
}
document.getElementById("append-div").appendChild(new_div);
}
<button class = "click-me" onclick = "myfunction()">Click Me!</button>
<div id = "append-div"></div>
Try doing this
document.getElementById("append-div").outerHTML = "";
It has support on cross browsers & IE 11+
https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML

Javascript: word game, loop through array

I'm new to Javascript and I'm struggling to make something work.
I have a basic word game that is supposed to replace one character and the user has to guess that one. It works well (apart from obvious design errors, never mind these) if I specify ONE word only. However, I've spent all day to work through an array of words.
The user should see the (gapped) word, enter the missing character and should then be presented with the next gapped word until the array is finished.
This is the (fairly ok) code for the single word:
<html>
<body>
<h1> Guess the word! :) </h1>
<br><br>
<div id="paste_game" style="left: 30%; top: 25%; border: 3px solid #73AD21; font-size: 350%; font-weight: bold; display: flex; align-items: center; justify-content: center">
</div>
<br>
<br> feedback:
<div id="feedback" style="top: 35%; font-size: 150%; font-weight: bold; background-color:powderblue; display: flex; align-items: center; justify-content: center">
... feedback ...
</div>
<br> number of attempts:
<div id="attempts" style="top: 35%; font-size: 150%; font-weight: bold; background-color:powderblue; display: flex; align-items: center; justify-content: center">
... attempts ...
</div>
<div id="guess_area" style="height: 10em; display: flex; align-items: center; justify-content: center">
<h2>ENTER THE MISSING CHARACTER: </h2><br>
<input type="text" id="guess"><br>
<button onClick="guessChar()">GUESS!</button>
</div>
<script>
var testword = "straightforward";
var current_blank = getBlank(testword);
document.getElementById("paste_game").innerHTML = replaceChar(testword);
var count = 0;
function getBlank(word) {
var numchars = word.length;
var randomchar = Math.floor((Math.random() * numchars) + 1);
var chosenchar = word.charAt(randomchar);
return chosenchar;
}
function replaceChar(word) {
var newWord = word.replace(current_blank, "[ ]");
return newWord;
}
function guessChar() {
var char = document.getElementById("guess").value;
if (char == current_blank) {
document.getElementById("feedback").innerHTML = "Correct, the missing blank is >>" + char +"<<";
document.getElementById("paste_game").innerHTML = testword;
}
else if (char != current_blank) {
if (count < 2) {
document.getElementById("feedback").innerHTML = "Sorry, try again!";
// reset only works with forms, form breaks code
//document.getElementById("form").reset();
count++;
document.getElementById("attempts").innerHTML = count;
}
else {
document.getElementById("feedback").innerHTML = "Sorry, you've tried too often!";
count++;
document.getElementById("attempts").innerHTML = count;
}
}
else {
alert("ERROR");
}
}
</script>
</body>
</html>
This is the messed up code with an array (I stopped working on it in-between)
<html>
<body>
<h1> Guess the word! :) </h1>
<div id="start_div" style="height: 40px; display: flex; align-items: center; justify-content: center">
<button id="start_button" onClick="startGame()">START GAME!</button>
</div>
<div id="next_div" style="height: 60px; display: flex; align-items: center; justify-content: center">
<button id="start_button" onClick="nextWord()">NEXT WORD!</button>
</div>
<div id="paste_game" style="left: 30%; top: 25%; border: 3px solid #73AD21; font-size: 350%; font-weight: bold; display: flex; align-items: center; justify-content: center">
</div>
<br>
<br> feedback:
<div id="feedback" style="top: 35%; font-size: 150%; font-weight: bold; background-color:powderblue; display: flex; align-items: center; justify-content: center">
... feedback ...
</div>
<br> number of attempts:
<div id="attempts" style="top: 35%; font-size: 150%; font-weight: bold; background-color:powderblue; display: flex; align-items: center; justify-content: center">
... attempts ...
</div>
<div id="guess_area" style="height: 10em; display: flex; align-items: center; justify-content: center">
<h2>ENTER THE MISSING CHARACTER: </h2><br>
<input type="text" id="guess"><br>
<button onClick="guessChar()">GUESS!</button>
</div>
<script>
// define variables
//var guess_word = "straightforward";
var guessword_array = ['handy', 'lovely', 'annoying', 'superb'];
var global_chosen_char;
var count = 0;
var game_started = false;
var game_word;
var guessed_char;
var current_word;
var loopy;
/**
for (var i = 0; i < guessword_array.length; i++) {
array_current_position = guessword_array[i];
console.log("Array currently at "+guessword_array[i]+", position: "+i);
document.getElementById("paste_game").innerHTML = replaceChar(guessword_array[i]);
}
**/
/**
var tempword = replaceChar(guessword_array[i]);
document.getElementById("paste_game").innerHTML = tempword;
**/
// FUNCTION: get random character from word (=1) and replace by [] (=2)
function replaceChar(word) {
//1
var numchars = word.length;
var randompos = Math.floor((Math.random() * numchars) + 1);
if (randompos == numchars) {
randompos = 0;
}
//2
var chosenchar = word.charAt(randompos);
var newword = word.replace(chosenchar, "[]");
global_chosen_char = chosenchar;
global_newword = newword;
return newword;
}
// FUNCTION: first time the game is started
function startGame() {
if (guessed_char == undefined) {
alert("Thank you for playing!\nPlease start guessing and enter your guess below!");
current_word = guessword_array[0];
game_word = replaceChar(guessword_array[0]);
document.getElementById("paste_game").innerHTML = game_word;
console.log(game_word);
game_started = true;
return;
}
else {
alert("Sorry, an error has occurred!");
}
}
function nextWord() {
for (var i = 1; i < guessword_array.length; i++) {
game_word = replaceChar(guessword_array[i]);
console.log("nextword: "+game_word);
wait(100);
document.getElementById("paste_game").innerHTML = game_word;
guessChar();
}
}
function guessChar() {
if (game_started != true) {
startGame();
}
else if (game_started == true && guessed_char != "") {
guessed_char = document.getElementById("guess").value;
if (guessed_char == global_chosen_char) {
document.getElementById("feedback").innerHTML = "Correct! ".fontcolor("green")+"The word is: "+""+current_word.fontcolor("red").fontsize(20);
guessed_char = "";
console.log("Guessed char:" +guessed_char);
console.log("guessed righ");
}
else {
if (count < 2) {
document.getElementById("feedback").innerHTML = "Sorry, try again!".fontcolor("red");
count++;
document.getElementById("attempts").innerHTML = count;
}
else {
document.getElementById("feedback").innerHTML = "Sorry, you've tried too often!";
count++;
document.getElementById("attempts").innerHTML = count;
console.log("guessed wrong");
guessed_char = "";
}
}
}
else if (game_started == true && guessed_char == "") {
alert("Guess char is empty");
}
}
</script>
Please help me, I've already lost so much time on this - thank you so much!!!
P.S.: I know that there are some other issues with my code, but please focus on the array thing for now - thank you ever so much!
I modified it to use a list, also it uses an interval to switch to the next word.
The code could obviously use optimization, but I'm not going to go that far.
<html>
<body>
<h1> Guess the word! :) </h1>
<br><br>
<div id="paste_game" style="left: 30%; top: 25%; border: 3px solid #73AD21; font-size: 350%; font-weight: bold; display: flex; align-items: center; justify-content: center">
</div>
<br>
<br> feedback:
<div id="feedback" style="top: 35%; font-size: 150%; font-weight: bold; background-color:powderblue; display: flex; align-items: center; justify-content: center">
... feedback ...
</div>
<br> number of attempts:
<div id="attempts" style="top: 35%; font-size: 150%; font-weight: bold; background-color:powderblue; display: flex; align-items: center; justify-content: center">
... attempts ...
</div>
<div id="guess_area" style="height: 10em; display: flex; align-items: center; justify-content: center">
<h2>ENTER THE MISSING CHARACTER: </h2><br>
<input type="text" id="guess"><br>
<button onClick="guessChar()">GUESS!</button>
</div>
<script>
var words = ["straightforward", "testing"];
var currentWord = 0;
var current_blank = getBlank(words[currentWord]);
document.getElementById("paste_game").innerHTML = replaceChar(words[currentWord]);
var count = 0;
function getBlank(word) {
var numchars = word.length;
var randomchar = Math.floor((Math.random() * numchars) + 1);
var chosenchar = word.charAt(randomchar);
return chosenchar;
}
function replaceChar(word) {
var newWord = word.replace(current_blank, "[ ]");
return newWord;
}
function guessChar() {
var char = document.getElementById("guess").value;
if (char == current_blank) {
document.getElementById("feedback").innerHTML = "Correct, the missing blank is >>" + char +"<<";
document.getElementById("paste_game").innerHTML = words[currentWord];
setTimeout(function(){
currentWord++;
current_blank = getBlank(words[currentWord]);
document.getElementById("paste_game").innerHTML = replaceChar(words[currentWord]);
}, 2000);
}
else if (char != current_blank) {
if (count < 2) {
document.getElementById("feedback").innerHTML = "Sorry, try again!";
// reset only works with forms, form breaks code
//document.getElementById("form").reset();
count++;
document.getElementById("attempts").innerHTML = count;
}
else {
document.getElementById("feedback").innerHTML = "Sorry, you've tried too often!";
count++;
document.getElementById("attempts").innerHTML = count;
}
}
else {
alert("ERROR");
}
}
</script>
</body>
</html>
You iterate over your array once and start all games at the same time. You may wait for the user to finish:
var words=["hi","test","abc"];
var current=0;
function next_word(){
current++;
var word=words[current];
....
}

Categories

Resources