How to know when a particular button is clicked in Javascript? - javascript

I'm making a function that displays a modal, and the modal has two buttons. I want this function to wait until one of the two buttons has been clicked, and return a value that corresponds to which button is clicked.
Here's a sample code that I came up with:
function myFunc()
{
var val=0;
buttonA = document.getElementById('buttonA');
buttonB = document.getElementById('buttonB');
buttonA.onclick = function(){
//do something
val = 1;
}
buttonB.onclick = function(){
//do something
val = 2;
}
while(val == 0);
return val;
}
The problem in this code is that the page becomes unresponsive because of the infinite loop, hence it isn't possible to change the value of val once initialised.
To be more precise, I want the main thread (on which myFunc is being implemented) to sleep until one of the other two threads (each of buttonA and buttonB) is clicked.
Is there some other work-around for this ? Please answer in Javascript only (no jQuery). Thanks.

Try something more like this:
function myFunc()
{
buttonA = document.getElementById('buttonA');
buttonB = document.getElementById('buttonB');
buttonA.onclick = function(){
//do something
differentFunc(1)
}
buttonB.onclick = function(){
//do something
differentFunc(2)
}
}
This is a different way to make the function more versatile (edited per your comment):
function myFunc(callback)
{
buttonA = document.getElementById('buttonA');
buttonB = document.getElementById('buttonB');
buttonA.onclick = function(){
//do something
callback(1)
}
buttonB.onclick = function(){
//do something
callback(2)
}
}
and call it like
myFunc(function(result) {
// do stuff with result
}
Javascript is naturally single-threaded. Any code that waits infinitely like that will cause a hangup and disallow input. There are ways to write async functions, namely using Promises like I did for a minute there, but it's generally easier to make your code work synchronously.

If I understand the OP's purpose is to create a modal with 2 choices like a confirm()? But for some reason confirm() isn't suitable? So a value on each button and it waits for user interaction? Unless I'm missing something fairly important, I have made a dynamically generated modal (no manual markup) that has 2 buttons. The purpose and result elude me so I left it with one event listener and a function with a simple ternary condition to which the alerts can be replaced by appropriate statements or expression at OP's discretion.
SNIPPET
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
.modal {
position: fixed;
top: 0;
left: 0;
height: 100vh;
width: 100vw;
background:transparent;
}
.ui {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: table-cell;
border: 3px ridge grey;
border-radius: 6px;
}
button {
font-size: 24px;
}
</style>
</head>
<body>
<script>
var frag = document.createDocumentFragment();
var modal = document.createElement('div');
var ui = document.createElement('div');
var on = document.createElement('button');
var off = document.createElement('button');
modal.className = 'modal';
ui.className = 'ui';
on.id = 'on';
on.textContent = 'On';
off.id = 'off';
off.textContent = 'Off';
frag.appendChild(modal);
modal.appendChild(ui);
ui.appendChild(on);
ui.appendChild(off);
ui.addEventListener('click', status, false);
function status(e) {
var tgt = e.target.id;
tgt === 'on' ? alert('ON!') : alert('OFF!');
}
document.body.appendChild(frag);
</script>
</body>
</html>

Related

JS: calling functions via buttons does not work anymore, if page is updated without reloading the page

I want to write a program with one html page, which i can update and fill with different elements via javascript with one button that stays the same in every version, which displays a modalBox. I made a very basic version of this: One page, that is filled with two buttons (next and last) for navigating through the pages and one to display the modal. In addition, i added a number, which is incremented oder decremented accordingly, when you click through the updated versions of the page.
var counter = 1;
function setUp(){
var c = document.getElementById("container");
var d = document.createElement("div");
d.setAttribute("id", "main");
d.innerHTML = counter;
var nxt = document.createElement("button");
var bck = document.createElement("button");
var modalBtn = document.createElement("button");
nxt.innerText = ">";
bck.innerText = "<";
modalBtn.innerText="Show Modal";
nxt.setAttribute("onclick","nextPage()");
bck.setAttribute("onclick","lastPage()");
modalBtn.setAttribute("onclick","showModal()");
d.appendChild(bck);
c.appendChild(d);
d.appendChild(nxt);
d.appendChild(modalBtn);
}
function showModal(){
var m = document.getElementById("modal");
m.style.display = "block";
}
function closeModal(){
var m = document.getElementById("modal");
m.style.display = "none";
}
function nextPage(){
var c = document.getElementById("container");
c.innerHTML="";
counter++;
setUp();
}
function lastPage(){
var c = document.getElementById("container");
c.innerHTML="";
counter--;
setUp();
}
setUp();
*{
padding: 0;
margin: 0;
}
#modal{
position: absolute;
width: 500px;
height: 300px;
background-color: black;
display: none;
}
#main{
background-color: aliceblue;
height: 500px;
width: 800px;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="tryout.css">
<script src="tryout.js" defer></script>
<title>Document</title>
</head>
<body>
<div id="container">
<div id="modal"><button id="closeButton" onclick="closeModal()">Close</button></div>
</div>
</body>
</html>
The problem is: on onload, the modal button works fine (on click, the modal is displayed). As soon as i update (not reloading!) the page via the next- or back button, the modal button stops working (Error-message says the type of modalbutton is null). I have no clue why, because to my knowledge, the buttons are reinitiated by clicking on the next or back button (because the setUp()-function is called in the functions triggered by the buttons). As soon as I reload the page via the reload-button, it is working until i use one of the next and back buttons.
I am new to js, it's probable that I'm missing sth. obvious here :) Many Thanks!
On the "nextPage" and "lastPage" function , you're just removing the whole content (including the modal) from the div which associated container class.
That's why when you calling the "showModal" function , there is no element with modal id on the DOM. That's why its saying null.
you can follow what Sakil said on the comment or, in your both(nextPage & lastPage) functions,you can just remove the div with id main and add it later on "setUp" function.
I'm adding some code snippet below, hope it will help;
function nextPage() {
//grab the div with "main" id
let main = document.getElementById("main");
//remove it from document
main.remove();
counter++;
//add it again; what you're doing actually.
setUp();
}
function lastPage() {
//grab the div with "main" id
let main = document.getElementById("main");
//remove it from document
main.remove();
counter--;
//add it again; what you're doing actually.
setUp();
}
of course you should refactor the code base, cause there is lot more copy-pasting staff present, but I'm leaving that up to you.

