use location.hash to keep page status in javascript - 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>

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>

Click on the button and show Alert

The following code shows an alert box:
I want each box to be displayed by clicking on its own button
html
<button class="btn-alert btn-success" type="submit">delete</button>
<button class="btn-alert btn-success" type="submit">delete</button>
<button class="btn-alert btn-success" type="submit">delete</button>
<div class="alert-s col-4"></div>
<div class="alert-s col-4"></div>
<div class="alert-s col-4"></div>
<script>
const targetDiv = document.getElementById("alert");
const btn = document.getElementById("toggle");
function clickfn() {
for(let i = 0; i < targetDiv.length; i++) {
if (targetDiv.style.display = "none") {
targetDiv.style.display = "block";
} else {
targetDiv.style.display = "none";
}
}
};
</script>
can anyone help me to do so?
You can add a class to all your buttons, lets say toggle, then use javascript to call your function like:
var btns = document.getElementsByClassName('toggles');
for (var i = 0; i < btns.length; i++) {
btns[i].onclick = function () {
alert("Finaly!");
}
}
you don't need the for loop as getElementById returns a single element.
If you want to show alert on both button click and don't want to write two separate codes give them a similar class name and query them that way using document.querySelectorAll(a dot class name in quotes).
<button class="btn">Button one</button>
<button class="btn">Button two</button>
<script>
const btns = document.querySelectorAll(".btn");
for (let i = 0; i < btns.length; i++) {
btns[i].onclick = () => {
alert(`button ${i + 1} was clicked`);
};
}
</script>

Create Reset button for a counter

I have this counter. It is a counter that uses Javascript Closure. Can you help me with a reset button?
If you can, to this type of "counter" code, not to another...
HTML CODE
<button type="button" onclick="geo()">Count!</button>
<p id="count">0</p>
JAVASCRIPT CODE
<script>
var count= (function () {
var nr = 0;
return function () {nr+= 1; return nr;}
})();
function geo(){
document.getElementById("count").innerHTML = count();
}
</script>
I'm not even sure what you have right now is working.
const addBtn = document.querySelector('#add');
const resetBtn = document.querySelector('#reset');
const pCount = document.querySelector('#count')
let start = 0;
function add(){
start++
pCount.innerHTML = start
}
function reset(){
start = 0;
pCount.innerHTML = start
}
addBtn.addEventListener('click', add)
resetBtn.addEventListener('click', reset)
<button id="add"> Add </button>
<button id="reset" > Reset </button>
<p id="count"></p>
I don't know much about the closure (seems very interesting...) but moving nr variable outside of your function and then call a reset on nr will reset the counter.
var count = (function() {
var nr = 0;
return function(reset = false) {
nr = reset ? 0 : nr + 1
return nr;
}
})();
function geo() {
document.getElementById("count").innerHTML = count();
}
function reset() {
document.getElementById("count").innerHTML = count(true);
}
<button type="button" onclick="geo()">Count!</button>
<button type="button" onclick="reset()">Reset!</button>
<p id="count">0</p>

Press and hold button and change query selector

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

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