Javascript - When element is clicked add 1 to score - javascript

I have a score variable and I'm trying to add 1 to it every time a word is clicked, and display the score on the webpage. Here is the html:
<p>1. The <span id="noun">dog</span> and the <span id="noun">kitten</span> play with the <span id="noun">ball</span>.</p>
<h3>Score: <span id="results1"></span> out of 9</h3>
and here is the javascript:
var nounAll = document.querySelectorAll('#noun');
var score = 0;
var result1 = document.querySelector('#result1');
for(var i = 0; i < nounAll.length; i++) {
console.log(nounAll[i].textContent)
nounAll[i].addEventListener("mouseover",function()
{
this.classList.add("hovered")
});
nounAll[i].addEventListener("mouseout", function()
{
this.classList.remove("hovered")
});
nounAll[i].addEventListener("click", function()
{
this.classList.toggle("clickedOn")
score++;
});
}
document.getElementById("results1").textContent = score;
What am I doing wrong?

Your score variable is working fine. You just need to update the Score element:
nounAll[i].addEventListener("click", function()
{
this.classList.toggle("clickedOn")
score++;
// Add the below line
document.getElementById("results1").textContent = score;
});

The problem is that after the click event is fired, you don't assign the new score to your target DOM element on every action.
nounAll[i].addEventListener("click", function()
{
this.classList.toggle("clickedOn")
score++;
document.getElementById("results1").textContent = score; // add this line to your click event handler
});

var nounAll = document.querySelectorAll('#noun');
var score = 0;
var result1 = document.querySelector('#result1');
for(var i = 0; i < nounAll.length; i++) {
console.log(nounAll[i].textContent)
nounAll[i].addEventListener("mouseover",function(e)
{
e.target.classList.add("hovered")
});
nounAll[i].addEventListener("mouseout", function(e)
{
e.target.classList.remove("hovered")
});
nounAll[i].addEventListener("click", function(e)
{
e.target.classList.toggle("clickedOn")
score++;
document.getElementById("results1").textContent = score;
});
}
<p>1. The <span id="noun">dog</span> and the <span id="noun">kitten</span> play with the <span id="noun">ball</span>.</p>
<h3>Score: <span id="results1"></span> out of 9</h3>

There are 2 mistakes:
Your element IDs are not unique, you want to use classes instead, so change id="noun" to class="noun" in the HTML and change the selector in document.querySelectorAll accordingly (dot rather than hash).
There is a logic error: you are updating a js variable but after you update the variable you also have to change the content of the span accordingly (in the fiddle I have put an example of how you can do that)
My solution

Related

JavaScript Calculator - How to get numbers into input field?