Why is the imagine not displayed while beeing "inline". js/html

I want to show and hide a picture by using one button. when it's clicked, the picture is displayed and a variable is set to 1. so that when you press the button the next time, the picture will be hidden again.
After the button is pressed, I console.log the value of set variable + if the picture is displayed or not. Console says that the Picture is "inline". But the picture is not on my screen.
I think all you need is the js function. If you need more information. just comment. thank's!
<script>
function showHideM(){
let open;
open = 0
if (open == 0){
open = 1;
document.getElementById("melmanId").style.display = "inline";
console.log(open)
console.log(document.getElementById("melmanId").style.display)
return;
}
if (open == 1){
open = 0;
document.getElementById("melmanId").style.display = "none";
}
}
</script>
You don't really need flags to maintain the state of the image's visibility. You can use classList's toggle method to toggle a class on/off or, in this case, visible/hidden, which makes things a little easier.
// Cache the elements, and add an event listener
// to the button
const img = document.querySelector('img');
const button = document.querySelector('button');
button.addEventListener('click', handleClick);
// Toggle the "hidden" class
function handleClick() {
img.classList.toggle('hidden');
}
.hidden { visibility: hidden; }
img { display: block; margin-bottom: 1em; }
button:hover { cursor: pointer; background-color: #fffff0; }
<img class="hidden" src="https://dummyimage.com/100x100/000/fff">
<button>Click</button>
Additional documentation
addEventListener
querySelector
Note: this will replace all the styles applied to 'melmanId'
<script>
let show = true;
function showHideM() {
show = !show;
if(show){
document.getElementById("melmanId").style.display = "inline";
}else{
document.getElementById("melmanId").style.display = "none";
}
}
</script>

Deduct Timer Count Every Page Refresh (Vanilla Javascript)

I am absolutely a noob when it comes to Javascript so I hope someone can help me please. I made a very simple Vanilla JS + HTML code that counts the number of times that it reaches 10 seconds (10 seconds = 1 count). This code will also refresh the page onmouseleave and when I change tab using window.onblur. My problem is that every time the page refreshes, the counter will go back to zero. What I want is that for the counter to deduct just one (or a specific number of) count every page refresh instead of completely restarting the count to zero. Please help me with Vanilla Javascript only and no JQuery (because I am planning to use this code personally and offline). Thank you in advance.
For those who may wonder what's this code is for, I want to create this to encourage myself to stay away from my computer for a certain period everyday. Like, if I can stay away from my computer for 100 counts, then I can use my computer freely after. I am addicted to the internet and I want to make this as my own personal way of building self-control.
Here is my code:
<style>
label {
color: orange;
}
p {
border-radius: 0px;
color: black;
text-decoration: none;
font-family: Consolas !important;
font-size: 16px;
font-weight: normal;
outline: none;
line-height: 0.25 ;
}
</style>
<body onmouseleave="window.location.reload(true)">
<p>You have earned <label id="pointscounter">00</label> point/s.</p>
<script>
var PointsLabel = document.getElementById("pointscounter");
var totalCountPoints = 0;
setInterval(setTimePoints, 10000);
function setTimePoints() {
++totalCountPoints;
PointsLabel.innerHTML = pad(totalCountPoints);
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
</script>
<script>
var blurred = false;
window.onblur = function() { blurred = true; };
window.onfocus = function() { blurred && (location.reload()); };
</script>
</body>
Storage
If you want the data to survive a reload, you need to save it somewhere. There are multiple options you can use. I used localStorage. You can learn more about it here: https://www.w3schools.com/jsref/prop_win_localstorage.asp. localStorage even survives closing the Browser Tab.
If you want to reset the data in a new session, you can use sessionStorage (just replace localStorage with sessionStorage): https://www.w3schools.com/jsref/prop_win_sessionstorage.asp.
What I did:
Save data on blur
If a blur-event occurs, the data is saved.
I also stopped the interval because there is no need for the interval anymore.
blurred variable
There is (currently?) no need for this variable.
The only usecase seems to be:
window.onfocus = function() {
blurred && location.reload();
};
To my knowledge you don't need this variable here.
Comming back
If the user already has points in localstorage, the current Points are calculated based on the points in localstorage. It currently deducts 1 point.
Using onmouseleave
I replaced the location.reload(true) on the body-tag with a function call. Everytime the mouse leaves, it calls this function. This function calls the onBlur function. The onBlur function is there, to ensure, that both window.onblur and onmouseleave do the same thing (save & stop). After the onBlur function is called, an EventListener is added to wait for mouseenter. When the mouse is seen again, we can reload the page with the onFocus function. It wouldn't reload the page as soon as the mouse left, because the timer would start (bc of reload), even if the mouse wasn't on the document.
Todo:
There is currently no check to see, if a the mouse in on the document after a reload. The timer will begin, even if the mouse isn't on the document.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
label {
color: orange;
}
p {
border-radius: 0px;
color: black;
text-decoration: none;
font-family: Consolas !important;
font-size: 16px;
font-weight: normal;
outline: none;
line-height: 0.25;
}
</style>
</head>
<body onmouseleave="mouseLeft()">
<p>You have earned <label id="pointscounter">00</label> point/s.</p>
<script>
var PointsLabel = document.getElementById("pointscounter");
var totalCountPoints = 0;
// Calculate Points if user has already collected points
if (localStorage.getItem("points") !== null) {
// You can change, how many points to deduct
const pointsToDeduct = 1;
var tempPoints = localStorage.getItem("points");
totalCountPoints = tempPoints - pointsToDeduct;
// Reset to 0 if points now negative
if (totalCountPoints < 0) {
totalCountPoints = 0;
}
PointsLabel.innerHTML = pad(totalCountPoints);
}
// need to save, to stop/clear it later
var timePointsInterval = setInterval(setTimePoints, 10000);
function setTimePoints() {
++totalCountPoints;
PointsLabel.innerHTML = pad(totalCountPoints);
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
function mouseLeft() {
onBlur();
document.addEventListener("mouseenter", onFocus);
}
function onBlur() {
// save Current Points:
localStorage.setItem("points", totalCountPoints);
//stop the timer
clearInterval(timePointsInterval);
}
function onFocus() {
location.reload();
}
// Blur Detection
var blurred = false;
window.onblur = function () {
// [-] blurred = true;
onBlur();
};
window.onfocus = function () {
// [-] blurred && location.reload();
onFocus();
};
</script>
</body>
</html>

Javascript loading speed issue as variable increases

I am having an issue with page loading time. Currently right now I am running UBUNTU in Oracle Vm Virtual Box. I am using mozilla firefox as my browser and I am working on an etchasketch project from "The odin project".
My problem is the page loading time. The code takes a prompt at the start and generates a grid for the etch a sketch based on that prompt. I have not given it the minimum and maximum values (16 and 64) respectively, however any number when prompted at the beginning that is beyond 35 doesn't load or takes ages to load.
How do I speed up the process time? / why is it moving so slow? / how can I avoid this ? / is there a fix that I am over looking that can make this work a lot faster? / feel free to tackle any and all of those questions!
This is my HTML CODE:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8"/>
<title>
</title>
</head>
<body>
<div class="etchhead">
<p> Choose your grid size </p>
<input type = "text"></input>
<button id="startOver"> Clear Grid </button>
<p> Change color </p>
</div>
<div id="grid">
</div>
<script src="eas.js"></script>
</body>
</html>
And this is my CSS code:
p {
color: blue;
display: inline;
}
#grid {
display: grid;
width: 800px;
max-width: 800px;
height: 800px;
max-height: 800px;
line-height: 0;
}
.gridBox {
border: 1px solid black;
background-color: lightgrey
}
And this is my JAVASCRIPT code:
gridStart();
function gridStart(){
var boxes = 0
var selectBody = document.querySelector("#grid");
var addBox = document.createElement("div");
var boxCountStart = prompt("enter a number between 16 and 64");
var boxDimensions = (boxCountStart * boxCountStart);
function rowsAndColumns() {
var selectBody = document.querySelector("#grid");
var gridTemplateColumns = 'repeat('+boxCountStart+', 1fr)';
selectBody.style.gridTemplateColumns= gridTemplateColumns;
selectBody.style.gridTemplateRows= gridTemplateColumns;
};
function hoverColor(){
var divSelector = selectBody.querySelectorAll("div");
divSelector.forEach((div) => {
div.addEventListener("mouseover", (event) => {
event.target.style.backgroundColor = "grey";
});
});
};
rowsAndColumns();
for (boxes = 0; boxes < boxDimensions ; boxes++) {
var selectBody = document.querySelector("#grid");
var addBox = document.createElement("div");
addBox.classList.add("gridBox");
addBox.textContent = (" ");
selectBody.appendChild(addBox);
hoverColor();
};
};
There are two components to your issue. One is that you are repeatedly modifying the DOM in a loop. You can fix it by appending all your boxes to a DocumentFragment and then adding that to the DOM after your loop finishes. You are also calling hoverColor(); inside your loop which results in adding tons of event listeners that all do the same thing (since inside hoverColor you are adding a listener to every single div). You can fix both those issues like this:
var fragment = document.createDocumentFragment( );
for (var i = 0; i < boxDimensions ; i++) {
var addBox = document.createElement("div");
addBox.classList.add("gridBox");
addBox.textContent = (" ");
fragment.appendChild(addBox);
}
document.querySelector("#grid").appendChild( fragment );
hoverColor();
Here is a JSFiddle with your original code, and here is one with the modification.
You could also benefit from only having one event listener total. You don't need to loop and add an event listener to every div. Just add one to #grid and use event.target (like you already do, to find the div that the event originated from). Something like this:
function hoverColor(){
document.querySelector("#grid").addEventListener( 'mouseover', function ( event ) {
event.target.style.backgroundColor = "grey";
} );
}

Nested setInterval function on scroll not working

I am trying to set interval to a function that is only called when user scrolls below a certain height. My code return no errors and the function does not run either. However, I tried logging a random number at the end of the function and it doesn't so I think it has to do with my function. Take a look:
var firstString = ["This ", "is ", " me."];
var firstPara = document.querySelector("#firstPara");
var distanceSoFar = (document.body.scrollTop);
window.addEventListener("scroll", function() {
setInterval(slideIn, 450);
});
function slideIn() {
if (distanceSoFar > "130") {
for (var i = 0; i < firstString.length; i++) {
var stringOut = firstString.shift();
firstPara.innerHTML += stringOut;
console.log("5");
}
}
};
firstPara is just a paragraph in a div on the page. So the idea is to place some text in it on interval when a user scrolls into that view like so:
body {
height: 1000px;
}
div {
position: relative;
top: 700px;
}
div #firstPara {
border: 1px solid;
}
Part of your code is working. It handles the scroll event correctly and the slideIn function is called but the condition distanceSoFar > "130" is never met.
I'd suggest two changes to make your code work as you expect:
Use document.documentElement.scrollTop instead of document.body.scrollTop. document.body.scrollTop may return incorrect values (0) on some browsers. Look at this answer, for example.
Declare distanceSofar inside of the slideIn function. You declared the variable on the top of your code, so it stores a static value of the scrollTop property.
I'd avoid using setInterval inside a scroll event handler, you are setting a lot of intervals and not clearing them. I added some console.logs to show you how the slideIn function keeps being called even when the user is not scrolling.
A final tip: the scrollTop property is a number, so you can compare it to 130 instead of "130".
Here is the working fiddle.
I tried your code. I think it is working as you expected. I also added a clearInterval inorder to clear the timer after printing all text and also to avoid repeated calling.
<html>
<head>
<style>
body {
height: 1000px;
}
div {
position: relative;
top: 700px;
}
div #firstPara {
border: 1px solid;
}
</style>
<script>
function start(){
var s =0;
var interval = undefined;
function slideIn() {
console.log(distanceSoFar);
if (distanceSoFar > "130") {
while ( firstString.length > 0) {
var stringOut = firstString.shift();
firstPara.innerHTML += stringOut;
console.log(s++);
}
clearInterval(interval);
interval = undefined;
}
};
var firstString = ["This ", "is ", " me."];
var firstPara = document.querySelector("#firstPara");
var distanceSoFar = (document.body.scrollTop);
window.addEventListener("scroll", function() {
if(!interval)
interval = setInterval(slideIn, 450);
});
};
</script>
</head>
<body onload="start()">
<div id="firstPara"/>
</body>
<html>

Categories