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)
}
Related
I am trying to create a simple genorator code for a flight simulator. It should genorate four numbers between 0 and 7, and then update the text of a Div.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SG 0.0.0</title>
<script src="index.js"></script>
</head>
<body>
<div id="squawk">0000</div>
<button onclick="genSquawk" id="gen">Genorate Squawk</button>
</body>
</html>
JS:
const div = document.getElementById('squawk')
var num1 = Math.random() * 7;
var num2 = Math.random() * 7;
var num3 = Math.random() * 7;
var num4 = Math.random() * 7;
function genSquawk() {
div.textContent = num1,num2,num3,num4;
}
div.textContent = num1,num2,num3,num4; is not valid syntax. If you want an an array, for instance, you could use [num1, num2, num3, num4]. Since you're updating the node's text content, you likely want to make these numbers a string value to insert into your div element. In that case, there are many ways to make a string from your series of numbers. One way is string concatenation, something like
div.textContent = `${num1}, ${num2}, ${num3}, ${num4}`;
There are a few changes to be made. One is the following line:
<button onclick="genSquawk" id="gen">Genorate Squawk</button>
You are referencing the genSquawk function on the onclick property, not calling it. The correct is:
<button onclick="genSquawk()" id="gen">Genorate Squawk</button>
Now it should trigger the function properly. The second one is: the syntax num1,num2,num3,num4 is not correct, and will cause the code to display only the first num. In order to do so, use string literals: ${num1}, ${num2}, ${num3}, ${num4}.
Finally, I do not know if you want integers or if each of the four numbers could be floats. But I added a function to generate a int number between 0 and 7.
function getRandomArbitrary() {
return Math.floor(Math.random() * 7);
}
function genSquawk() {
const div = document.getElementById('squawk')
var num1 = getRandomArbitrary();
var num2 = getRandomArbitrary();
var num3 = getRandomArbitrary();
var num4 = getRandomArbitrary();
div.textContent = `${num1}${num2}${num3}${num4}`;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SG 0.0.0</title>
<script src="index.js"></script>
</head>
<body>
<div id="squawk">0000</div>
<button onclick="genSquawk()" id="gen">Genorate Squawk</button>
</body>
</html>
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'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
I'm trying to make a random sequence triggered by mouse click, and track how many times a user would click on the images. Could anyone help me with that? Thanks!
Below are my code that are pulling images randomly:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>The Door Moment</title>
<script type="text/javascript">
function changePic()
{
var num = Math.ceil(Math.random()*9);
document.getElementById("p").src = num + ".jpg";
}
function buttonclick() {
document.getElementById("p").value++;
}
</script>
</head>
<body>
<p align="center"><img src = "1.jpg" id = "p" width="400px" height="600px" onclick="changePic()" /></p>
</div>
</body>
Assume you start your image sequence from 1, you can use a counter to count your image click times.
When image element is clicked, buttonclick function will track how many times user has clicked on the image. And then change your current image sequence number which will show a different image.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>The Door Moment</title>
<script type="text/javascript">
const counter = {};
let num = 1;
function changePic()
{
num = Math.ceil(Math.random()*9);
document.getElementById("p").src = num + ".jpg";
}
function buttonclick() {
counter[num] = (counter[num] || 0) + 1;
console.log(counter)
//if you want to show current count for the sequence, you can use console.log(counter[num])
changePic()
}
</script>
</head>
<body>
<p align="center"><img src = "1.jpg" id = "p" width="400px" height="600px" onclick="buttonclick()" /></p>
</div>
</body>
try make clickCounter object with a key equal to the picture number and better use onclickmethod in JS but not in html
let num = 1;
const clickCounter = {};
const randomPic = document.getElementById('randomPic')
randomPic.onclick = function(){
clickCounter[num] = (clickCounter[num] || 0) + 1;
changePic();
console.log(clickCounter); // if you need
}
function changePic() {
num = Math.ceil(Math.random()*9);
randomPic.src = num + ".jpg";
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>The Door Moment</title>
</head>
<body>
<p align="center"><img src = "1.jpg" id = "randomPic" width="400px" height="600px"/></p>
</body>
</html>