for learning purpose i'm trying to move an <p> tag innerHTML by one char every second. I managed to move it, but i can't set that delay between moves. It just moves it instantly.
function shiftAChar(str) {
charToShift = str[str.length - 1];
return charToShift + "" + str.substring(0, str.length - 1);
console.log(str);
setTimeout(shiftAChar, 1000);
}
function shiftString(str) {
for (i = 0; i <= 40; i++) {
console.log(str);
str = shiftAChar(str);
document.getElementById("divSecundar").getElementsByTagName("p")[0].innerHTML = str;
}
}
window.onload = function () {
document.getElementById("runEffect").addEventListener("click", function () {
str = document.getElementById("divSecundar").getElementsByTagName("p")[0].innerHTML;
console.log(str);
shiftString(str);
});
document.getElementById("stopEffect").addEventListener("click", function () { run = false; })
}
HTML :
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Nu are</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="evenimente.js"></script>
</head>
<body>
<h2>Header Two</h2>
<div>
<div id="divSecundar">
<p>Aceasta este primul paragraf</p>
<p>Aceasta este al treilea</p>
</div>
<p>Aceasta este cel de-al doilea paragraf</p>
</div>
<input type="text" value="asdf" id="textBoxInput" />
<input type="button" value="Run effect" id="runEffect" />
<input type="button" value="Stop effect" id="stopEffect" />
<input type="button" value="Animatie" id="animatie" />
<br />
<br />
<input type="button" value="Click" id="btnClick" />
<input type="button" value="Click" id="btnClickRemove" />
</body>
</html>
I don't want to use jQuery. Can it be achived using only pure javascript code?
My solution :
function shiftAChar(str) {
charToShift = str[str.length - 1];
return charToShift + "" + str.substring(0, str.length - 1);
}
function shiftString(str, counter) {
if (counter <= 5) {
str = shiftAChar(str);
document.getElementById("divSecundar").getElementsByTagName("p")[0].innerHTML = str;
setTimeout(function () {
shiftString(str, ++counter);
}, 1000);
}
}
window.onload = function () {
document.getElementById("runEffect").addEventListener("click", function () {
str = document.getElementById("divSecundar").getElementsByTagName("p")[0].innerHTML;
console.log(str);
shiftString(str, 0);
});
}
I think you're close. Specifically you don't want to do this in a loop per se, but instead you'd pseudo-recursively call the function using setTimeout (as you're attempting). I think the problem you're finding is that the loop and the setTimeout attempt are both trying to do the same thing, and the loop is simply doing it faster.
For the sake of simplicity, let's assume the logic to move a character from one element to the other is encapsulated in the function moveOneCharacter(). (This would include the actual UI updating.) Since you already know how to make that work, this answer can just focus on the timing problem.
Structurally, the overall process might look something like this:
function shiftTheNextCharacter() {
moveOneCharacter();
if (charactersRemain()) {
setTimeout(shiftTheNextCharacter, 1000);
}
}
No loop needed. Once you call this shiftTheNextCharacter() function, it will move the first character. If there are any more characters (you'd have to write that function too, of course), it schedules itself to shift the next one.
This assumes there's always at least one character to start, of course. You can modify the logic accordingly. But the point of the structure is that a loop will do things instantly, whereas scheduling operations to happen at a later time gives you control over that timing.
Related
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function wordRand(){
var words = ["DOG", "CAT", "MOUSE", "GIRAFFE"];
return words[Math.floor(Math.random()*words.length)];
}
function replaceAt(str,index,chr){
if(index > str.length-1)
return str;
return str.substring(0,index) + chr + str.substring(index+1);
}
function wordSet(){
var i, word=wordRand();
document.getElementById("text").innerHTML += word.charAt(0); //places the first letter.
for(i=1;i<word.length;i++)
document.getElementById("text").innerHTML += '-';
document.getElementById("checkword").innerHTML = word; //my current solution.
}
function check(letter){
//variable "word" receives the string from the paragraph with ID "checkword".
var exists=false, i, word=document.getElementById("checkword").innerHTML, correct;
for(i=1;i<word.length;i++){
if(word.charAt(i)==letter){
exists=true;
correct = document.getElementById("text").innerHTML;
correct = replaceAt(correct, i, letter);
document.getElementById("text").innerHTML = correct;
}
}
if(exists==false)
document.getElementById("verify").innerHTML += "No ";
}
</script>
</head>
<body onload="wordSet();">
<p id="text"></p>
<p id="verify">Mistakes: </p>
<div id="keyboard">
<button onclick="check('Q');">Q</button>
<button onclick="check('W');">W</button>
<button onclick="check('E');">E</button>
<button onclick="check('R');">R</button>
<button onclick="check('T');">T</button>
<button onclick="check('Y');">Y</button>
<button onclick="check('U');">U</button>
<button onclick="check('I');">I</button>
<button onclick="check('O');">O</button>
<button onclick="check('P');">P</button>
<button onclick="check('A');">A</button>
<button onclick="check('S');">S</button>
<button onclick="check('D');">D</button>
<button onclick="check('F');">F</button>
<button onclick="check('G');">G</button>
<button onclick="check('H');">H</button>
<button onclick="check('J');">J</button>
<button onclick="check('K');">K</button>
<button onclick="check('L');">L</button>
<button onclick="check('Z');">Z</button>
<button onclick="check('X');">X</button>
<button onclick="check('C');">C</button>
<button onclick="check('V');">V</button>
<button onclick="check('B');">B</button>
<button onclick="check('N');">N</button>
<button onclick="check('M');">M</button>
</div>
<!--word saver, for functions (which I want to get rid of)-->
<p id="checkword" style="visibility:hidden;"></p>
</body>
</html>
I'll start off by saying that I apologize if this question is extremely basic and probably has been already answered, but I can't seem to find a proper response to it:
I am in the process of creating the code for an HTML page, with a bit of JavaScript included. However, I have a problem with a variable: my only way to pass it is by first inserting its content in an element inside the body, and then copying it in the other function's variable, as follows:
function parolaSet(){
var i;
var parola=parolaRand();
document.getElementById("testo").innerHTML += parola.charAt(0);
for(i=1;i<parola.length;i++)
document.getElementById("testo").innerHTML += '-';
document.getElementById("verifica").innerHTML = parola;
}
function check(lettera){
var present=false, i, parola=document.getElementById("verifica").innerHTML, giusto;}
Where "verifica" is a "p" element. I did think about using the simple "return parola;" command in the parolaSet function, however, this function sets a word in the HTML page that can't be changed by any means, as it's a requirement for my project to work. Making the call everytime I need a returned value from it would reset the word and mess everything up. So, is there another way to share this value without having to use up space in the page, repeating the parolaSet function's code and just by using common JavaScript functions and commands? If JavaScript on its own is not enough for this, I would like to acknowledge other options anyway.
P.S. Creating a global variable doesn't seem to work, as the value is returned as an "Object object" when used in the page or inside of functions.
EDIT: Due to absolutely reasonable suggestions, I added a snippet of my page. It's all just a basic hangman game, the words in the original code are much more, but this is the most minimal I could make it.
Try a hidden input field to pass the value along with every web request.
Somthing like:
<input hidden id="MyValueToPass" value="parola">
Have a look at this
I delegate the click and have word as a global
let word;
function wordRand() {
var words = ["DOG", "CAT", "MOUSE", "GIRAFFE"];
return words[Math.floor(Math.random() * words.length)];
}
function replaceAt(str, index, chr) {
if (index > str.length - 1)
return str;
return str.substring(0, index) + chr + str.substring(index + 1);
}
function wordSet() {
word = wordRand(); // set the global word
document.getElementById("text").innerHTML = word.charAt(0) + word.slice(1).replace(/./g,"-")
}
function check(letter) {
//variable "word" receives the string from the paragraph with ID "checkword".
var exists = false, i, correct;
for (i = 1; i < word.length; i++) {
if (word.charAt(i) == letter) {
exists = true;
correct = document.getElementById("text").innerHTML;
correct = replaceAt(correct, i, letter);
document.getElementById("text").innerHTML = correct;
}
}
if (exists == false)
document.getElementById("verify").innerHTML += "No ";
}
window.addEventListener("load", function() {
document.getElementById("keyboard").addEventListener("click", function(e) {
const tgt = e.target.closest("button");
if (tgt)
check(tgt.textContent)
})
wordSet();
});
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p id="text"></p>
<p id="verify">Mistakes: </p>
<div id="keyboard">
<button>Q</button>
<button>W</button>
<button>E</button>
<button>R</button>
<button>T</button>
<button>Y</button>
<button>U</button>
<button>I</button>
<button>O</button>
<button>P</button>
<button>A</button>
<button>S</button>
<button>D</button>
<button>F</button>
<button>G</button>
<button>H</button>
<button>J</button>
<button>K</button>
<button>L</button>
<button>Z</button>
<button>X</button>
<button>C</button>
<button>V</button>
<button>B</button>
<button>N</button>
<button>M</button>
</div>
<!--word saver, for functions (which I want to get rid of)-->
<p id="checkword" style="visibility:hidden;"></p>
</body>
</html>
I have been googling for this, but I found the solutions difficult, so I came here to ask how can I do it.
I'm doing an incremental game and I want to start with the basics: mining gold and buying. Now I'm moving to my next step at developing this game and I really need help
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Gold Miner</title>
</head>
<body>
<h2 id="goldMined">0 Gold Mined</h2>
<br />
<br />
<button onclick="buyGoldPerClick()" id="perClickUpgrade">Get More Money. Cost: 10 Gold</button>
<br />
<br />
<button onclick="Reset()">Reset Game</button>
<script src="main.js" charset="utf-8" type="text/javascript"></script>
</body>
</html>
JavaScript
var gameData = {
gold: 0,
goldPerClick: 0.01,
goldPerClickCost: 10,
tickReduction: 1000,
tickReductionCost: 100
}
function mineGold() {
gameData.gold += gameData.goldPerClick
document.getElementById("goldMined").innerHTML = gameData.gold.toFixed(0).toLocaleString('en') + " Gold Mined"
document.getElementById("perClickUpgrade").innerHTML = "Buy Pickaxe. Cost: " + gameData.goldPerClickCost.toFixed(0).toLocaleString('en') + " Gold"
}
function buyGoldPerClick() {
if (gameData.gold >= gameData.goldPerClickCost) {
gameData.gold -= gameData.goldPerClickCost
gameData.goldPerClick *= 2
gameData.goldPerClickCost *= 3
document.getElementById("goldMined").innerHTML = gameData.gold.toLocaleString('en') + " Gold Mined"
document.getElementById("perClickUpgrade").innerHTML = "Buy Pickaxe. Cost: " + gameData.goldPerClickCost.toLocaleString('en') + " Gold"
}
}
function Reset() {
gameData.gold = 0
gameData.goldPerClick = 0.01
gameData.goldPerClickCost = 10
}
var mainGameLoop = window.setInterval(function () {
mineGold()
}, 10)
var saveGameLoop = window.setInterval(function () {
localStorage.setItem("goldMinerSave", JSON.stringify(gameData))
}, 1)
var savegame = JSON.parse(localStorage.getItem("goldMinerSave"))
if (savegame !== null) {
gameData = savegame
}
Any help supports a lot for me, as I am a JavaScript and HTML programming beginner! Thanks for reading my post!
You can use the NumberFormat() function from the Intl API available in Javascript. (click on the link for documentation).
The first parameter to the Intl.NumberFormat() function is the locale, if you want it to be generic, just pass in 'en-US'. But if you can also pass in navigator.language if you want to just take the language from the browser.
The second parameter to this function is an options object. Now, within this options object, I have passed in the maximumSignificantDigits and set it to 3. You can change that as per your requirements. You also have other options you can pass in, just check out the link I provided above.
Finally, you will be calling the format() function and passing in your gold as the parameter, and this will overall return you the formatted value with 3 maximum significant digits.
const gold = 1000000;
const formattedGold = Intl.NumberFormat('en-US', { maximumSignificantDigits: 3 }).format(gold);
//Printing output to console
console.log(formattedGold);
I was working on this code, and I got stuck here as a JS rookie and need help. How would you rewrite this block, using % operator, instead of if statement?
<!DOCTYPE html>
<html>
<head>
<script>
window.onload=function(){
var letters = ["A","B","C"]
var counter = 0;
var timer=setInterval(
function(){
counter= counter+1;
if (counter==letters.length){
counter=0;
}
document.getElementById("demo").value=letters[counter];
},1000)
}
</script>
</head>
<body>
<input type="text" id="demo" value="A">
</body>
</html>
Simple use it after doing your add operation to return the remains after division (or modulus):
const letters = ["A","B","C"]
let counter = 0;
setInterval(function(){
counter = (counter+1) % letters.length;
document.getElementById("demo").value = letters[counter];
}, 1000);
<input type="text" id="demo" value="A" />
Couple of other tips, use const if the values don't change (like your array), and let if it can definitely change. Also, you don't need to store your interval here as you never cancel it, so no need for const timer in that case. Simplifies the code a lot!
I am trying to make new lines (in this single line of text) as you can see in my index.html file, but it is not working, any help? (\n is where the new line should start, has not worked either.
index.html:
<html>
<head>
<title>test</title>
</head>
<body bgcolor="black">
<font color="green">
<p id="terminal"></p>
<script>
var text = "this is a test\nthis should be on the next line";
var count = 0;
var speed = 50;
function Type() {
if(count < text.length) {
document.getElementById("terminal").innerHTML += text.charAt(count);
count ++;
setTimeout(Type, speed);
}
}
Type();
</script>
If you don't want to use <br /> you can easily use the <pre> tag. It's actually easier to use <pre> since you don't have to insert the <br /> at the right location in the DOM.
Taken from the docs.
The HTML pre element represents preformatted text which is to be presented exactly as written in the HTML file.
var text = "this is a test\nthis should be on the next line";
var count = 0;
var speed = 50;
function Type() {
if(count < text.length) {
document.getElementById("terminal").innerHTML += text.charAt(count);
count ++;
setTimeout(Type, speed);
}
}
Type();
<html>
<head>
<title>test</title>
</head>
<body bgcolor="black">
<font color="green" />
<pre id="terminal"></pre>
</body>
</html>
Substitute the new line \n with break <br>
I am new to programming and am currently stuck on the Ping-Pong aka FizzBuzz problem. (Make a webpage where the user is prompted to enter a number and every number up to that number is displayed. However, for multiples of three, the page prints "ping," for multiples of five, the page prints "pong," and for multiples of both three and five (15), the page prints "ping-pong.")
I've checked out other solutions on here (such as this one) and they've been helpful for understanding how to solve it. And I hope my javascript reflects that.
My problem is I'm stuck trying to take the input number from the form I have on the webpage and run it through the javascript, if that makes sense.
I'm pretty sure that part of my javascript is just a conglomeration of throwing everything I had at it, which is not the best. Could anyone check out my code and see what I'm doing wrong here?
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-1.11.2.js"></script>
<script src="js/scripts.js"></script>
<title>Ping-Pong Test</title>
</head>
<body>
<div class="container">
<h1>Ping Pong Test</h1>
<p>Let's play the Ping-Pong game. The Ping-Pong game is a simple test that involves loops, conditionals, and variables. Enter your number below to start</p>
<form id="start-form">
<label for="input-number">Your number:</label>
<input id="input-number" type="number">
<button type="submit" class="btn">Calculate</button>
</form>
<div id="end-number">
<ul id="results"></ul>
</div>
</div>
</body>
</html>
And my javascript:
$(document).ready(function () {
$("#start-form").submit(function(event) {
var a = document.getElementById("#input-number");
var num = a.elements[0].value;
var listItems = "";
var i;
for (var i = 1; i <= num; i++) {
if (i % 15 === 0) {
console.log("Ping-Pong");
}
else if (i % 3 === 0) {
console.log("Ping");
}
else if (i % 5 === 0) {
console.log("Pong");
}
else{
console.log(i);
};
event.preventDefault();
};
});
Again, I'm new, so if anyone could break it down step by step, I'd really appreciate it. Thanks.
It is not right:
var a = document.getElementById("#input-number");
Must be one of the below lines:
var a = document.getElementById("input-number");
// Or
var a = $("#input-number").get(0);
// Or
var a = $("#input-number")[0];
But it will not solve your problem. Looking deep into your code. I guess you need to have a form an then get the first element:
var a = document.getElementById("start-form");
var num = a.elements[0].value;
But you can simplify even more. Why not just do it:
// remove the a variable
var num = $("#input-number").val(); // get the input-number value
Based on your code I think you just need some syntax cleaned up in order for jquery to use the value from your form.
I took your code, stripped it down for clarity and made a fiddle out of it.
Here is the link:
http://jsfiddle.net/zwa5s3ao/3/
$(document).ready(function(){
$("form").submit(function(event){
var num = $('#input-number').val()
for (var i = 1; i <= num; i++) {
if (i % 15 === 0) {
$('#list').append('<li>'+"Ping-Pong"+'</li>');}
else if (i % 3 === 0) {
$('#list').append('<li>'+"Ping"+'</li>');}
else if (i % 5 === 0) {
$('#list').append('<li>'+"Pong"+'</li>');}
else{
$('#list').append('<li>'+i+'</li>');}
};
event.preventDefault();
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>Ping-Pong Test</title>
<body>
<form>
Your number:
<input type="number" name="input-number" id="input-number">
<input type="submit" value="Calculate">
</form>
<ul id="list"></ul>
</body>
Hope this helps!