<html>
<body>
<button onclick = 'click1()'> </button>
</body>
<script>
var one
function click1(){
one = one + 1;
}
if (one == 3){
document.write('yes')
}
</script>
</html>
Here is an example JS / HTML. How can I write yes if the button is clicked three times?. This code would work in python and other languages. How can I do this in JS?
Your code have syntax and logical errors
<html>
<body>
<button onclick='click1()'>click here </button>
<script>
var one = 0;
function click1(){
one = one + 1;
if (one == 3){
alert("here");
}
}
</script>
</body>
</html>
after three clicks you will again have to reset variable one in if statement
if (one == 3){
alert("here");
one = 0;
}
There are multiple issues here.
First of all you should set a default to the variable, otherwise it will be declared as undefined.
Second you should put your if in the same function.
Third you should call your functions with the brackets in your html => 'click1()'
I also recommend making some changes
make your variable a let instead of a var.
use typesafe checks with 3 equal signs
<html>
<body>
<button onclick = 'click1()'> </button>
<script>
let one = 0;
function click1(){
one += 1;
if (one === 3){
document.write('yes')
}
}
</script>
</body>
</html>
var one = 0;
function click1() {
one++
if (one == 3) {
console.log('yes');
one = 0
}
}
<button onclick ='click1()'> </button>
Change your code like this:
<html>
<body>
<button onclick="click1()">Click</button>
</body>
<script>
var one = 0;
const click1 = () => { if (++one === 3) document.write('yes') };
</script>
</html>
Looks like you're missing the brackets on the function call on your button. Try: onclick='click1()'
You could use an approach like below. See the code comments for details:
// Reference to the DOM elements
const countEl = document.querySelector('#count-el');
const buttonEl = document.querySelector('button');
// Init a counter variable and return a function that increments it
const increment = (() => {
let i = 1;
return () => i++;
})();
// The click event listener
buttonEl.addEventListener('click', () => {
// Increment the count and update the UI based on if current click count is 3
if (increment() === 3) {
countEl.textContent = 'yes';
}
});
<span id="count-el"></span>
<br />
<button>Click 3 times</button>
Related
I have a form that counts when a button (button.clicked in the example below) is clicked. I want to make it operate in two modes: one keeps counting with every click, the other has a timer (started with the click of another button, button.start) that will disable the click-count button when the timer runs out. Each mode is chosen by clicking a button (button.menu-timer and button.menu-clicks). When the count mode is selected, one function (cc) is called. When switched to the timer mode, another function (tt) should be called and the first function should stop.
If I click one mode button, then everything works as it should, but if after that I click the other mode button, both functions continue to operate; each click of button.click adds two to the count. Moreover, if you click the mode buttons several times, clicking the count button will increase the counter many times, rather than only once.
I searched for solutions on the Internet and found one based on return; I tried to use return in various ways but couldn't get it to work.
I need that when choosing the right mode, only the desired function works. And so that when you click several times on one mode, the function will run once.
The following snippet is also available on CodePen.
let clicker = document.querySelector(".click");
let start = document.querySelector(".start");
let clickerValue = document.querySelector(".click").value;
const reset = document.querySelector(".reset");
const menuTimer = document.querySelector(".menu-timer");
const menuClicks = document.querySelector(".menu-clicks");
const times = document.querySelectorAll(".time");
let i = 0;
let y;
let tf;
let timer = 15;
function tt(tf) {
if (tf ===2) {
return;
}
start.addEventListener("click", () => {
start.style.zIndex = "-1";
y = setInterval(() => {
if (i === timer) {
clicker.setAttribute("disabled", "");
} else {
i++;
}
}, 1000);
});
clicker.addEventListener("click", () => {
clicker.textContent = clickerValue++;
});
reset.addEventListener("click", resetF);
}
function cc(tf) {
if (tf = 1) {
return;
}
start.addEventListener("click", () => {
console.log("111111");
start.style.zIndex = "-1";
});
clicker.addEventListener("click", () => {
clicker.textContent = `a ${clickerValue++}`;
});
reset.addEventListener("click", resetF);
}
function resetF() {
clearInterval(y);
i = 0;
start.style.zIndex = "2";
clickerValue = 0;
clicker.textContent = clickerValue;
clicker.removeAttribute("disabled", "");
}
menuTimer.addEventListener("click", function () {
menuTimer.classList.add("active");
menuClicks.classList.remove("active");
tt(1);
resetF();
});
menuClicks.addEventListener("click", function () {
menuClicks.classList.add("active");
menuTimer.classList.remove("active");
cc(2)
resetF();
});
<div class="menu">
<button type="button" onclick="tf = 1" class="menu-timer">TIMER</button>
<button type="button" onclick="tf = 2" class="menu-clicks">CLICKS</button>
</div>
<div class="click-btn">
<button class="click" type="button">0</button>
<button class="start" type="button">START</button>
</div>
<button class="reset" type="button">Reset</button>
You have a typo with assigning = instead of equality operator ===
function cc(tf) {
if (tf = 1) { // should be ===
return;
}
...
}
Also before you addEventListener('click', ...), a good practice is to remove previous click listeners with removeEventListener('click')
I'm struggling with this assignment: Pin an event listener to the buttons.
Create a function that gets called when one of the buttons is clicked. Check this with a console.log. Make sure the click event is passed to this function.
Make sure you have access to the value of the button clicked in this function. Check this with console.log. The outcome you want to see in the console when you click is: Leopard / Lion / Elephant / Rhino or Buffalo.
fiveButtons = document.getElementsByClassName("big-five-button");
for (var i = 0; i < fiveButtons.length; i++) {
fiveButtons[i].addEventListener("click", function () {
Array.from(fiveButtons).forEach(function (nameButton) {
console.log(nameButton.innerHTML);
})
});
}
This is what I wrote so far. When I'm clicking the button now, the outcome is the text from all the buttons. While I want the outcome to only be "Lion" after the button lion has been clicked.
<h1>The Big Five</h1>
<ul class="big-five-list">
<li class="big-five-list-item">
<button class="big-five-button">Lion</button>
</li> etc.
when creating an addEventListener you can use the event object to target the element clicked, like this:
fiveButtons[i].addEventListener("click", function (event) {
console.log(event.target.innerHTML);
});
You can change the button to include an onclick function like the below:
https://www.w3schools.com/jsref/event_onclick.asp
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction('Lion')">Lion</button>
<input type="text" value="" id="getValue">
<p id="demo"></p>
<script>
function myFunction(value) {
document.getElementById("getValue").value = value;
}
</script>
</body>
</html>
The onclick function will then have a value inside the () for the function name. This will pass the value you want across to the function and it can be called whatever you want. The above snippet shows an example of how it can be used
Try this solution!
fiveButtons = document.getElementsByClassName("big-five-button");
for (var i = 0; i < fiveButtons.length; i++) {
fiveButtons[i].addEventListener("click", function (item) {
console.log(item.target.innerHTML);
});
}
The function you pass to addEventListener gives an event argument:
fiveButtons = document.getElementsByClassName("big-five-button");
for (var i = 0; i < fiveButtons.length; i++) {
fiveButtons[i].addEventListener("click", function (event) { // use the first argument
console.log('element value:', event.target.value); // log the 'value' of the event target;
// I suspect you want the innerHTML or innerText
console.log('element innerText:', event.target.innerText);
});
}
You can then get the required information from the DOM node in event.target
You don't need the Array.from inside the for loop. You can just do that:
fiveButtons = document.getElementsByClassName("big-five-button");
for (let i = 0; i < fiveButtons.length; i++) {
fiveButtons[i].addEventListener("click", function () {
console.log(fiveButtons[i].innerText);
});
}
EDITED
// Get all the buttons
const fiveButtons = document.getElementsByClassName("big-five-button");
// Iterate through the collection of buttons
// Here is let i = 0 instead of var i = 0, since var has functional scope and let has block scope
// If we used var i = 0 it would not work implicitly because i would exist in the scope of a function,
// and all the event handlers (for each button) would share the same value of i
for (let i = 0; i < fiveButtons.length; i++) {
// For each button register event handler
fiveButtons[i].addEventListener("click", _ => {
// When button is clicked this part of a code is being called
// Because of javascript CLOSURE, it remembers the i value
console.log(fiveButtons[i].innerHTML)
});
}
If this is not understandable please read about closures in javascript.
I have similar problem in my main project. Down below I shown my problem to the simplified way. I know why my code in executing couple times, the question is how to repair this.
HTML Code:
<body>
<button id="btn">CLICK ME</button>
<script src="index.js" defer></script>
</body>
Javascript:
const btn = document.getElementById("btn");
var number = 1;
function load() {
console.log(number);
btn.addEventListener('click', (e) => add(e))
};
function add(e) {
number += 1;
load();
e.stopPropation();
}
load();
And of course when I click the button first time everything is fine, but when I click second time, the button executes function two times, after third click four times and so on. I thought that e.stopPropation(); will solve the problem, but unfortunately is not.
Main Question:
How to kill events which are doubled?
here use this
const btn = document.getElementById("btn");
var number = 1;
function load() {
console.log(number);
btn.addEventListener("click", (e) => add(e));
}
function add(e) {
number += 1;
load();
e.stopImmediatePropagation();
}
load();
The variables in this Javascript code represent buttons that once they have been clicked will trigger an animation within a function to be determined later. For the animation to be triggered, all 5 buttons need to be clicked. That’s the part I am struggling with. The code represents the most I have been able to do so far (not very good at javascript). Can anyone point me in the right direction to solve this issue?
<script>
var homework= document.getElementById("homerwork");
var teeth= document.getElementById("teeth");
var reading= document.getElementById("reading");
var stuff= document.getElementById("stuff");
var good= document.getElementById("good");
homework.addEventListener("click", rightclick);
teehth.addEventListener("click",righclick);
reading.addEventListener("click", righclick);
stuff.addEventListener("click", righclick);
good.addEventListener("click", rigclick);
function rightclicks () {
//function that will trigger the animation//
}
</script>
It is not clear exactly what you want. If you want your function triggered within certain time interval, there is a js method setInterval();.
For example:
var a = function(){
if (current === sliderImages.length - 1) {
current = -1;
}
slideRight();
}
setInterval(a, 3000);
The code above triggers the function every 3 seconds.
You made some spelling errors(such as, function name). Added the runnable code. Here, all buttons are calling the same rightclick method. Hope this will help you to begin with.
var homework= document.getElementById("homerwork");
var teeth = document.getElementById("teeth");
var reading= document.getElementById("reading");
var stuff= document.getElementById("stuff");
var good= document.getElementById("good");
homework.addEventListener("click", rightclick);
teeth.addEventListener("click", rightclick);
reading.addEventListener("click", rightclick);
stuff.addEventListener("click", rightclick);
good.addEventListener("click", rightclick);
function rightclick () {
alert('hi');
// function that will trigger the animation
}
<html>
<head>
<title>Sample page</title>
</head>
<body>
<div class="wrapper">
<button id="homerwork">Homework</button>
<button id="teeth">Teeth</button>
<button id="reading">Reading</button>
<button id="stuff">Stuff</button>
<button id="good">good</button>
</div>
</body>
</html>
Set an attribute clicked of each html element in the click event handler. Then, check if each button has the attribute 'clicked', and if so call rightClicks()
Something like
var ids = ['homework', 'teeth', 'etc'];
function rightClick(event) {
event.target.clicked = true;
var allClicked = true;
for (var i = 0; i < ids.length; i++) {
var el = document.getElementById(ids[i]);
if (!document.getElementById(ids[i]).attr('checked')) {
allClicked = false;
}
}
if (allClicked) {
rightClicks();
}
}
I'm sure there is a simpler or superior way of doing this, but by building off of your original code snip—firstly fixing typos, second adding to the rightclick() function—I've created a solution only using Vanilla JS. Hopefully this gives you something to work with!
var homework= document.getElementById("homerwork");
var teeth= document.getElementById("teeth");
var reading= document.getElementById("reading");
var stuff= document.getElementById("stuff");
var good= document.getElementById("good");
homework.addEventListener("click", rightclick);
teeth.addEventListener("click", rightclick);
reading.addEventListener("click", rightclick);
stuff.addEventListener("click", rightclick);
good.addEventListener("click", rightclick);
function rightclick () {
this.setAttribute("clicked", true);
var buttons = document.getElementsByClassName("btns");
var numButtons = buttons.length;
var boolArray = [];
for(var key in buttons){
if(buttons[key].tagName == "BUTTON"){
boolArray.push(buttons[key].getAttribute("clicked"));
};
};
if(boolArray.length===numButtons){
if(boolArray.includes("false")){
return;
} else {
alert("all buttons clicked. go ahead with animation");
}
};
};
<html>
<head>
<title>Sample page</title>
</head>
<body>
<div>
<button class="btns" id="homerwork" clicked=false>Homework</button>
<button class="btns" id="teeth" clicked=false>Teeth</button>
<button class="btns" id="reading" clicked=false>Reading</button>
<button class="btns" id="stuff" clicked=false>Stuff</button>
<button class="btns" id="good" clicked=false>good</button>
</div>
</body>
</html>
OK so I am making a reaction tester, and I have a function that makes shapes appear on screen, So what I want is some sort of function were after 5 clicks on a certain element it will end a function. Is there a way of doing that? sorry if its a dumb question, its because I am new to the whole coding...
Here you go
var clickHandler = (function (e) {
var count = 0;
return function () {
count += 1;
if (count > 5) {
return;
}
// do other stuff here
}
}());
aDiv.addEventListener('click', clickHandler, false);
You Can use static variable to count how many times the object has been clicked.
and here is how you can create static variable in javascript.
You can unbind the click event once the counter reaches 5. See the example below
function test(sender) {
sender.dataset.clicked++;
console.log("I've been clicked", sender.dataset.clicked);
if (+sender.dataset.clicked === 5) {
// unbind the event
sender.onclick = null;
}
return;
}
<div onclick="test(this);" data-clicked="0">click me</div>
You may use global variable which may remain counting on click function
<script>
var globalvar = 0;
onclickfunct()
{
globalvar += 1;
if(globalvar == 5)
{
//do my work
}
else
{
//give alert
}
}
</script>