I’m trying to track the clicks on a button on my website. I’ve tried adding the following but to no success. I’m a noob to JS..
function trackButton(e) {
onPage.innerHTML = ++i;
}
var i = 0;
var onPage = document.getElementById(‘track’);
var clickCount = document.getElementById(‘bttn’);
clickCount.addEventListener('click', function (e) {
addOne(e);
}, false);
You did some mistake:
The function addOne doesn't exist, it's trackbutton
it's i++ to increment a value, not ++i
And some tips for you:
Use let and const (ES6) for the variable, not var
And the e for the event is useless here, you are not using it, so it's not mandatory here
Do these change and it must work !
UPDATE:
To increment a value ++i works, see the documentation
Change the quotes ‘‘ with " " or ' '.
Like so: document.getElementById(‘track‘) to document.getElementById('track')
I was checkin your code and its almost all right, i think that the problem its in your addOne function, here is a way to resolve the problem.
i creat the button and paragraph elements in html and in javascript a variable n where we are going to storage the clicks tha the user did and we increment n when the function its called in the button's event
var n = 0;
var button = document.getElementById('track');
button.addEventListener('click', trakeo);
var texto = document.getElementById('number');
function trakeo(){
n++
texto.innerHTML = n;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>A Great Demo on CodePen</title>
</head>
<body>
<button id="track">Button</button>
<p id="number"></p>
</body>
</html>
Try to use
addEventListener('click',)
https://www.w3schools.com/jsref/met_element_addeventlistener.asp
Related
I'm Making a Two Button in HTML,CSS and Javascript. The first button is called "Call Button" and second button is "Skip Button".
The process/scenario is :
The Skip Button is Disabled,
It will only be Enabled when 'Call Button' was Clicked 3 times.
If 'Call Button' was Clicked Three Times by the User, The Skip BUtton will be enable.
I have already made the function for the said process and scenario.
The problem is, Everytime I clicked the "Call Button" the Page refresh and the counter for the button is always refreshing turning it into zero(0) value every time I click "Call Button".
Now is it possible to store the 'Counter' in a LocalStorage?
How Can I implement it in my Code? Its my First time using this kind of function.
I highly appreciate it.
`<!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">
<title>Document</title>
<script>
// Function for counting the number of times the user clicked the call button
let counter = 0;
function enableButton() {
checker += 1;
if(counter === 3){
document.getElementById("button2").disabled = false;
}
}
</script>
</head>
<body>
<button type="button" id="button1" onclick="enableButton()">Call Button</button>
<button type="button" id="button2" disabled>Skip Button</button>
</body>
</html>`
The Above Code is a Example of my work. But on my original project, it has an refresh/reload function on button.
There might be other ways of doing it, but this is an example of how to store the counter in localStorage:
let counter = localStorage.getItem("clickCounter");
if (counter === null) {
counter = 0;
} else {
counter = parseInt(counter)
}
function enableButton() {
counter += 1;
localStorage.setItem("clickCounter", counter.toString());
if(counter >= 3){
document.getElementById("button2").disabled = false;
}
}
You have to parse the item from the localStorage, since you can only store strings.
I would like some help please.
I managed to make my code work after finding a similar question on Stack Overflow, but the method I've been trying previously doesn't seem to work at all.
My code is very simple, if the number is 2 and I click the button, the message will say "Correct". If the number is anything else, it will say "Wrong".
Below is the 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">
<script src="script.js" defer></script>
<title>Document</title>
</head>
<body>
<input type="number">
<p>Message</p>
<button>Update</button>
</body>
</html>
Here is the JavaScript code that works
Codepen link
const message = document.querySelector("p")
const button = document.querySelector("button")
function myFunction() {
const number = document.querySelector("input").value;
if (parseInt(number) === 2) {
message.textContent = "Correct"
} else message.textContent = "Wrong!"
}
button.addEventListener("click", myFunction)
Here is the code that doesn't work
Codepen link
const message = document.querySelector("p")
const button = document.querySelector("button")
const number = document.querySelector("input").value
function myFunction() {
if (parseInt(number) === 2) {
message.textContent = "Correct"
} else message.textContent = "Wrong!"
}
button.addEventListener("click", myFunction)
My question is, why doesn't my second JavaScript code work? Is it possible to keep the number const outside of the function (keep the const variable global)?
As the tutorials I'm watching suggest you keep variables outside functions to prevent DRY.
Also, how can I get the code to run without having to click the "update" button each time
?
e.g. if I type 2, the message will automatically say "Correct".
Thank you very much in advance.
const number needs to be in the function, otherwise the const will be null always
function myFunction() {
const number = document.querySelector("input").value
if (parseInt(number) === 2) {
message.textContent = "Correct"
} else message.textContent = "Wrong!"
}
Live update on keyup inputfield
const inputfield = document.querySelector("input");
inputfield.addEventListener("keyup", myFunction);
So basically I have done this code down bellow and I am trying to have a button that adds 1 to a variable and when that variable hits the specific number it plays an action. My final goal is to make it so when the variable hits the specific number it redirects to another page. I have tried for way too long and my friends don't know the solution either.
<!DOCTYPE html>
<head> </head>
<!DOCTYPE html>
<html>
<head>
<title> click tester </title>
<Meta charset="utf-8">
</head>
<body>
<script>
var theClicks = 1;
const win = 25;
if(theClicks >= win) {
alert('over 25');
}
</script>
<button onclick=theClicks++;>Button that adds1 to variable</button>
</body>
</html>
<button onclick=theClicks++;>Button that adds1 to variable</button>
Just increments the variable. To expand that you could add more actions in the button onclick event, but it's much better to just put it all in a function you can call.
<script>
var theClicks = 1;
const win = 25;
function doThing() {
if (++theClicks >= win) {
alert('over 25');
}
}
</script>
<button onclick='doThing()'>Button that adds1 to variable</button>
You could take an approach like below. Basically create a function that keeps track of a counter variable (i.e., i). Next add a click event listener to the button and increment the counter on each click. When the counter reaches 25 then do some action (I made it only needed to be clicked 3 times in the code below for demo convenience) .
For example:
// Reference to the DOM elements
const countEl = document.querySelector('#count-el');
const buttonEl = document.querySelector('button');
// Init a counter variable and return a function that increments it
const increment = (() => {
let i = 1;
return () => i++;
})();
// The click event listener
buttonEl.addEventListener('click', () => {
// Increment the count and update the UI if current click count is 3
if (increment() === 3) {
countEl.textContent = 'Do action now!';
}
});
<span id="count-el"></span>
<br />
<button>Click 3 times to do action</button>
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
I am learning Javascript language and so I am on a project while I came across this issue. Here is the code:
function koko() {
items = document.getElementsByTagName("a");
for (var pos = 0; pos < items.length; pos++) {
this.items[pos].addEventListener("click", function() {
console.log(pos);
});
}
}
koko();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
Click me 1
Click me 2
Click me 3
</body>
</html>
Every time I click on any item with a tag I get same value on the console that is items.length. But I am expecting it to print the position/index of the element that is clicked. For example, if I click Click me 2 it should print 1. What am I missing here?
When the click listener is executed, pos has the value of 3, your code is fine, look at this example:
function koko() {
items = document.getElementsByTagName("a");
for (var pos = 0; pos < items.length; pos++) {
this.items[pos].addEventListener("click", function() {
console.log(this.innerHTML);
});
}
}
koko();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
Click me 1
Click me 2
Click me 3
</body>
</html>
Try this for the desired results
function koko() {
items = document.getElementsByTagName("a");
for (var pos = 0; pos < items.length; pos++) {
this.items[pos].id = pos;
this.items[pos].addEventListener("click", function() {
console.log(this.id);
});
}
}
koko();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
Click me 1
Click me 2
Click me 3
</body>
</html>
You function logs pos, WHEN the button is clicked, not when the event listener is added. To fix this, you can use this code:
function koko() {
items = document.getElementsByTagName("a");
for (var pos = 0; pos < items.length; pos++) {
this.items[pos].addEventListener("click", function() {console.log(this.id);});
}
}
koko();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
Click me 1
Click me 2
Click me 3
</body>
</html>
The changes it makes from the original code:
Added id to each link. The number in this is written to the screen.
Changed Javascript to write the id of the link.
I am struggling with the following problem.
I have made a memorygame with javascrpt for school.It all works fine, but my teacher told me that i can not have on line of javascript in my HTML, like this :
HTML :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="styles.css">
<title>Memory spelen</title>
</head>
<body>
<script type="text/javascript" src="javascript.js"></script>
<div id="memory_board"></div>
<script>newBoard();</script>
</body>
</html>
The newBoard() is applied to the memory_board div. How can i take this little piece of script out of my HTML file and place it in my js file, to still function properly.
Thanks in advance
Inside of your javascript.js put this
window.onload = function {
// content of your script
var newBoard = function(){
// the new updated newBoard() function from below
}
// other parts of your script
if(window.location.href == 'your-url') {
// now, after the newBoard() has been updated
// the next to lines are not needed
// var board = document.getElementById('memory_board');
// board.innerHTML = newBoard();
// just call the function
newBoard();
}
};
UPDATE
I just took a look at your old fiddle and I changed your newBoard function to this
function newBoard(){
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for(var i = 0; i < memory_array.length; i++){
var div = document.createElement('DIV');
div.id = "tile_" + i;
(function(div,i){
div.onclick = function() {
memoryFlipTile(this, memory_array[i]);
};
}(div,i));
document.getElementById('memory_board').appendChild(div);
}
}
Check the working fiddle.
try to put it like this in external js file
$(document).ready(function(){
newBoard();
});
It looks that you need to call newBoard() method on onload event of memory_board div , You can do this in following ways:
<div id="memory_board" onload="javascript:newBoard()" ></div> // use onload event of memory_board
you can use onload function on the javascript. It will call the function when all the HTML tag is loaded on the screen.