the counter number is not updating even after clicking the button.
var counterNumber = 0;
var counterText = document.querySelector("strong");
var reduceButton = document.querySelectorAll("button")[0];
var increaseButton = document.querySelectorAll("button")[1];
increaseButton.addEventListener("click", function() {
counterNumber++;
})
reduceButton.addEventListener("click", function() {
counterNumber--;
})
counterText.textContent = counterNumber;
Your eventListener acts on the button clicks and counterNumber are increased as it should (you can add a console.log to see this) But you never assign the new value to your text counterText. That row is run once and not everytime you click a button.
Move this row:
counterText.textContent = counterNumber;
to be within your eventListener functions
Related
Trying to make it so this counter with buttons increases or decreases based on clicks, however on the first click the counter doesn't increase. If I do + 1 it will but then will stop. ++works but only after first click. Trying to learn easy way to resolve my code that isn't a drastic change.
https://jsfiddle.net/sy0ohtrc/
var pageCount = 1;
var elPage = document.getElementById("currentPage");
elPage.innerHTML = pageCount;
//Get next button and add connect function on click
var elNext = document.getElementById("nextButton");
elNext.addEventListener("click", nextPage);
function nextPage() {
var elPageIncrease = document.getElementById("currentPage");
elPageIncrease.innerHTML = pageCount++;
}
var elPrev = document.getElementById("prevButton");
elPrev.addEventListener("click", prevPage);
function prevPage() {
var elPageDecrease = document.getElementById("currentPage");
elPageDecrease.innerHTML = pageCount--;
}
You should use --/++ before the counter because when you use the increment/decrement operator after, the value will be returned before the it increased/decreased.
AND there is no need for declaring 3 time the same element.
Finally change the innerHTML to textContent (and if you want to know why read this thread).
Your code should look something like that:
var pageCount = 1;
var elPage = document.getElementById("currentPage");
elPage.textContent = pageCount;
//Get next button and add connect function on click
var elNext = document.getElementById("nextButton");
elNext.addEventListener("click", nextPage);
function nextPage() {
// var elPageIncrease = document.getElementById("currentPage"); you have elPage already pointing this element
elPage.textContent = ++pageCount;
}
var elPrev = document.getElementById("prevButton");
elPrev.addEventListener("click", prevPage);
function prevPage() {
// var elPageDecrease = document.getElementById("currentPage"); you have elPage already pointing this element
elPage.textContent = --pageCount;
}
<div class="pager">
<button id="prevButton">prev</button>
<p class="pageNumber" id="currentPage"></p>
<button id="nextButton">next</button>
</div>
So I have this blueprint object:
function User (theName, theEmail) {
this.name = theName;
this.email = theEmail;
this.quizScores = [];
this.currentScore = 0;
}
I create a new user like this var user1 = new User (theName.value, theEmail.value); which is inside a function for event listener when user types in his name and email. Now there are questions and a button for next question. Everytime user clicks next question button, I want to increment currentScore by one. Problem is that it stays 0 all the time. I do it like this:
scoretag = document.createElement("p");
scoretag.innerHTML = user1.currentScore;
body.appendChild(scoretag);
Event listener and main loop:
for (var i = 0; i < theChoices[question1.theChoices].length; i++) {
var arrayQ = document.createElement("p");
arrayQ.innerHTML = theChoices[question1.theChoices][i];
list.appendChild(arrayQ);
var radio = document.createElement("input");
radio.type = "radio";
listOptions.appendChild(radio);
dbtn.addEventListener("click", function() {
//list.removeChild(arrayQ);
//listOptions.removeChild
list.removeChild(list.firstChild);
list.removeChild(list.lastChild);
user1.currentScore = user1.currentScore+1;
scoretag = document.createElement("p");
scoretag.innerHTML = user1.currentScore;
body.appendChild(scoretag);
})
}
UPDATE: I putted the code for appending a child to a body element inside the loop after incrementation of score, but this results in many numbers printed on the page one after another.
But like I said, when I try t increment by one on button click, it still keeps showing 0 on the screen. Any help?
Every time you increment the score, you need to update the HTML element. This is an idea:
function User (theName, theEmail) {
this.name = theName;
this.email = theEmail;
this.quizScores = [];
this.currentScore = 0;
}
var user1 = new User ("aa","bb");
function updateScore(){
user1.currentScore++;
document.getElementById('score').innerText = user1.currentScore;
}
<button id="btn" onclick="updateScore()">next</button>
<p id="score">0</p>
I have an event listener that is listening for a click event inside of a media query, if when the window is under 500px. Likewise I have one that is listening for a click event if the window is wider than 500px.
Once the buttons have been clicked within both states, the code works as I would like. However I have the following issue I would like to solve:
When the window is smaller than 500px and the button is clicked it displays the content as required, though when the window is dragged to be wider than 500px, the button then needs to be clicked again to show the content.
As I say this works fine once buttons have been clicked when the window is wider than 500px and then again under 500px, the correct content shows when the window is dragged back and forth.
What I would like to know is how to do the following:
When the button is clicked when the window is under 500px and then dragged out, the corresponding content is displayed without having to press the button again. I also want this to be the case when the window is wider than 500px and dragged to below this value.
Please see the JSFiddle here
Is there a way to somehow make an eventlistener for the element that has already been clicked and do it this way?
//Start listing variables for use in array.
var art1 = document.getElementById("article1");
var button1 = document.getElementById("btn1");
var art2 = document.getElementById("article2");
var button2 = document.getElementById("btn2");
var art3 = document.getElementById("article3");
var button3 = document.getElementById("btn3");
var articleArray = [art1, art2, art3];
var buttonArray = [button1, button2, button3];
function mediaQuery(x) {
//If window is under 500px in width.
if (x.matches) {
//Begin accordion code
var initAccordion = function(accordionElement) {
function handlePanelClick(event) {
showPanel(event.currentTarget);
}
function showPanel(panel) {
var expandedPanel = accordionElement.querySelector(".active");
if (expandedPanel) {
expandedPanel.classList.remove("active");
}
panel.classList.add("active");
}
var allPanelElements = accordionElement.querySelectorAll(".panel");
for (var y = 0; y < allPanelElements.length; y++) {
allPanelElements[y].addEventListener("click", handlePanelClick);
}
//showPanel(allPanelElements[0]);
}
initAccordion(document.getElementById("contentWrapper"));
} else { // If window if is over 500px in width.
//Begin button code.
var createfunc = function(i) {
return function() {
document.getElementById("fillMe").innerHTML = articleArray[i].innerHTML;
};
}
for (let i = 0; i < articleArray.length; i++) {
let button = buttonArray[i];
button.addEventListener("click", createfunc(i));
}
}
}
//Declare media query and add listener.
var x = window.matchMedia("(max-width: 500px)")
mediaQuery(x) // Call listener function at run time
x.addListener(mediaQuery) // Attach listener function on state changes
I have many <div> each containing another div that's my button. I have an .one('click', '.button', function(){}); that activates on each click and increments a number in a single div elsewhere.
var barPrimC = 25;
var barPrimN = 6;
var barPrimS = 5;
var barPrimT = 48;
var barSecMajC = 11;
var barSecMajN = 2;
var barSecMajS = 3;
var barSecMajT = 19;
var incSL
$('.complete, .incomplete').click(function() {
$('.classInfo').slideUp();
if($(this).next().is(':hidden') == true) {
$(this).addClass('on');
$(this).next().show('slow');
incSL = this;
// ADD to List
$(".shortAdd").one('click','.button', function(){
$(this).text('Remove from Short List');
$(this).parent().attr("class", "shortRemove");
$(incSL).attr("class", "incompleteSL");
$('.classInfo').slideUp();
barPrimS++;
barSecMajS++;
var updateBarP = $(".bpS").find(".b-text-right").text(barPrimS);
var cat = $(this).data("category");
var catBar = $("."+cat).find(".bCommonS");
var updateBarS = catBar.filter(".bsS").find(".s-text-right").text(barSecMajS);
});
// REMOVE from List
$(".shortRemove").one('click','.button', function(){
$(this).text('Add to Short List');
$(this).parent().attr("class", "shortAdd");
$(incSL).attr("class", "incomplete");
$('.classInfo').slideUp();
barPrimS--;
barSecMajS--;
var updateBarP = $(".bpS").find(".b-text-right").text(barPrimS);
var cat = $(this).data("category");
var catBar = $("."+cat).find(".bCommonS");
var updateBarS = catBar.filter(".bsS").find(".s-text-right").text(barSecMajS);
});
}
});
I was originally using .on but it was activating both of my methods (for ADD and REMOVE clicks).
If I have :
<div>1st time div CLICKED (runs 1 time)</div>
<div>2nd time div CLICKED (runs 2 times)</div>
<div>3rd time div CLICKED (runs 3 times)</div>
<div>4th time div CLICKED (runs 4 times)</div>
So basically if barPrimS starts off at 5, it goes to 6 when the add click method is ran. When a separate add click method is ran, it goes to 8. Then to 11 then to 15.
I can't figure out why this is happening, please help! Should increment by only 1 (5, 6, 7, 8). I've tried barPrimS = barPrimS + 1 and other ways, but they all do the same.
I ended up removing the .shortAdd and .shortRemove .on('click') methods from within the parent click even, as suggested, and didn't nest them. I then combined the short and add as an if/else statement under the .shortAdd and simply .toggleClass() with the .shortRemove class, checking to see if it existed.
This fixed all errors for me.
I have the following js code:
function createConBox() {
var charDiv = document.getElementById("characterList"); // reference to "characterList" div
header = document.createElement("p"); // creates the <p> tag
charDiv.appendChild(header); // adds the <p> tag to the parent node
title = document.createTextNode("Show Only Lines By:"); // creates the text string
header.appendChild(title); // adds the text string to the parent node
// create select box and add elements
selectBox = document.createElement("select");
selectBox.setAttribute("id", "cList");
charDiv.appendChild(selectBox);
charNames = uniqueElemText("h3"); // array of character names
newOption = document.createElement("option");
selectBox.appendChild(newOption);
newOptionTitle = document.createTextNode("Show All Lines");
newOption.appendChild(newOptionTitle);
for (i = 0; i < charNames.length; i++) {
newOption = document.createElement("option");
selectBox.appendChild(newOption);
newOptionTitle = document.createTextNode(charNames[i]);
newOption.appendChild(newOptionTitle);
}
}
function showLines() {
alert("The Box has been changed");
}
Every time the option in the box is changed, I want it to call 'showLines()'. However, every time I try to implement an event, I can only get it to trigger when the page loads, and never again thereafter.
selectBox.onchange = showLines; should solve your problem.
in some browsers onchange get fired only after blurring select box. to over come this you can use onclick instead of onchange
My guess is that you're doing this:
selectBox.onchange = showLines();
If that's the case, just remove the ():
selectBox.onchange = showLines;
When I pass dynamically id in case then what I do:
var selectcell = tablerow.insertCell(1);
var selectelmt = document.createElement('select');
selectelmt.name = 'Select';
selectelmt.value = 'select';
selectelmt.classList = 'form-control input-sm cobclass';
selectelmt.onchange= onselectchange(i);
selectelmt.id = 'cobselect' + i;
selectelmt.options[0] = new Option('select');
selectcell.appendChild(selectelmt);
// ddrbind(i);
show();
i++;`