javascript - change function onclick button (using another function) - javascript

I want to make simple clicking game, but I have a problem. Let's say I have this:
var clicks = 0;
function somefunction() {
clicks++;
}
<button onclick="somefunction()">BUTTON 1</button>
<button onclick="anothfunction()">BUTTON 2</button>
and here comes the problem. I want to count clicks on BUTTON 1, but after clicking on BUTTON 2. It will count one click as two clicks.
Thank you in advance. ;-)

Have the second button set a variable that's used by the first function.
var clicks = 0;
var increment = 1;
function somefunction() {
clicks += increment;
console.log(clicks);
}
function anothfunction() {
increment = 2;
}
<button onclick="somefunction()">BUTTON 1</button>
<button onclick="anothfunction()">BUTTON 2</button>

Related

Unable to get button value into function

Working on TOD calculator project.
While I likely have other potential errors in my code, I am only seeking to understand getting the button number/value into the function.
I think I need to get the button value assigned so that the
xyz function can process it. Is it even necessary to add the value attribute to a CSS button in this instance?
<div class="row4">
<button class="btn" value="7">7</button>
<button class="btn" value="8">8</button>
<button class="btn" value="9">9</button>
<button class="btn" value="*">*</button>
</div>
let buttons = document.getElementsByClassName("btn");
for (let i = 0; i < buttons.length; i += 1) {
buttons[i].addEventListener("click", xyz);
function xyz(x) {
let nbr1 = "0";
let operator = "";
let nbr2 = "0";
const sum = maths(nbr1, operator, nbr2);
if (x == "=") button.value = sum;
if (x == "+" || "-" || "*" || "/") x = operator;
if (operator == null) x = nbr1;
else x = nbr2;
console.log(nbr1, operator, nbr2);
}
}
document.getElementsByClassName("btn").value causes an
uncaught typeError: buttons is undefined
Without .values the function runs without errors, but none
of the values get assigned.
I have tried:
getAttributes(‘value’) and get: "not a function" typeError.
a number of different iterations in the (xyz) of lines such as: x, buttons, buttons.value etc.
First of all, you are redefining the function in every iteration of the loop (not necessary and not optimal). Just define the function before you start the loop.
The event handler will be passed the event object as the parameter. The event.target points to the actual clicked-on element which may be a child of the button, while event.currentTarget will be the element the handler was assigned to (the button itself).
If you only have the button value nested inside it then you can use event.currentTarget.innerText instead of event.currentTarget.value to get the value attribute.
let buttons = document.getElementsByClassName("btn");
function xyz(event) {
const btnVal = event.currentTarget.innerText
console.log(btnVal);
}
for (let i = 0; i < buttons.length; i += 1) {
buttons[i].addEventListener("click", xyz);
}
<div class="row4">
<button class="btn">7</button>
<button class="btn">8</button>
<button class="btn">9</button>
<button class="btn">*</button>
</div>

