Press and hold button and change query selector - javascript

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();

Related

Need To stop Timer counting down when browser tab minimized or been switched between tabs

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 have 10 buttons that I want when I press a button, a function occurs

I have a page with 10 buttons I want when I press a button the speech inside it changes
And div appears, and when you click the second time, everything returns as it was
button 10 html
<button class="button" id="movetool">click 1</button>
<button class="button" id="movetool2">click 2</button>
<button class="button" id="movetool3">click 3</button>
<button class="button" id="movetool4">click 4</button>
<button class="button" id="movetool5">click 5</button>
<button class="button" id="movetool6">click 6</button>
<button class="button" id="movetool7">click 7</button>
<button class="button" id="movetool8">click 8</button>
<button class="button" id="movetool9">click 9</button>
<button class="button" id="movetool0">click 10</button>
button javacsript
var activeButton = localStorage.getItem('activeButton');
var isActive = localStorage.getItem('isActive');
const allButtons = document.querySelectorAll(".button");
[...allButtons].forEach(function(thisButton) {
if (isActive === 'true') {
if (activeButton !== thisButton.id) {
thisButton.disabled = true;
}
}
});
const movetool = event => {
activeButton = localStorage.getItem('activeButton');
const target = event.target.closest("button");
if (activeButton === target.id) {
var enableAll = false;
Array.from(allButtons).forEach(function(thisButton) {
if (thisButton.disabled) {
enableAll = true;
return;
}
});
if (enableAll) {
Array.from(allButtons).forEach(function(thisButton) {
thisButton.disabled = false;
});
localStorage.setItem('isActive', false);
} else {
Array.from(allButtons).forEach(function(thisButton) {
thisButton.disabled = true;
});
if (target.classList.contains("button")) {
target.disabled = false;
localStorage.setItem('isActive', true);
localStorage.setItem('activeButton', target.id);
}
}
} else {
Array.from(allButtons).forEach(function(thisButton) {
thisButton.disabled = true;
});
if (target.classList.contains("button")) {
target.disabled = false;
localStorage.setItem('isActive', true);
localStorage.setItem('activeButton', target.id);
}
}
}
document.querySelector('.button_container').addEventListener('click', movetool);
I want to change the text when I press the button to "clicked"
and show div
code
the button is clicked
You should do:
allButtons.forEach(button => button.addEventListener("click", () => {
localStorage.setItem('isActive', button.id)
// Do that refresh loop you had at the top of your question
})
Inside your moveTool event listener callback
thisButton.innerHTML = 'clicked';

I have ten buttons I want when I press a button all buttons stop

I have ten buttons I want when I press a button all the other buttons stop
You did it and it worked, but if you do a reload, you can press another button. I want to prevent the user from pressing another button than the one he pressed.
html
<button class="button" id="movetool" onclick="movetool()">click 1</button>
<button class="button" id="movetool2" onclick="movetool2()">click 2</button>
<button class="button" id="movetool3" onclick="movetool3()">click 3</button>
<button class="button" id="movetool4" onclick="movetool4()">click 4</button>
<button class="button" id="movetool5" onclick="movetool5()">click 5</button>
<button class="button" id="movetool6" onclick="movetool6()">click 6</button>
<button class="button" id="movetool7" onclick="movetool7()">click 7</button>
<button class="button" id="movetool8" onclick="movetool8()">click 8</button>
<button class="button" id="movetool9" onclick="movetool9()">click 9</button>
<button class="button" id="movetool10" onclick="movetool10()">click 10</button>
javascript
var clickCounter10 = window.localStorage.getItem('clickCounter10') || 0;
var movetool10 = document.getElementById('movetool10');
var man10 = 10;
changeBtn10();
movetool10.onclick = function() {
clickCounter10++;
window.localStorage.setItem('clickCounter10', clickCounter10);
changeBtn10();
};
function changeBtn10() {
clickCounter10 = parseInt(clickCounter10, 10);
if (clickCounter10 === 2) {
clickCounter10 = 0;
document.getElementById('movetool10').innerHTML = 'ok 1';
document.getElementById("man10").innerHTML = man10;
document.getElementById("movetool").disabled = false;
document.getElementById("movetool2").disabled = false;
document.getElementById("movetool3").disabled = false;
document.getElementById("movetool4").disabled = false;
document.getElementById("movetool5").disabled = false;
document.getElementById("movetool6").disabled = false;
document.getElementById("movetool7").disabled = false;
document.getElementById("movetool8").disabled = false;
document.getElementById("movetool9").disabled = false;
} else if(clickCounter10 !== 0) {
document.getElementById('movetool10').innerHTML = 'no ok 1';
document.getElementById("man10").innerHTML = man10 - 1;
document.getElementById("movetool").disabled = true;
document.getElementById("movetool2").disabled = true;
document.getElementById("movetool3").disabled = true;
document.getElementById("movetool4").disabled = true;
document.getElementById("movetool5").disabled = true;
document.getElementById("movetool6").disabled = true;
document.getElementById("movetool7").disabled = true;
document.getElementById("movetool8").disabled = true;
document.getElementById("movetool9").disabled = true;
}
}
EDIT: I've added some comments so you can read about it. Made it all if-else conditions.
Remove all your inline HTML event attributes. That's highly unmanageable. Imagine creating a function and an action handler per button. It could get messy. Use delegation:
JavaScript event delegation is a simple technique by which you add a
single event handler to a parent element in order to avoid having to
add event handlers to multiple child elements
You can achieve this with these few lines of code:
//get the active button
var activeButton = localStorage.getItem('activeButton');
var isActive = localStorage.getItem('isActive');
//get all the button
const allButtons = document.querySelectorAll(".button");
[...allButtons].forEach(function(thisButton) {
/*
If isActive equals true,
set thisButton disabled to true if activeButton is not equal to thisButton's id
*/
if (isActive === 'true') {
if (activeButton !== thisButton.id) {
thisButton.disabled = true;
}
}
});
const movetool = event => {
/*get current activeButton*/
activeButton = localStorage.getItem('activeButton');
/*
get the closest button on call
*/
const target = event.target.closest("button");
/*
diables all buttons
*/
/*if active button is equal to target.id*/
if (activeButton === target.id) {
var enableAll = false;
/*get the array from all the buttons*/
Array.from(allButtons).forEach(function(thisButton) {
if (thisButton.disabled) {
enableAll = true;
return;
}
});
if (enableAll) {
/*get the array from all the buttons*/
Array.from(allButtons).forEach(function(thisButton) {
thisButton.disabled = false;
});
localStorage.setItem('isActive', false);
} else {
Array.from(allButtons).forEach(function(thisButton) {
thisButton.disabled = true;
});
if (target.classList.contains("button")) {
/*
sets disable to false on the closest button
}
*/
target.disabled = false;
/*
sets local storage new activeButton to the closest button's id
*/
localStorage.setItem('isActive', true);
localStorage.setItem('activeButton', target.id);
}
}
} else {
Array.from(allButtons).forEach(function(thisButton) {
thisButton.disabled = true;
});
if (target.classList.contains("button")) {
/*
sets disable to false on the closest button
}
*/
target.disabled = false;
/*
sets local storage new activeButton to the closest button's id
*/
localStorage.setItem('isActive', true);
localStorage.setItem('activeButton', target.id);
}
}
}
/*
a single event listener
*/
document.querySelector('.button_container').addEventListener('click', movetool);
<!-- wrap all buttons in a container to remove the event handlers -->
<div class="button_container">
<button class="button" id="movetool">click 1</button>
<button class="button" id="movetool2">click 2</button>
<button class="button" id="movetool3">click 3</button>
<button class="button" id="movetool4">click 4</button>
<button class="button" id="movetool5">click 5</button>
<button class="button" id="movetool6">click 6</button>
<button class="button" id="movetool7">click 7</button>
<button class="button" id="movetool8">click 8</button>
<button class="button" id="movetool9">click 9</button>
<button class="button" id="movetool10">click 10</button>
</div>
just pre disable all buttons
if clickCounter10 != 0 or whatever you want
you can use querySelectorAll to do it all at once
var clickCounter10 = window.localStorage.getItem('clickCounter10') || 0,
movetool10 = document.getElementById('movetool10'),
man10 = 10,
all_button = document.querySelectorAll(`button[id^="movetool"]`);
clickCounter10 = parseInt(clickCounter10, 10);
// pre disable all buttons if clickCounter10 != 0
all_button.forEach(button => {
if (clickCounter10 != 0) {
button.disabled = true;
} else {
button.disabled = false;
}
});
// short version
all_button.forEach(button => button.disabled = (clickCounter10 != 0) ? true : false);
changeBtn10();
movetool10.onclick = function () {
clickCounter10++;
window.localStorage.setItem('clickCounter10', clickCounter10);
changeBtn10();
};
function changeBtn10() {
if (clickCounter10 === 2) {
clickCounter10 = 0;
document.getElementById('movetool10').innerHTML = 'ok 1';
document.getElementById("man10").innerHTML = man10;
all_button.forEach(button => button.disabled = false);
} else if (clickCounter10 !== 0) {
document.getElementById('movetool10').innerHTML = 'no ok 1';
document.getElementById("man10").innerHTML = man10 - 1;
all_button.forEach(button => button.disabled = true);
}
}

use location.hash to keep page status in javascript

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>

Count on click button1 and recount if on click button2

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

Categories

Resources