I know this might be pretty simple but I cannot see the tree from the wood atm.
Please can you help?
I have a variable whose initial value is 1 and I want to increment it by 1 every single time the user clicks on a button.
I have this code:
let counter = 0;
dPadRight.addEventListener("click", function increment() {
counter++;
}
);
console.log(counter);
We don't have your html markup, so below I just created a div with ID of 'dPadRight' to add the listener to. I then referenced this in a variable in the javascript code. I assume you're already doing something like this to have a variable called 'dPadRight'.
Based on your comment describing your need to "use [the counter] for other things", I added another "pad" identified as "otherPad". "dPadRight" can serve to increment the counter. "otherPad" can serve to do something with the counter. In the code below, I just log it.
The lesson here is that if you want to use the counter after it's been incremented -- well -- then you can't be referencing it the main javascript body because that's before it's ever had the chance to increment.
let dPadRight = document.querySelector('#dPadRight');
let otherPad = document.querySelector('#otherPad');
let counter = 0;
dPadRight.addEventListener("click", () => {
counter++;
});
otherPad.addEventListener("click", () => {
console.log(counter);
});
<div id="dPadRight">
click to increment counter
</div>
<br/>
<div id="otherPad">
click to log counter
</div>
Try this
let counter = 1;
let dPadRight = document.getElementById('dPadRight');
dPadRight.addEventListener("click", function() {
console.log(counter);
counter++;
if(counter > 5){
// just to show that counter is available outside the annonymous
// function
let bla = getCounterValue();
console.log("Bla Value " + bla);
}
}
);
function getCounterValue(){
return counter;
}
<button id="dPadRight">Increment Me </button>
Related
I am still learning and I like to know why certain codes happen the way they do. So, created a code to increment by 1 when a button is clicked and have that displayed on the screen. However, when using addEventListener, it didnt work. It only added 1 and never increased by 1 again.
But when I used onclick Event in html, it worked fine and incremented. What could be the issue? Here are the codes:
HTML
<div class="score container">
<h3 class="firstScore">0</h3>
<h3 class="to">To</h3>
<h3 class="secondScore">0</h3>
Player One
JS code with addEventLister. This doesnt increment, But when I used consol.log(count), it increased by 1 but grayed out. Kindly check the attached screenshot
var playerOne = document.querySelector('.playerOne')
playerOne.addEventListener('click', () => {
count = 0;
function countNum() {
count++;
document.querySelector('.firstScore').innerHTML = count;
}
countNum()
})
This is the JS code that I used onclick and added the function to the button directly. This is working fine. I want to know what made the addEventListener not to work?
count = 0;
function countNum() {
count++;
document.querySelector('.firstScore').innerHTML = count;
console.log(count)
}
The button with the html:
<button onclick="countNum()" class="playerOne">Player One</button>
You're resetting count to 0 every time the function is called.
You need to use the inner function as the event listener, not the outer function. You can do this with an IIFE that returns the inner function.
var playerOne = document.querySelector('.playerOne')
playerOne.addEventListener('click', (() => {
count = 0;
function countNum() {
count++;
document.querySelector('.firstScore').innerHTML = count;
}
return countNum;
})())
<div class="score container">
<h3 class="firstScore">0</h3>
<h3 class="to">To</h3>
<h3 class="secondScore">0</h3>
<button class="playerOne">Player One</button>
You should move your var count = 0 outside from addEventListener function. Otherwise on each click you will reset your counter and then immediately increment it, which means you always assign to innerHTML value equal to 1.
Fixed example with addEventListener:
var playerOne = document.querySelector('.playerOne');
var firstScore = document.querySelector('.firstScore');
var count = 0;
var countNum = function() {
count++;
firstScore.innerHTML = count;
};
playerOne.addEventListener('click', countNum);
Working example.
I am writing a little clicking game with javascript at the moment and I am currently stuck with a little challenge. I need it so that whenever i have clicked a button 10 times. my second value should increase by one. Maybe a little bit hard to understand, I'll try to explain it in code.
// Let's just say I have this variable.
var timesThatTheButtonHasBeenClickedTenTimes = 0;
// So let's say I have an amount of times clicked.
Amount = 0;
// Whenever I click the button..The Amount increases like this.
Amount++;
// so after one click the amount should be..
Amount = 1;
// I need it so that when the button has been clicked 10 times I want to display //that. Something like this.
timesThatTheButtonHasBeenClickedTenTimes = 1;
Should I do this with a while loop or what.
// Let's just say I have this variable.
var timesThatTheButtonHasBeenClickedTenTimes = 0;
// So let's say I have an amount of times clicked.
var amount = 0;
var counter = function () {
amount++;
if (amount === 10) {
amount = 0;
timesThatTheButtonHasBeenClickedTenTimes++;
}
document.getElementById('clicks').innerHTML = amount;
document.getElementById('hits').innerHTML = timesThatTheButtonHasBeenClickedTenTimes;
};
document.getElementById("mybutton").addEventListener("click", counter);
<button id='mybutton'>
Click me!
</button>
<p>
Clicks = <span id='clicks'>0</span>
</p>
<p>
10 times hits = <span id='hits'>0</span>
</p>
Hope it helps!
You could do something like:
var timesButtonClicked = 0;
var secondValue = 0;
if (timesButtonClicked === 10) {
secondValue++;
timesButtonClicked = 0;
} else {
timesButtonClicked++;
}
This is the very simple solution for you problem:
var clicks = 0;
Clicker = function() {
clicks++;
console.log('You clicked '+clicks+' times already.');
if(clicks == 10){
alert('Something what you want to alert.')
clicks = 0;
}
}
<button onclick="Clicker()">
Click me 10x times pls
</button>
One approach I'd suggest is:
function increment() {
// find the current number of times the <button> has been clicked,
// if the <button> has a data-current attribute we retrieve that
// attribute-value and parse it as a number in decimal format;
// if it does not have that custom data-* attribute we set the
// variable to 0:
let currentValue = this.dataset.current ? parseInt(this.dataset.current, 10) : 0;
// here we update the data-current attribute to the incremented value
// of the currentValue:
this.dataset.current = ++currentValue;
// we retrieve the element with the id of 'clicks', and set
// its textContent to the value held by the currentValue:
document.getElementById('clicks').textContent = currentValue;
// here we retrieve the element with an id of 'numberOfTens',
// and set its textContent to the floored value of the currentValue
// divided by 10:
document.getElementById('numberOfTens').textContent = Math.floor(currentValue / 10);
}
// here we retrieve the element with the id of 'clicker':
document.getElementById('clicker')
// and bind the increment() function (note the deliberate lack of
// parentheses) as the event-handler for the 'click' event:
.addEventListener('click', increment);
div:empty::before {
content: '0';
}
#clicks::after {
content: ' clicks.';
}
#numberOfTens::after {
content: ' tens of clicks.';
}
<button id="clicker">Click</button>
<div id="clicks"></div>
<div id="numberOfTens"></div>
References:
CSS:
:empty pseudo-class.
Pseudo-elements, ::before, ::after.
content property.
JavaScript:
document.getElementById().
EventTarget.addEventListener().
HTMLElement.dataset.
parseInt.
Pre-increment variable ++variableName.
I am currently working on a postIt for my website where pressing the plus button would create an editable post it/sticky notes. I am done with that part now but I am struggling with the next part which is limiting the number of sticky notes to just 4. I tried having a global variable that would serve as a counter so when the counter is 3, it should stop creating more sticky notes but unfortunately, it is not working.
Here is the link to my workable code:
Sticky note
And this is my futile attempt at limiting the number of sticky notes to 4.
$("#create").click(function(){
var count = 0;
if( count < 4){
$("#create").click(function() {
$(this).before("<textarea></textarea>");
});
count++;
}
}
Can anyone please give me pointers as to how to limit the notes to 4? I have been working on this forever now.
Just move var count = 0; outside the event listener and remove the inner event listener:
var count = 0; // outside the scope of the event listener function bellow so it won't get destroyed/recreated each time the function get called (ie when a clicks happen)
$("#create").click(function() {
if(count < 4) { // we haven't yet exceeded the limits
$(this).before("<textarea></textarea>"); // don't attach another click event listener on #create (we are already in one) so just create the note.
count++;
}
});
Everytime you click create, count the number of textarea elements then determine if you should create a new one:
$("#create").click(function() {
var count = $("textarea");
if (count.length < 4) {
$(this).before("<textarea></textarea>");
}
});
You can even add a class in the newly created textarea to ensure that you only count the ones created by this function.
HTML:
<textarea>This is not part of the group.</textarea>
<textarea class="sticky">This is a sticky note you can type and edit.</textarea>
<div id="create">+</div>
JS:
$("#create").click(function() {
var count = $("textarea.sticky");
if (count.length < 4) {
$(this).before("<textarea class='sticky'></textarea>");
}
});
The problem is that you are defining your count variable inside of your click event handler. As such, every time you click the element, the counter gets reset. You also shouldn't make use of a secondary click handler inside the main one.
To resolve this, bring the count variable outside of the click handler:
var count = 0;
$("#create").click(function() {
if (count < 3) {
$(this).before("<textarea></textarea>");
count++;
}
});
Note that the conditional should check that the count is less than 3, because it increases the count after creation. If it is set to check if the count is less than 4, five notes would be created.
In order to also hide the + after creating the fourth element, you would use:
if (count == 3) {
$(this).hide();
}
After increasing the count.
This can be seen working here.
Hope this helps! :)
I thought that this onClick event in a For loop would help me but when I tried it, it still didn't work.
I am making a simple Battleship game, and while I'm trying to have the user click on only 4 squares to place on ship, the loop keeps going and doesn't stop after 4 tries. I have my onclick even handler in a for loop, but after 4 tries it doesn't stop. I've tried adding a count variable after the end, and even tried adding a break statement but can't get it to work.
Here's my code:
function placeShips() {
var playerTable = document.getElementById("mainPlayer");
var playerCells = playerTable.getElementsByTagName("td");
var count = 1;
alert("Please place the first ship. Click on 4 squares.");
while (count <= 4) {
for (i = 0; i < playerCells.length; i++) {
playerCells[i].onclick = placeBattleship;
}
count++;
}
}
The placeBattleship function contains the code to change the grid square to a background color of red to mark it. My problem is that once the user clicks 4 squares, you can keep going and click on more and more. I can't get the above for loop that calls the placeBattleship function to stop after the user clicks on 4 squares. I've tried putting it in a while loop, and even the solution in the above link, as well as moving the assignment of count, but can't get it to stop after x amount of times (in this case, 4).
Any ideas on what I'm doing wrong, or a better way to do it?
Wouldn't you consider to use jQuery?
Look your function much shorter:
function placeShips() {
$("td:lt(4)").click(placeBattleship);
}
You can testify on the code below:
<table>
<tr>
<td>1.1</td><td>2.1</td>
</tr>
<tr>
<td>1.2</td><td>2.2</td>
</tr>
<tr>
<td>1.3</td><td>2.3</td>
</tr>
</table>
<div id="console"></div>
<script>
$("td:lt(4)").each(function(){
$("#console").append("Content of "+ $(this).html() + "<br/>");
});
$("td:lt(4)").click(function(){
$("#console").append("Clicking "+ $(this).html() + "<br/>");
});
</script>
...or on my Plunker: https://plnkr.co/edit/yNZw6ZhkNfA9E0NdQg7V
So, now we have a solution that stop for 4th click on the squares:
function placeBattleship() {
var $shipDisplay = $("#shipDisplay");
var counter = $shipDisplay.data("counter");
if(counter++ < 4) {
$(this).css("background-color", "red");
$shipDisplay.data("counter", counter);
}
}
function placeShips() {
$("td").click(placeBattleship);
}
$(document).ready(function(){
placeShips();
});
I use a div with id shipDisplay to store a data-attribute for count the clicks.
Look at the plunker: http://plnkr.co/edit/PEba15PSLv2LK6qjY7AD?p=preview
You should separate priorities in your logic and removeEventListener when counter hits 4 , hopefully this helps you :
//defined outside the function
var counter = 0;
playerCells.addEventListener("click" , placeShips );
Then
function placeShips() {
if(counter <= 4){
//Move ship
placeBattleship();
//add to counter
counter++
}else{
//Remove click event if counter reaches 4 .
playerCells.removeEventListener("click" , doSomethingElse)
}
}
You question needs a bit clarification. To my current understanding, you need to move the checking of count to placeBattleship.
What you are doing is binding click to same tds 4 times, not limiting the number of event triggering to 4 times.
// pseudo code
var count = 4; // this is global
var currentCount = 0;
initFunc() {
// bind click events ONCE
}
startPlacing() {
// accept user click and place ship
// set currentCount to zero
}
placeShip() {
// the callback of user `click`
// check for currentCount == count then move on (no more placement)
// increase currentCount by 1
// place ship
}
Note that after an event is triggered, the listener will not be removed. Until you removeEventListener() from it, it will always be listening.
I'm now trying to repeatedly display id1 and id2 elements ( hide, show ). If possible I also want to put fade-in/out methods.
Although I can see "counter" value by putting alert(); function. But id1,2 don't change themselves, and only id1 is stuck as a final display.
I put the code of mine below.
<div class="row" id = 'wow1'> wowwow1 </div>
<div class="row" id = 'wow2' style="display:none;"> wowwow2 </div>
////
<script>
$(function() {
var counter = 0;
var timer = setInterval( showDiv, 2000);
function showDiv() {
if (counter ==0) { counter++; return; }
$('#wow1','#wow2')
.hide()
.filter( function() { return this.id.match('wow' + counter); })
.show('fast');
counter == 2? counter = 0 : counter++;
alert(wow);
}
});
</script>
I modified this code a bit from other stack overflow question for this application. How can I make this work?
Please let me know!
Best
Change $('#wow1','#wow2') to $('#wow1,#wow2')
As your current code is looking for #wow1 inside #wow2 whereas you actually want to select both elements.
http://api.jquery.com/jQuery/#jQuery-selector-context