hiding a button in html [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
I want to hide a button on the click of another button. So i checked some questions on stack overflow . I used display property and assigned it to hidden. And now I want to unhide it on the click of another button.
I want to increment variable "a" on the click of button1. and when the variable a is greater or equal to three i want to unhide 'button' (The button which has id #again) which is hidden. That means after clicking in button1 twice i want to unhide the button. But It is not working. No mater how many times i click in the button1, it is not working.I used display property and made it to hidden in the html file.
Could anybody say what i want to do here in order to unhide the button when clicked on the button1 twice.
let a = 1;
let button = document.querySelector("#again");
let button1 = document.querySelector("#again1");
button1.onclick = () => {
a++;
}
if (a >= 3) {
button.style.display = "block";
}
<button id="again" style="display:none;">click me</button>
<button id="again1">here</button>
<script src="practise.js"></script>
Your if block is calculated just once in the beginning when the browser parses through the js file. Instead, you want to check it every time button1 is clicked. Move it inside the event listener.
let a = 1;
let button = document.querySelector("#again");
let button1 = document.querySelector("#again1");
button1.onclick = () => {
a++
if (a >= 3) {
button.style.display = "block";
}
}
<button id="again" style="display:none;">click me</button>
<button id="again1">here</button>
spelling onclick
if needs to go inside the function
let a = 1;
let button = document.querySelector("#again");
let button1 = document.querySelector("#again1");
button1.onclick = () => {
a++;
if (a >= 3) {
button.style.display = "block";
}
}
<button id="again" style="display:none;">click me</button>
<button id="again1">here</button>
<script src="practise.js"></script>
Alternative using eventListener and hidden
let a = 1;
let button = document.querySelector("#again");
let button1 = document.querySelector("#again1");
button1.addEventListener("click", () => {
a++;
button.hidden = a < 3
})
<button id="again" hidden>click me</button>
<button id="again1">here</button>
<script src="practise.js"></script>
Just put the if condition inside the onClick() function .
let a = 1;
let button = document.querySelector("#again");
let button1 = document.querySelector("#again1");
button1.onclick = () => {
a++
if (a > 2) {
button.style.display = "block";
}
}
<button id="again" style="display:none;">click me</button>
<button id="again1">here</button>
Try this simple:
var button = document.getElementById("again1")
let button1 = document.querySelector("#again");
count = 0;
button.onclick = function() {
count += 1;
if (count >= 3) {
button1.style.display = "block";
}
button.innerHTML = "Click me: " + count;
};
<button id="again" style="display:none;">click me</button>
<button id="again1">here</button>
Here in the above responses 'display: hidden' means it will occupy the space in UI where as 'display: none' means it won't occupy the space. Now you can decide which one to use as well

Why is addEventListener increment code not working?

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.

Vanilla Javascript : how to make a button clickable once only

I have a quiz app application that I am working on that dynamically creates 2-4 buttons for the answer. However, if you click on an answer, you can keep clicking on the same answer or keep clicking the other answers. I want the user to be able to click one of the buttons but then not be able to keep clicking. caveat though: when a user clicks one of the buttons, a new "Next" button gets created and that one does still need it's click event.
tl;dr
I need dynamically created buttons to be clickable only once but a "Next" button to still be clickable.
Code:
function renderButtons() {
var answerContainer = document.getElementById("answer-buttons");
answerContainer.innerHTML = "";
for (var i = 0; i < 4; i++) {
var button = document.createElement("button");
button.classList.add("btn");
button.setAttribute("id", "answerBtns");
button.hasAttribute("data-correct");
button.setAttribute("data-correct", questions[count].answers[i].correct);
button.onclick = btnclick;
button.textContent = questions[count].answers[i].text;
answerContainer.appendChild(button);
}
}
// if user clicks on button check if true
function btnclick(e) {
e.preventDefault();
var value = event.target.dataset.correct;
scoreBox.textContent = "Score: " + score;
if (value === "true") {
score += 5;
document.body.style.background = "green";
} else {
document.body.style.background = "red";
}
var next = document.getElementById("answer-buttons");
var nextBtn = document.createElement("button");
nextBtn.classList.add("nextBtn");
nextBtn.textContent = "Next";
next.appendChild(nextBtn);
nextBtn.onclick = nextBtnFx;
if you want to see what I'm talking about, the app can be found here:
https://andrethetallguy.github.io/Animal-Quiz/
Thanks!!!
In the handler function nextBtnFx you could disable the button with
this.disabled = "true"
that would make it unclickable after the first click
ref: https://stackoverflow.com/a/17115132/13998159
<!DOCTYPE html>
<html>
<head>
<title>Button</title>
</head>
<body>
<input type="button" id="btn01" value="OK">
<button onclick="disableElement()">Disable</button>
<button onclick="enableElement()">Enable</button>
<script>
function disableElement() {
document.getElementById("btn01").disabled = true;
}
function enableElement() {
document.getElementById("btn01").disabled = false;
}
</script>
</body>
</html>
You can use these functions to disable/enable the buttons.

On each click new button has been created. How should I create same functionality for new created buttons

var clicks = 0;
function clickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
var btn = document.createElement("BUTTON");
var t = document.createTextNode(clicks);
btn.setAttribute("onClick", clicks);
btn.appendChild(t);
document.body.appendChild(btn);
}
<button type="button" onClick="clickME(**strong text**)">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
This is the code that created new button with the counter. Now I want to implement same functionality for each of the new buttons. Please guide me.
The problem is in this line
btn.setAttribute("onClick", clicks);
clicks is a variable which counts the clicks, not a function. You want to instead assign the function to the new button, like this:
btn.onclick = clickME;
Here's the code: https://codesandbox.io/s/still-frog-0qust

Categories