So I have assigned all my numbers a class of numbers and all my operators a class of operators with ids specific to their operation. Every item is within a div tag.
Full data here: jsfiddle
<div class="number clear" id="clear"><h1>C</h1></div>
<div class="number" id="entry"><input type="number"></div>
<div class="number seven"><h1>7</h1></div>
<div class="number eight"><h1>8</h1></div>
<div class="number nine"><h1>9</h1></div>
<div class="operate divide" id="divide"><h1>/</h1></div>
So the above is just a glimpse of the HTML. My CSS works perfectly fine but I'm struggling with the JavaScript. I've put in a for loop to pull from all the numbers in the HTML to do an addEventListener for onclick. I feel confident in the for loop but I could definitely be wrong.
Right now I have the following:
let number = document.getElementsByClassName("number");
let operate = document.getElementsByClassName("operate");
let entry = document.getElementById("entry");
let clear = document.getElementById("clear");
let sub=document.getElementById("sub");
let multiply = document.getElementById("mul");
let divide = document.getElementById("divide");
let add = document.getElementById("plus");
for (let i=0; i<numbers.length; i++) {
numbers[i].addEventListener("click", function(entry)){
let inputValue = entry[0].innerHTML;
let buttonValue = this.html;
if (buttonValue === "C") {
entry[0].innerHTML = "";
} else {
entry[0].innerHTML += buttonValue;
}
}
}
function (entry){
}
I know I need to run a function in the for loop but for the life of me I'm drawing blanks as to what to enter to push the values from the div into the entry field for the calculation. Right now if I click on any of the buttons nothing happens, clearly as there's no function. Any insight on how to adjust this to get something to populate would be appreciated.
let numbers = document.getElementsByClassName("number");
let entry = document.getElementById("entry");
for (let i=0; i<numbers.length; i++) {
numbers[i].addEventListener("click", function(){
let buttonValue = this.textContent;
if (buttonValue === "C") {
entry.innerHTML = "0000";
} else {
entry.innerHTML = (entry.innerHTML+buttonValue).substr(-4);
}
});
}
.number {
display:inline-table;
}
<h1><div id="entry">0000</div></h1>
<div class="number"><h1>1</h1></div>
<div class="number"><h1>2</h1></div>
<div class="number"><h1>3</h1></div><br>
<div class="number"><h1>4</h1></div>
<div class="number"><h1>5</h1></div>
<div class="number"><h1>6</h1></div><br>
<div class="number"><h1>7</h1></div>
<div class="number"><h1>8</h1></div>
<div class="number"><h1>9</h1></div><br>
<div class="number "><h1>C</h1></div>
You just mixed up some variable names and used non existent properties...
As mentioned by Jonas in his answer, there are a bunch of issues in your current code - including some syntax issues. So I decided replace your event handler completely, and write it using jQuery - as it really comes in handy in such cases.
The event handler looks like this:
$(".number").on("click", function(event){
var num = $(this).text();
console.log(num);
if(num != 'C') {
var currentNumber = $("#entryNum").val();
$("#entryNum").val(currentNumber.toString() + num.toString());
} else {
$("#entryNum").val('');
}
});
The logic of the event handler remains quite similar to your original logic, but I have just simplified it using jQuery. Also, to allow for faster access to the input element, I gave it an ID entryNum:
<div class="number" id="entry"><input type="number" id="entryNum"></div>
Here's the updated fiddle: https://jsfiddle.net/Nisarg0/L9mL4v3a/6/
Not certain about exact logic or expected result, though there are issue with selecting appropriate element and syntax errors
for (let i = 0; i < numbers.length; i++) {
numbers[i].addEventListener("click", function(event) {
// select the `<input>` child element of `entry` here, not `entry[0]`
// and use `.value` property
let inputValue = entry.querySelector("input").value;
// you want `.textContent` here, not `.innerHTML`
let buttonValue = this.textContent;
if (buttonValue === "C") {
entry.innerHTML = "";
} else {
entry.innerHTML += buttonValue;
}
}) // include closing `)` at `.addEventListener()` call
}
I just implement Press and Clear function.
Learn and do it!
1.Add id for inputfield
<div class="number" id="entry"><input id="entryText" type="number"></div>
2.Do it!
let numbers = document.getElementsByClassName("number");
let entryText = document.getElementById("entryText");
for (let i=0; i<numbers.length; i++) {
numbers[i].addEventListener("click", function(event){
let buttonValue = event.toElement.innerText;
if (buttonValue === "C") {
entryText.value = "";
} else {
entryText.value += buttonValue;
}
});
}
There are several issues in your code:
Your event listener accepts a parameter called entry, which overwrites the entry variable in the outer scope. The first parameter of the event listener that you pass to addEventListener contains information about the click event (which you normally don't need). So remove the entry parameter from the event listener.
The value of this in an event listener is a reference to the element that you bound the event listener to. It won't have a property called html.
You declare a variable called number, but use a variable called numbers.
numbers[i].addEventListener("click", function(entry)){ results in a syntax error. Remove the second ) between parameter list and the function body.
function (entry){} results in a syntax error, because function statements require a name. Just remove it, it's superfluous.
That said, get some inspiration from the following code snippet:
const input = document.querySelector('input');
document.querySelectorAll('.number').forEach(function (button, index) {
button.addEventListener('click', function () {
input.value += index + 1;
});
});
<input type="number">
<button class="number">1</button>
<button class="number">2</button>
<button class="number">3</button>
<button class="number">4</button>

Using a javascript button to change html, with multiple values that are picked using an auto incrementing number

Basic html:
<button id="changer">Changer button</button>
<div id="text"> </div>
"Changer" is the button element in html, "text" is the div tag in which our text will be placed.
var selector = 0;
We set the selector to 0. Next, every time the button "changer" is clicked, we add 1 to the selector var, unless it has reached its max value of 14, in which case we start over. And based on the selector value, we pick from the available text values.
document.getElementById("Changer").onclick = function () {
if (selector < 14) {
selector++;
}
else {
selector = 0;
selector++;
}
document.getElementById("text").innerHTML = text;
}
if (selector = 1 ){
text = "<p>this is text 1</p>";
if (selector = 2 ){
text = "<p>this is text 2</p>";
etc...
The problem is, the function upon being clicked jumps right to the last text value available. How do I fix this? Will add live example soon if needed.
Your are assigning the selector inside the if condition to a value.
if(selector = 1) {...
What you actually want to do is check if the selectors value is equal to something like so:
if(selector == 1) {...
But you do not need to repeat the check, you can simply do:
var selector = 0;
var btn = document.getElementById('changer');
var output = document.getElementById('text');
btn.addEventListener('click', function() {
if (selector < 14) {
selector++;
output.innerHTML = "<p>this is text " + selector + "</p>";
} else {
selector = 0;
output.innerHTML = "";
}
})
<button id="changer">Changer button</button>
<div id="text"> </div>

Adding numbers in span JavaScript

I have a button on my page with click counter as span (with class .counter). Once the button is clicked, +1 should be added to the counter (on page, not in console). How can I add 1 to the string in span, currently innerHTML is 0? I tried with the code below but it doesn't work, unfortunately. When I tried without parseInt, digits were added to a span so I got e.g. 011 instead of 2.
document.addEventListener("DOMContentLoaded", function () {
var counters = document.querySelectorAll(".counter");
var btn1 = document.getElementById("button1");
function btn1Count (event) {
parseInt(counters[0].innerHTML,10) += 1;
}
btn1.addEventListener("click", btn1Count);
});
Use parseInt but like :
counters[0].innerHTML = parseInt(counters[0].innerHTML,10) + 1;
NOTE : It'll be better to use textContent instead if you would just to append text (No html) :
counters[0].textContent = parseInt(counters[0].textContent,10) + 1;
Hope this helps.
var btn1 = document.getElementById("button1");
var counters = document.querySelectorAll(".counter");
btn1.addEventListener("click", btn1Count);
function btn1Count (event) {
counters[0].textContent = parseInt(counters[0].textContent) + 1;
}
<button id="button1">Button 1</button>
<br>
<span class='counter'>0</span>
Just change
counters[0].innerHTML = parseInt(counters[0].innerHTML,10) + 1;
you just didn't set the span content

Dynamical Calculator Javascript

It is a calculator which has spans from which I want to take a values(1,2,3, etc.) and two fields: First for displaying what user is typing and the second is for result of calculation.
The question how to get values so when I click on spans it will show it in the second field
Here is the code.
http://jsfiddle.net/ovesyan19/vb394983/2/
<span>(</span>
<span>)</span>
<span class="delete">←</span>
<span class="clear">C</span>
<span>7</span>
<span>8</span>
<span>9</span>
<span class="operator">÷</span>
....
JS:
var keys = document.querySelectorAll(".keys span");
keys.onclick = function(){
for (var i = 0; i < keys.length; i++) {
alert(keys[i].innerHTML);
};
}
var keys = document.querySelectorAll(".keys span");
for (var i = 0; i < keys.length; i++) {
keys[i].onclick = function(){
alert(this.innerHTML);
}
}
keys is a NodeList so you cannot attach the onclick on that. You need to attach it to each element in that list by doing the loop. To get the value you can then simple use this.innerHTML.
Fiddle
This should get you started.. you need to get the value of the span you are clicking and then append it into your result field. Lots more to get this calculator to work but this should get you pointed in the right direction.
Fiddle Update: http://jsfiddle.net/vb394983/3/
JavaScript (jQuery):
$(".keys").on("click","span",function(){
var clickedVal = $(this).text();
$(".display.result").append(clickedVal);
});
You can set a click event on the span elements if you use JQuery.
Eg:
$("span").click(
function(){
$("#calc").val($("#calc").val() + $(this).text());
});
See:
http://jsfiddle.net/vb394983/6/
That's just to answer your question but you should really give the numbers a class such as "valueSpan" and the operators a class such as "operatorSpan" and apply the events based on these classes so that the buttons behave as you'd expect a calculator to.
http://jsfiddle.net/vb394983/7/
var v="",
max_length=8,
register=document.getElementById("register");
// attach key events for numbers
var keys = document.querySelectorAll(".keys span");
for (var i = 0; l = keys.length, i < l; i++) {
keys[i].onclick = function(){
cal(this);
}
};
// magic display number and decimal, this formats like a cash register, modify for your own needs.
cal = function(e){
if (v.length === self.max_length) return;
v += e.innerHTML;
register.innerHTML = (parseInt(v) / 100).toFixed(2);
}
Using JQuery will make your life much easier:
$('.keys span').click(function() {
alert(this.innerHTML);
});

Javascript Add/Remove unique cloned div

I have a dropdown that I want to be cloned and have a unique id. I managed to do it and it works on my website.
I am trying to make a "x" button to removed added clones and I can't get it to work.
The javascript:
var counter = 1;
function addInput(divName, template){
if (counter == 5) {
document.getElementById("add_more_text").remove();
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = document.getElementById(divName).innerHTML;
document.getElementById(template).appendChild(newdiv);
counter++;
}
var selectElements = document.querySelectorAll('select');
for (var i = 0; i < selectElements.length; i++){
selectElements[i].id = 'id-' + i;
selectElements[i].name = 'category' + i;
}
}
function removeInput(divName, template){
document.getElementById(template).removeChild(divName);
counter--;
}
The html:
<div id="template">
<select name="category0"><option>hi</option></select>
x
</div>
<div id="add_more"></div>
+ Add more
DEMO
Any help is much appreciated!
Simpler to modify remove function as follows:
function removeInput(obj) {
if (obj.parentNode.className == 'added') {
obj.parentNode.parentNode.removeChild(obj.parentNode);
counter--;
}
}
And have a link in template like this:
x
Class added is to distinguish new clones that can be removed:
newdiv.className = 'added';
Demo: http://jsfiddle.net/rjXXa/2/
in your onClick property
x
you are passing template and add_more
And in the handler function
function removeInput(divName, template){
the parameters are in a different order, so divName will contain 'template' and template will contain 'add_more'. Even if you fix this,
document.getElementById(template).removeChild(divName); // will throw error
because the div#add_more is not a child of div#template.
For fixing this, you need to pass a reference to the clicked element, like the following
x
and in your function
function removeInput(anchor){
var clone = anchor.parentNode; // div containing the anchor
if(clone.id!='template'){ // make sure we're not removing the original template
clone.parentNode.removeChild(clone);
counter--;
}
}
as in this Fiddle
Update
It's better to remove the add more option from display using css and make it visible later than removing/appending it in DOM, as follows
change the following in addInput() function
if (counter > 4) {
document.getElementById("add_more_text").style.display='none';
}
and in removeInput() function add
if (counter < 5) {
document.getElementById("add_more_text").style.display='block';
}
as in this Fiddle

Categories

Resources