I have two buttons and a counter, I have to reset counter every time I change the button. I don't know how to reset the counter.
var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
function clickCount(){
count++;
display.innerHTML = count;
}
button1.onclick = function(){
clickCount();
count=0;
}
button2.onclick = function(){
clickCount();
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>
Pass a parameter to your clickCount function with the button name, and check if it has changed.
var count = 0;
var lastButtonClicked = "";
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
function clickCount(buttonName){
if (buttonName === lastButtonClicked)
{
count++;
}
else
{
count = 1;
lastButtonClicked = buttonName;
}
display.innerHTML = count;
}
button1.onclick = function(){
clickCount("1");
}
button2.onclick = function(){
clickCount("2");
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>
Just add the extra parameter that determines which button the counter is from.
var isFirstButton = true;
var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
function clickCount(){
count++;
display.innerHTML = count;
}
button1.onclick = function(){
if (!isFirstButton){
count = 0;
}
isFirstButton = true;
clickCount();
}
button2.onclick = function(){
if (isFirstButton){
count = 0;
}
isFirstButton = false;
clickCount();
}
I updated your original code, added a active button variable which is chosen from the event target, this way, it doesn't matter how many buttons you want to count, they will all be unique, and you don't need a variable for each one.
This is similar to [stephen.vakil] post, however with this code, you do not need to name the buttons, just use the DOM and event target to define the uniqueness.
var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
var activeTarget; // which target are we counting
function clickCount(e){
var e = e || window.event; // IE or other browser event
var target = e.target || e.srcElement; // target from different browsers
if(target != activeTarget) { // Is this the current target?
count = 0; // No, reset counter
activeTarget = target; // and make it the active target
}
count++; // No matter which target, incr counter
display.innerHTML = count; // and display result
}
button1.onclick = function(e) { // don't forget the event arg
clickCount(e); // and pass it to the count function
}
button2.onclick = function(e) { // same as above
clickCount(e);
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>
The reference for the source event target onclick calling object
Related
Here is my script written
I want to stop timer when user switch to different tabs and resume back when visit the site. can anyone help me to solve this task. Need To stop Timer counting down when browser tab focus or been switched between tabs can
anyone help me to this code
<div style="text-align: center;">
<a class="button" href="" id="download">Click To Download</a>
<button class="infoblogger" id="btn"> Download</button>
<script>
var downloadButton = document.getElementById("download");
var counter = 45;
var newElement = document.createElement("p");
newElement.innerHTML = "www.xyz.com";
var id;
downloadButton.parentNode.replaceChild(newElement, downloadButton)
function startDownload() {
this.style.display = 'none';
id = setInterval(function() {
counter--;
if (counter < 0) {
newElement.parentNode.replaceChild(downloadButton, newElement);
clearInterval(id);
} else {
newElement.innerHTML = +counter.toString() + " second.Please Wait";
}
}, 1000);
};
var clickbtn = document.getElementById("btn");
clickbtn.onclick = startDownload
</script>
</div>
1st : <script> tag is not used inside div element
2nd : You can use a extra variable and check its state to run the function.
Here used focusOut whose value is false, and value changes to true if window minimizes or out of focus(other tab opened) and change back to false if gains back the focus. This state is used to keep the function running.
var downloadButton = document.getElementById("download");
var counter = 45;
var newElement = document.createElement("p");
newElement.innerHTML = "www.xyz.com";
var id;
let focusOut = false;
downloadButton.parentNode.replaceChild(newElement, downloadButton)
function startDownload() {
this.style.display = 'none';
id = setInterval(function() {
if (!focusOut) {
counter--;
if (counter < 0) {
newElement.parentNode.replaceChild(downloadButton, newElement);
clearInterval(id);
} else {
newElement.innerHTML = +counter.toString() + " second.Please Wait";
}
}
}, 1000);
};
var clickbtn = document.getElementById("btn");
clickbtn.onclick = startDownload
window.addEventListener('blur', function() {
focusOut = true;
})
window.addEventListener('focus', function() {
focusOut = false;
});
<div style="text-align: center;">
<a class="button" href="" id="download">Click To Download</a>
<button class="infoblogger" id="btn"> Download</button>
</div>
<script>
</script>
I've got a problem with limited click counter using JavaScript. I have tried suggestions below but it seems like my problem might be somewhere else.
HTML/Javascript Button Click Counter
Basically I want to count clicks x times, which is provided from <input type="number"> field. It looks like the script is not recognizing this item in counting function.
Below I'd like to share example code:
function myFunction() {
var count = 0;
var number = document.getElementById("amount").value;
var btn = document.getElementById("clickme");
var disp = document.getElementById("clicked");
btn.onclick = function() {
count++;
disp.innerHTML = count;
}
if (count > number) {
btn.disabled = true;
}
}
<!DOCTYPE html>
<html>
<body>
<input type="number" id="amount">
<p>how many times button should be clicked</p>
<p>Click the button.</p>
<div id="clicked"></div>
<button id="clickme" onclick="myFunction()">Click me</button>
<script>
</script>
</body>
</html>
Just remove the surrounding function and the onclick attribute.
Also, move the value retrieval and the disabled logic inside the listener, and convert the value to a number:
let count = 0;
const btn = document.getElementById("clickme");
const disp = document.getElementById("clicked");
const amount = document.getElementById("amount");
btn.onclick = function () {
count++;
disp.innerHTML = count;
const number = +amount.value;
if (count > number) {
btn.disabled = true;
}
}
<input type="number" id="amount" >
<p>how many times button should be clicked</p>
<p>Click the button.</p>
<div id="clicked"></div>
<button id="clickme">Click me</button>
You can simply your solution using the snippet below.
let count = 0;
const inp = document.getElementById("amount");
const countEl = document.getElementById("clicked");
function myFunction(e) {
if (++count >= Number(inp.value)) e.target.disabled = true;
}
<input type="number" id="amount">
<p>How many times button should be clicked</p>
<p>Click the button.</p>
<button id="clickme" onclick="myFunction(event)">Click me</button>
I would recommend something like this. The limit can be increased or decreased at any time to allow for more or less clicks. Once it reaches 0, the button will stop adding to the count -
const f =
document.forms.myapp
function update (event) {
const limit = Number(f.limit.value)
if (limit <= 0) return
f.limit.value = limit - 1
f.count.value = Number(f.count.value) + 1
}
f.mybutton.addEventListener("click", update)
<form id="myapp">
<input type="number" name="limit" value="10">
<button type="button" name="mybutton">click me</button>
<output name="count">0</output>
</form>
I have managed to count the click events with the limit provided by <input type="number"> field and adding data to the array. Additioanlly, I am trying to decrease dynamically the amount of click events and remove last records from array using another button. Basically I have NAN value when I try to get counter value to decrease it.
It looks like this:
HTML code:
<!DOCTYPE html>
<html>
<body>
<input type="number" id="amount">
<p>how many times button should be clicked</p>
<p> Add question</p> <input type="text" id="question">
<p>Click the button.</p>
<div id="clicked"></div>
<button id="clickme" >add me</button>
<button id="delme">
delete me
</button>
</body>
</html>
JS code:
var count = 0;
var i=0;
const btn = document.getElementById("clickme");
const disp = document.getElementById("clicked");
var amount = document.getElementById("amount");
var question = document.getElementById("question");
var tab;
btn.onclick = function () {
count++;
disp.innerHTML = count;
var number = +amount.value;
tab=new Array(number);
tab[i]=question.value;
console.log(tab[i] + i);
question.value=" ";
i++;
if (count == number) {
btn.disabled = true;
}
}
var delbtn=document.getElementById("delme");
var countdown = parseInt(document.getElementById("clicked"));
delbtn.onclick = function () {
console.log(countdown);
countdown--;
disp.innerHTML = countdown;
if (countdown == 0) {
btn.disabled = true;
}
}
I am doing a practice that use location.hash to keep page's state, what i have done using the below code is
1.click any button, the button's innerHTML will be written into the div#cont
2.refresh the page, it keeps the changes in the div#cont
<body>
<button id="a">A</button>
<button id="b">B</button>
<button id="c">C</button>
<div id="cont"></div>
<script>
// var hashValue;
function getHash() {
var hashValue = location.hash;
return hashValue;
}
function draw() {
var cont = getHash();
if (cont) {
document.getElementById('cont').innerHTML = cont.slice(1);
}
}
btns = document.getElementsByTagName('button');
for (i = 0; i < btns.length; i++) {
btns[i].index = i;
btns[i].onclick = function() {
location.hash = btns[this.index].innerHTML;
}
}
window.onhashchange = function() {
draw();
}
draw();
</script>
</body>
And what i want to achieve next is add three other buttons(D,E,F) and a new div, when clicking one of the D\E\F, the innerHTMl will written into the new div.
The final goal is
click one of the A\B\C, the value will be written into 'contABC'
click one of the D\E\F, the value will be written into 'contDEF'
keep the changes when the page refresh
because this time it has to record two value, and i have no idea how to use hash to do that, anyone can help? Thanks in advance!
This is HTML:
<button id="a">A</button>
<button id="b">B</button>
<button id="c">C</button>
<button id="d">D</button>
<button id="e">E</button>
<button id="f">F</button>
<div id="contABC"></div>
<div id="contDEF"></div>
Try by structuring the way you store the hash value , like using a separator -
<body>
<button data-attr='ABC' id="a">A</button>
<button data-attr='ABC' id="b">B</button>
<button data-attr='ABC' id="c">C</button>
<button data-attr='DEF' id="d">D</button>
<button data-attr='DEF' id="e">E</button>
<button data-attr='DEF' id="f">F</button>
<div id="contABC"></div>
<div id="contDEF"></div>
<script>
// var hashValue;
function getHash() {
var hashValue = location.hash && location.hash.slice(1);
return hashValue && hashValue.split('-');
}
function draw() {
var cont = getHash();
if (cont && cont.length>0) {
document.getElementById('contABC').innerHTML = cont[0];
document.getElementById('contDEF').innerHTML = cont[1];
}
}
btns = document.getElementsByTagName('button');
var seperator = '-';
for (i = 0; i < btns.length; i++) {
btns[i].index = i;
btns[i].onclick = function() {
var cont = getHash() || [];
if(btns[this.index].dataset.attr=='ABC'){
location.hash = btns[this.index].innerHTML + seperator + cont[1];
}else{
location.hash = cont[0] + seperator + btns[this.index].innerHTML ;
}
}
}
window.onhashchange = function() {
draw();
}
draw();
</script>
</body>
enter image description hereI have a button that permit to add checkbox element dynamically,
function addCheck() {
var checkinput = document.createElement('input')
var form = document.getElementById('form')
check.setAttribute('type', 'checkbox')
check.setAttribute('name', 'check')
form.appendChild(checkinput)
}
I want to count how many the user created a new Element whenever he presses the button
var count=0;
function addCheck() {
let pos= document.getElementById("dynamic-checkbox");
var checkinput = document.createElement("input");
check.setAttribute("type", "checkbox");
check.setAttribute("name", "rep");
pos.appendChild(check);
count++;
Here's an alternative to using a counter variable, or checking the length of the number of existing elements in the DOM. You initially set up the counter element with the textContent set as zero, and then with each call of the function set that content to whatever the current content is (coerced from a string to a number) plus 1.
// Cache the elements we reuse
const form = document.querySelector('form');
const button = document.querySelector('button');
const counter = document.querySelector('#counter');
button.addEventListener('click', addCheck, false);
function addCheck() {
const checkinput = document.createElement('input');
checkinput.setAttribute('type', 'checkbox');
checkinput.setAttribute('name', 'check');
form.appendChild(checkinput);
counter.textContent = Number(counter.textContent) + 1;
}
<div id="counter">0</div>
<button>Add checkbox</button>
<form></form>
You can use querySelectorAll() by passing the input type as the selector and take the length:
var count = form.querySelectorAll('input[type=checkbox]').length;
var form= document.getElementById("form");
function addCheck() {
var checkinput = document.createElement("input");
checkinput.setAttribute("type", "checkbox");
checkinput.setAttribute("name", "check");
form.appendChild(checkinput);
var count = form.querySelectorAll('input[type=checkbox]').length;
console.log('Total Checkbox: ' +count);
}
<form id="form"></form>
<button type="btn" onclick="addCheck()">Add</button>
You can also maintain a variable as counter:
var form= document.getElementById("form");
var count = 0;
function addCheck() {
var checkinput = document.createElement("input");
checkinput.setAttribute("type", "checkbox");
checkinput.setAttribute("name", "check");
form.appendChild(checkinput);
count++;
console.log('Total Checkbox: ' +count);
}
<form id="form"></form>
<button type="btn" onclick="addCheck()">Add</button>
Just add a counter and increment it on button click. While setting attribute you have used the name of the variable in which the element is stored as check, but it should be checkinput
var count = 0;
var total=0;
function addCheck() {
var checkinput = document.createElement('input')
var form = document.getElementById('form')
checkinput.setAttribute('type', 'checkbox')
checkinput.setAttribute('name', 'check')
form.appendChild(checkinput)
count++;
total=count+2;
console.log('Number of checkboxes created by the user:' + count)
console.log( 'Total checkboxes in the form:' + total)
}
<button onclick="addCheck()">click</button>
<form id="form">
<input type="checkbox" name="check">
<input type="checkbox" name="check">
</form>
based on the question press and hold button javascript and the fiddle http://jsfiddle.net/0bs3omjj/1/ i want to change the code to another scenario. I want to check if button1 is onmousedown - hold - onmouseup and if so... the query selector should change to the next button
I tried this
<div id="myDIV">
<button class="myButton">button 1</button>
<button class="myButton">button 2</button>
<button class="myButton">button 3</button>
<button class="myButton">button 4</button>
</div>
And JavaScript
var mouse_is_down = false;
var current_i = 0;
var buttoncounter = 1;
var button = "";
var buttoncount = 0;
function changebutton() {
var x = document.getElementById("myDIV").querySelectorAll(".myButton");
x[buttoncount].style.backgroundColor = "red";
button = x[buttoncount];
buttoncount++;
}
changebutton();
button.onmousedown = function(){
mouse_is_down = true;
console.log("mousedown" + buttoncounter);
setTimeout(
(function(index){
return function(){
if(mouse_is_down && current_i === index){
//do thing when hold
console.log("hold" + buttoncounter);
console.log(button);
}
};
})(++current_i), 500); // time you want to hold before fire action
};
button.onmouseup = function(){
mouse_is_down = false;
current_i++;
console.log("onmouseup" + buttoncounter);
console.log("change selector");
buttoncounter++;
changebutton();
console.log(button);
};
But the query selector responds only on the first button (click & hold) - but the javascript changes the color values from the other buttons. What is wrong?
First of all, don't use the same ID multiple times.
Second, you're on the right path, but simply put the onmouseup and other calls within your changebutton() function:
Your HTML:
<div id="myDIV">
<button class="myButton">button 1</button>
<button class="myButton">button 2</button>
<button class="myButton">button 3</button>
<button class="myButton">button 4</button>
</div>
Your Javascript:
var mouse_is_down = false;
var current_i = 0;
var buttoncounter = 1;
var button = "";
var buttoncount = 0;
function changebutton() {
var x = document.getElementById("myDIV").querySelectorAll(".myButton");
x[buttoncount].style.backgroundColor = "red";
button = x[buttoncount];
button.onmousedown = function(){
mouse_is_down = true;
setTimeout(
(function(index){
return function(){
if(mouse_is_down && current_i === index){
//do thing when hold
console.log("hold" + buttoncounter);
console.log(button);
}
};
})(++current_i), 500); // time you want to hold before fire action
};
button.onmouseup = function(){
mouse_is_down = false;
current_i++;
buttoncounter++;
changebutton();
};
buttoncount++;
}
changebutton();