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
Related
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
What i want to do is....when the counter button is clicked....increment a span to see how many times its been clicked but also create a new counter with its own incrementor
I have it somewhat working but when i create a new button....the counter doesnt work
anyone help me out with what im missing?
this is also done in vanilla js and html
template:
<div class="container">
<button type="button" id="increase" onClick="increaseCounter()">click</button>
<span id="amount"></span>
</div>
JS:
var counter = 0
function increaseCounter() {
let button = document.getElementById("increase");
let span = document.getElementById("amount");
counter += 1;
span.innerHTML = counter;
createNewButton();
}
function createNewButton() {
let container = document.getElementsByClassName("container")[0];
let btn = document.createElement("button");
btn.innerHTML = "new button";
btn.id = "increase";
container.appendChild(btn);
let span = document.createElement("span");
span.innerHTML = 0;
span.id = "amount";
container.appendChild(span);
}
LINK: https://codepen.io/zomdar/pen/ZEGPxNP?editors=1011
Here is a few things you should look for:
1- The event listener is only affected to the first button you assign as it is an inline event listener. So new buttons won't have the event listener.
2- If you want to have a new span containing the amount everyone, you must have a different ID for each span (or set the innerHTML directly as I did) or it will be the same span changing.
Note - The ID attribute should be unique in the page, every time you create a button the same ID is attributed. You should use the class attribute (non-unique value) or a different ID every time (e.g. "amount"+counter)
function increaseCounter() {
let button = document.getElementById("increase");
let span = document.getElementById("amount");
counter += 1;
// span.innerHTML = counter;
createNewButton();
}
function createNewButton() {
let container = document.getElementsByClassName("container")[0];
let btn = document.createElement("button");
btn.innerHTML = "new button";
btn.id = "increase"; // UNIQUE ID !!!
btn.onclick = increaseCounter;
container.appendChild(btn);
let span = document.createElement("span");
span.innerHTML = counter;
span.id = "amount";
container.appendChild(span);
}
You can pass along the element that was clicked as a parameter of the increaseCounter function and then get the nextElementSibling of that (the span associated with it), grab the innerHTML (current count) of it, then increment it by 1. This will prevent you from having to fetch the elements by id (as mentioned in the answer by clota974, you want your id's to be unique). You were also missing adding the onclick function for the buttons you were creating as well.
References:
https://www.w3schools.com/jsref/prop_element_nextelementsibling.asp
https://www.w3schools.com/jsref/event_onclick.asp
Here's the example code:
function increaseCounter(el) {
/* increment the span associated with this button (nextElementSibling is the span) */
el.nextElementSibling.innerHTML = parseInt(el.nextElementSibling.innerHTML) + 1;
createNewButton();
}
function createNewButton() {
let container = document.getElementsByClassName("container")[0];
let btn = document.createElement("button");
btn.innerHTML = "new button";
btn.onclick = function() {
increaseCounter(this);
};
container.appendChild(btn);
let span = document.createElement("span");
span.innerHTML = 0;
container.appendChild(span);
}
<div class="container">
<button type="button" onClick="increaseCounter(this)">click</button>
<span>0</span>
</div>
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>
I have an html with a span like this:
<span class="className">0</span> and it should display: 0
The problem is, how could I add a value (e.g. when value is 2, it will become 3) to the span by clicking a button and by doing it using javascript.
You can modify the content of any HTMLElement using:
innerHTML
textContent
look at this snippet:
document.addEventListener("DOMContentLoaded", function(){
var button = document.querySelector("#mybutton");
var span = document.querySelector(".className");
button.onclick = function() {
span.textContent= parseInt(span.textContent, 10) + 1;
}
});
<span class="className">0</span>
<button id="mybutton">add</button>
EDIT: If you want to use onclick="" which I don't recommend, you could do something like this:
var myFunction = function() {
var span = document.querySelector(".className");
span.textContent= parseInt(span.textContent, 10) + 1;
}
<span class="className">0</span>
<button id="mybutton" onclick="myFunction()">add</button>
I've got this array:
var size = [small, medium, large];
and this element:
<div class="wp-one wp-two wp-small"></div>
How do I change the size class looping through the size array in JQuery on pressing a button? For example if the element has wp-small, change to wp-medium and so forth looping through the array.
.wp-small {
color: #f00;
}
.wp-medium {
color: #0f0;
}
.wp-large {
color: #00f;
}
<div class="wp-one wp-two wp-small">fdgbfbfnghn</div>
<button>CHANGE CLASS</button>
You can do something like this:
var size = ['small', 'medium', 'large'];
var button = document.getElementById("button");
var id= document.getElementById("sentence");
var i = 0;
button.onclick = function(){
sentence.classList.remove("wp-"+size[i]);
(i == size.length - 1) ? i = 0 : i++;
sentence.classList.add("wp-"+size[i]);
}
JSFiddle
It could probably be tidied up but I'm no JS Wizard.
Basically, the first 4 lines are just me putting stuff into variables. Simple stuff.
I then make a function that on the click of button, it removes the class from the element that is current in the size array. It then checks to see what number the i is at (starting at 0) and if it's larger than the length of size, it resets back to the beginning, if not, it goes to the next array element.
It can be done in jQuery too:
$(document).ready(function(){
var size = ['small', 'medium', 'large'],
button = $("#button"),
sentence= $("#sentence"),
i = 0;
button.click(function(){
sentence.removeClass("wp-"+size[i]);
(i == size.length - 1) ? i = 0 : i++;
sentence.addClass("wp-"+size[i]);
});
});
JSFiddle
But will be faster and just as simple in pure JavaScript
is that what you need ?
var state = 0;
var size = ['small', 'medium', 'large'];
btn = document.getElementById('changeSize');
div = document.getElementById('btn');
btn.addEventListener('click', function() {
state = state == size.length - 1 ? 0 : state + 1;
btn.className = 'wp-' + size[state];
});
JSFiddle
You could add this jQuery code:
$(function(){
currSize = 0;
maxSize = (size.length - 1);
$('button').on('click', function(){
$('.wp-one').removeClass('wp-'+size[currSize]);
if (currSize < maxSize){
currSize++;
}
else{
currSize = 0;
}
$('.wp-one').addClass('wp-'+size[currSize]);
});
});
I am not sure what you are trying to accomplish. Do you want to alter through the availyble sizes, so that a wp-small element will be a wp-medium element and so on? And large ones will be small again?
If so try this:
buttonclickHandler = function(e) {
for(i=size.length;i>0;i--) {
var nextIndex = i % size.length;
$(".wp-" + size[i-1]).switchClass(".wp-" + size[i-1],".wp-" + size[nextIndex]);
}
}
Although in this code you'd have the problem that large elements would be first changed to small elements and later on to medium elements (within one single click). So you'd have to remember those initially large ones and exclude them from the small-to-medium-changes.
Due to simplicity I did not include that in the code above.