I'm learning web development and I'm trying to do the simplest things in javascript to learn how it works. I have this problem, the h1 text is not changing on the page but when I open the console it prints the changed value each time , here's the code (Hint, the sleep() function is from the internet and I don't know anything yet about it but it works):
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
<script>
let counter = 0;
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
function change(){
while(true)
{
document.querySelector("#show").innerText = counter;
counter++
console.log(document.querySelector("#show").innerText);
sleep(1000);
}
}
</script>
</head>
<body>
<button onclick="change()" id="button" >COUNT</button>
<h1 id="show">0</h1>
</body>
</html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
<script>
function change() {
let counter = 0;
setInterval(() => {
document.querySelector("#show").innerText = counter;
counter++;
}, 1000);
}
</script>
</head>
<body>
<button onclick="change()" id="button" >COUNT</button>
<h1 id="show">0</h1>
</body>
</html>
try changing your change function using setInterval. you can find how to use set interval using https://www.w3schools.com/jsref/met_win_setinterval.asp
Related
I'm trying to make a list of buttons and their names into an array in javascript?
I heave searched the internet for help but not found anything so far. The div with the name "apps" is where I'm trying to grab from and the array inside of the if statement in the javascript code is what I'm to to replace with the array.
HTML code:
<!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" type="text/css" href="clicker.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<title>Vairoon's clicker</title>
</head>
<body>
<button onclick="smnPlayer()">Get new player</button>
<p>Players per click: <span id="PPC">1</span></p>
<p>Players: <span id="players">0</span></p>
<p>New players per second: <span id="PPS">0</span></p>
<div class="upgrade">
<p>Upgrade your clicker game: <span id="upgCost">400</span></p>
<button id="upgrade">Upgrade clicker</button>
</div>
<div id="apps" name="apps"> <!-- The div I'm trying to grab from-->
<button>Obj1</button>
<button>Obj2</button>
</div>
<script ="clicker.js"></script>
</body>
</html>
Javascript code:
var players=0;
var PPS=0;
var PPC=1;
var upgradeCost=400;
var apps = ["New buildings","More upgrades","Adverts","More minigames"]
var basecosts = [0,20,100,1500,15000]
function getEl(elID) {
return document.getElementById(elID);
}
function smnPlayer() {
players+=PPC;
document.getElementById("players").innerHTML=players;
}
getEl("upgrade").onclick = function upgrade() {
if (players>=upgradeCost) {
players-=upgradeCost;
upgradeCost=upgradeCost*3;
PPC=Math.ceil(PPC*2);
PPS=PPS*2;
getEl("players").innerHTML=players;
getEl("upgCost").innerHTML=upgradeCost;
getEl("PPC").innerHTML=PPC;
getEl("PPS").innerHTML=PPS;
}
}
setInterval(() => {
if (players>=upgradeCost) {
getEl("upgrade").style.display="block";
} else {
getEl("upgrade").style.display="none";
}
for (let index = document.querySelectorAll('#apps').length; index < basecosts.length+1; index++) {
if (players>=basecosts[index]) {
if (array.includes(apps[index])){}else{ //the "array" is what to replace with the array
var button = document.createElement("BUTTON");
button.innerHTML = apps[index];
document.getElementById("apps").appendChild(button);
}
}
}
},10)
If you still don't understand what I'm trying to do, here's another explanation:
I want the code to go from
<div>
<button>Obj1</button>
<button>Obj2</button>
</div>
to
["Obj1","Obj2"]
Oh and a question if you can answer too, how do I add break line between the items I'm creating just with js?
For your simplified example:
myArray = Array.from(document.querySelectorAll("div button")).map(
function(b) {
return b.innerText;
}
);
console.log(myArray);
//add a line break:
document.querySelector("div").insertBefore(document.createElement("br"),document.querySelectorAll("div button")[1]);
<div>
<button>Obj1</button>
<button>Obj2</button>
</div>
I'm new to JavaScript and I've been trying to get the title text to switch between different texts for a day now. I've gathered some code snippets and put them together, so I'm not quite sure what's going on.
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
function switchingText(); {
document.getElementByID("title").innerHTML = "Text";
sleep(2000);
document.getElementByID("title").innerHTML = "Text2";
sleep(2000);
switchingText();
}
I would appreciate any help greatly.
This is a sample solution for your dilemma:
const title= document.getElementById("title");
const switchHeading = () => {
if (title.innerHTML== "Text"){
title.innerHTML = "Text2";
}else{
title.innerHTML = "Text";
}
}
setInterval(() => {
switchHeading()
}, 2000);
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<h1 id="title">Text</h1>
<script src="./script.js" async defer></script>
</body>
</html></html>
Helpful links:
W3Schools Set Interval
All you need to do is get the title element like you did but instead of changing the InnerHTML, change the value, like so:
document.getElementByID('title').value="Text"
Hope you found what you were looking for.
Instead of doing
document.getElementByID("title").innerHTML = "Text";
in the switching text function,
you need to do
document.title = 'your text'
I want to make a program which adds a textbox every time you click a button. Here's my code:
window.onload = function () { linelist = document.getElementById("linelist"); };
function AddLine() {
linelist.innerHTML += "<div class=\"normallink\"><input type=\"text\"><button class=\"dustbin\"><img src=\"dustbin.png\"></button></div><br />";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="linelist"></div><br />
<button id="addline" onclick="Addline();">+</button>
</body>
</html>
When I run it, it generates an error. Why is this occurring?
You have to define linelist outside the functions first with let or var:
let linelist = null;
window.onload = function () { linelist = document.getElementById("linelist"); };
function AddLine() {
linelist.innerHTML += "<div class=\"normallink\"><input type=\"text\"><button
class=\"dustbin\"><img src=\"dustbin.png\"></button></div><br />";
}
I'm trying to create a word game that will choose a random item from a list but some of the items have different weights so they show up less often. I want the function to be called once the user presses a HTML button. I have the code working fairly well right now (to the console). My question is how can I get the output from the function into the html web page. If anyone could help me with this, it would be a huge help.
Here's my code:
var item = {
'apple':10,
'banana':10,
'orange':10,
'grapes':1,
}
function testGame(input) {
var array = [];
for(var item in input) {
if(input.hasOwnProperty(item) ) {
for(var i=0; i<input[item]; i++ ) {
array.push(item);
}
}
}
return array[Math.floor(Math.random() * array.length)];
}
console.log(testGame(item));
I have some HTML code too, just don't know where or how to write the button code properly to produce the outcome I'm looking for.
Here's the HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Randomizer Game</title>
</head>
<body>
<h1>Game</h1>
<script src="index.js"></script>
<button onclick="testGame();">Test</button>
</body>
</html>
You can make new function where you can call it on button just like you called it with console.log:
<button onclick="start();">Test</button>
and call your randomizing function inside:
function start() {
testGame(item)
}
Then inside function testGame don't use return, just save random word result in variable and print it in HTML:
var result = array[Math.floor(Math.random() * array.length)];
console.clear();
console.log(result);
document.getElementById("result").innerHTML=result;
I have added div result in HTML:
<div id="result"></div>
EXAMPLE SNIPPET:
var item = {
'apple': 10,
'banana': 10,
'orange': 10,
'grapes': 1,
}
function testGame(input) {
var array = [];
for (var item in input) {
if (input.hasOwnProperty(item)) {
for (var i = 0; i < input[item]; i++) {
array.push(item);
}
}
}
var result = array[Math.floor(Math.random() * array.length)];
console.clear();
console.log(result);
document.getElementById("result").innerHTML=result;
}
function start() {
testGame(item)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Randomizer Game</title>
</head>
<body>
<h1>Game</h1>
<div id="result"></div>
<script src="index.js"></script>
<button onclick="start();">Test</button>
</body>
</html>
Use getElementById to get an element by id, for this I gave your button an id. With addEventListener you can add an event (here: click) to be call a function.
Doing here your randomizing. Get the element where you want the output again with getElementByIdand add with textContent your answer to it.
const ITEMS = {
'apple':10,
'banana':10,
'orange':10,
'grapes':1,
}
document.getElementById('btn').addEventListener('click', function testGame() {
var array = [];
for(var item in ITEMS) {
if(ITEMS.hasOwnProperty(item) ) {
for(var i=0; i<ITEMS[item]; i++ ) {
array.push(item);
}
}
}
document.getElementById('item').textContent = array[Math.floor(Math.random() * array.length)];
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Randomizer Game</title>
</head>
<body>
<h1>Game</h1>
<button id='btn'>Test</button>
<div id='item'></div>
</body>
</html>
I have just started learning Javascript, and I attempted to write code for hit counter for a webpage using Javascript. I know that we have to use cookies to get the correct number and use PHP to modify data stored in servers. But could you please debug this for me ? I'm getting the output as "The number of visitors is: NaN"
This is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<p>The number of visitors is : <span id="cntr">0</span></p>
</div>
<script>
function counter_fn() {
var counter = document.getElementById("cntr");
var count = 0;
count = counter.value;
count = count + 1;
counter.innerHTML = count;
}
window.onload = counter_fn;
</script>
</body>
</html>
You are trying to get the valuefrom a span element, which is wrong.
Your counter.value is undefined so it will give you the wrong answer.
You can get the 0 from the span by using document.getElementById("cntr").innerHTML. But the value returned is in string. So you need to do parseInt to convert it into integer and only then your addition will give you the correct value.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<p>The number of visitors is : <span id="cntr">0</span></p>
</div>
<script>
function counter_fn() {
var counter = document.getElementById("cntr");
var count = 0;
count = parseInt(counter.innerHTML);
count = count + 1;
counter.innerHTML = count;
}
window.onload = counter_fn;
</script>
</body>
</html>
You need to use parseInt
<script>
function counter_fn(){
var counter = document.getElementById("cntr");
var count = 0;
count = parseInt(counter.value);
count = count+1;
counter.innerHTML = parseInt(count);
}
window.onload = counter_fn;
</script>
UPDATE
As #Anurag Singh Bisht commented, you cannot get value from a span element . So to get value from <span> you need to use $('span').text();
<html>
<body>
<div id="cntr">
The number of visitors is :
<span>0</span>
</div>
<script>
function counter_fn(){
var counter = $('#cntr span').text(); // geting value from span
var count = 0;
count = parseInt(counter.value);
count = count+1;
counter.innerHTML = parseInt(count);
}
window.onload = counter_fn;
</script>
</body>
</html>
You need to parse the string to an integer and you need to get the innerHTML.
<script>
function counter_fn(){
var counterElement = document.getElementById("cntr")
var counterNumber = parseInt(counterElement.innerHTML)
counterNumber = counterNumber + 1
counterElement.innerHTML = counterNumber
}
window.onload = counter_fn;
</script>
The correct way to do it would be storing this value somewhere else, like localStorage and reading it from there. You are not supposed to read your own HTML to update the value. HTML elements are supposed to be results, not your input.
var counterNumber = 1
if (localStorage.getItem("count")) {
counterNumber = parseInt(localStorage.getItem("count")) + 1
}
else {
localStorage.setItem("count", counterNumber)
}