Javascript Loading display - javascript

I want to make a javascript program to activate something which requires some time to compute a animated screen pop ups while computing/loading. My Problem is I don't know how to achieve this in JS using async code. I have my approaches like this on where I just created a element into the website via javascript animated via CSS and when the computation was finished closed via javascript, but nothing happened. The idea was kind of like this:
document.getElementById("BTN").addEventListener("click",async function(){
document.getElementById("example").style.display = "block";
//Some Computing...
document.getElementById("example").style.display = "none";
});
#example{
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id = "example">Lädt</div>
<button id = "BTN">Button</button>
</body>
</html>
So what is wrong with this approach?

It's likely that your entire code block is executed in one go, including setting the loading element visible and invisible afterwards, without giving the browser time to actually update the rendered page to show the loading element.
One way to modify your code would be:
document.getElementById("BTN").addEventListener("click",async function(){
document.getElementById("example").style.display = "block";
setTimeout(function() {
//Some Computing...
document.getElementById("example").style.display = "none";
}, 0);
});
This should allow the browser to update the page before going into the computation.

You should access after loading window.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
window.onload = function(){
document.getElementById("BTN").addEventListener("click",async function(){
document.getElementById("example").style.display = "block";
//Some Computing...
document.getElementById("example").style.display = "none";
})
};
</script>
</head>
<body>
<div id = "example">Lädt</div>
<button id = "BTN">Button</button>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id = "example">Lädt</div>
<button id = "BTN">Button</button>
</body>
<script>
document.getElementById("BTN").addEventListener("click",async function(){
document.getElementById("example").style.display = "block";
//Some Computing...
document.getElementById("example").style.display = "none";
})
</script>
</html>

Related

Local Storage not working with window.location.replace?

I tried using Local Storage to store a variable to determine if a button can be used or not. This however is not working at all like I expected. Why is the Item getting shown as "null" and why is the console.log not working?
Index.html:
<!DOCTYPE html>
<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">
<title>index.html</title>
<script>
localStorage.setItem('status', 'unused')
console.log(localStorage.getItem('status'))
let usedButton = () => {
localStorage.setItem('status', 'used')
console.log(localStorage.getItem('status'))
window.location.replace('index2.html')
}
</script>
</head>
<body>
<button onclick="usedButton()">Use me</button>
</body>
</html>
index2.html
<!DOCTYPE html>
<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">
<title>index2.html</title>
<script>
console.log(localStorage.getItem('status'))
let isButtonUsed = () => {
if(localStorage.getItem('status') == 'used'){
console.log('I was already used')
}
}
</script>
</head>
<body>
<button onclick="isButtonUsed()">Am I used?</button>
</body>
</html>
I tried making it so that the Button on index.html changes the localStorage variable status from 'unused' to 'used'. But on the 2nd page it is showing up as null and so the function is not working. I don't know how I can get a Button to work on one page and by clicking it disabling other buttons on other pages you redirect to.
Thank you in advance for your help.

Access data-id of clicked anchor tag and also redirect to href path using JavaScript

I want to apply click event on anchor tags but when I click on first then get the data-id value of first and also redirect to href value similarly if I click on second link then get the data-id of second link only and redirect to its href value.
<!DOCTYPE html>
<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">
<title>Document</title>
</head>
<body>
One
Two
Three
<script>
const body = document.querySelector('body');
body.onclick = (e) => {
e.preventDefault();
let link = body.querySelector('.link');
console.log(link);
}
</script>
</body>
</html>
This is the code I'm trying but when I click on any of the anchor tag then only first anchor tag accessing.
This is what I did and now it's working perfect.
<!DOCTYPE html>
<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">
<title>Document</title>
</head>
<body>
One
Two
Three
<script>
const body = document.querySelector('body');
body.onclick = (e) => {
e.preventDefault();
let anc = e.target;
const data = {
a: anc.getAttribute('data-id')
}
localStorage.setItem('data', JSON.stringify(data));
window.location = anc.getAttribute('href');
}
</script>
</body>
</html>

How to get a javascript variable to display a change when you click a button? [duplicate]

This question already has answers here:
How do I change the text of a span element using JavaScript?
(18 answers)
Closed 7 months ago.
I'm fairly new to HTML and JS and this is a smaller part of a larger project I'm working on. What I'm trying to do is get the number on screen to change whenever either button is clicked. As is, when I click the button the value of 'score' changes but it does not update on the page. I have tried using setInterval on the document.write in the body and that didn't work. I am very much stuck and any help is appreciated, thank you.
<!DOCTYPE html>
<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">
<title>Document</title>
<script>
let score = 1;
function subtractOne() {
score--;
}
function addOne() {
score++;
}
</script>
</head>
<body>
<button id="subtractOne" onclick="subtractOne()">Subract One</button>
<script>document.write(score)</script>
<button id="addOne" onclick="addOne()">Add One</button>
</body>
</html>
You need to use current score value and put it somewhere after each update.
let score = 1;
updateText();
function subtractOne() {
score--;
updateText();
}
function addOne() {
score++;
updateText();
}
function updateText() {
document.getElementById('result').innerText = score;
}
<!DOCTYPE html>
<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">
<title>Document</title>
</head>
<body>
<span id='result'></span>
<button onclick="subtractOne()">Subract One</button>
<button onclick="addOne()">Add One</button>
</body>
</html>
you can define a function to inject the value. and also, you can inject the value once the document load completely
<!DOCTYPE html>
<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">
<title>Document</title>
<script>
let score = 12;
window.onload = () => {
update()
}
function update() {
const span = document.getElementById('updateme')
span.innerHTML = score
}
function subtractOne() {
score--;
update()
}
function addOne() {
score++;
update()
}
</script>
</head>
<body>
<button id="subtractOne" onclick="subtractOne()">Subract One</button>
<span id="updateme"></span>
<button id="addOne" onclick="addOne()">Add One</button>
</body>
</html>
<!DOCTYPE html>
<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">
<title>Document</title>
<script>
let score = 1;
function subtractOne() {
document.getElementById("myTextarea").value = score--;
}
function addOne() {
document.getElementById("myTextarea").value = score++;
}
</script>
</head>
<body>
<button id="subtractOne" onclick="subtractOne()">Subract One
</button>
<textarea id="myTextarea" cols="2">
</textarea>
<button id="addOne" onclick="addOne()">Add One</button>
By default javascript willn't listening the value changes in the UI. Write eventlisteners and render it to the UI.
document.write(score) this will be called on initial load and willn't be rendered again and again until page re-renders.
So create any html tag and Whenever you are calling add/sub methods return updated the value to that newly created tag like below
function subtractOne() {
score--;
document.getElementById("testVal").textContent= score;
}
function addOne() {
score++;
document.getElementById("testVal").textContent= score;
}
<span id="testVal"></span>

Cannot set property of undefined error on button press

I'm trying to change the background color of a div element on button press but I'm getting the error Cannot set property 'BackgroundColor' of undefined. The event handler for the button is inside the window.onload event. I thought at that point every element inside the html document would be loaded, but apparently not.
Here is the code:
<!DOCTYPE html>
<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">
<title>Document</title>
</head>
<body>
<div class="random">This should become unreadable</div>
<button id="button">Click me!</button>
<script>
window.onload = function() {
document.getElementById("button").addEventListener('click', function() {
document.getElementsByClassName("random").style.BackgroundColor= "black";
});
}
</script>
</body>
</html>
try the following code segment.
the issue is document.getElementsByClassName("random") returning an array of elements.So you should select one element from that array and get the style of that element.
And BackgroundColor should be backgroundColor
<!DOCTYPE html>
<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">
<title>Document</title>
</head>
<body>
<div class="random">This should become unreadable</div>
<button id="button">Click me!</button>
<script>
window.onload = function() {
document.getElementById("button").addEventListener('click', function() {
document.getElementsByClassName("random")[0].style.backgroundColor= "black";
});
}
</script>
</body>
</html>
You can this out - getElementsByClassName produces error "undefined"
Another alternative could be this.
<body>
<div id="random">This should become unreadable</div>
<button id="button">Click me!</button>
<script>
window.onload = function() {
document.getElementById("button").addEventListener('click', function() {
document.getElementById("random").style.backgroundColor= "black";
});
}
</script>
Modify the script as follows and try again:
<!DOCTYPE html>
<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">
<title>Document</title>
</head>
<body>
<div class="random">This should become unreadable</div>
<button id="button">Click me!</button>
<script>
window.onload = function() {
document.getElementById("button").addEventListener('click', function() {
document.querySelector(".random").style.backgroundColor= "black";
});
}
</script>
</body>
</html>
Look into comments by #Bravo, document.getElementsByClassName("random") returns a HTMLCollection, not a single element - therefore document.getElementsByClassName("random").style is undefined
<!DOCTYPE html>
<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" />
<title>Document</title>
</head>
<body>
<div class="random">This should become unreadable</div>
<button id="button">Click me!</button>
<script>
window.onload = function () {
document
.getElementById('button')
.addEventListener('click', function () {
const button = document.getElementsByClassName('random');
for (let index = 0; index < button.length; index++) {
const element = button[index];
element.style.backgroundColor = 'black';
}
// if you will have only one element with class=random or if you only want to apply style to the first element with class=random, then
// button[0].style.backgroundColor = 'black';
// in your case, you should add an id to the element and use id as the selector
});
};
</script>
</body>
</html>

I am getting this error while doing simple toggle program

[I don't why I am getting this error, My JS code is running fine directly in the console of my browser but when I am trying to attach a .js file to my html I get this error.[][1]1
://i.stack.imgur.com/wON7T.jpg
var button1 = document.querySelector("button");
var isPurple = false;
button1.addEventListener("click", function(){
if(isPurple){
document.body.style.background = "white";
isPurple = false;
} else {
document.body.style.background = "purple";
isPurple = true;
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="MyTitle.js"></script>
</head>
<body>
<button>click me</button>
</body>
</html>
tHe code supplied seems to work fine - as noted int the comments - where you place the external js - make sa difference - it should be placed at the end of the code - just before the closing body tag. As a rule - place all the external CSS files in the head and all external js files in the body - unless there is some rendering based logic that is required in the javascript.
In this case - the javascript is intended to identify the button using the querySelector() - but it is not in the DOM yet so cannot be identified.
Also - you can simplify your code and just toggle the variable on the click and then use a ternary for adding / romoving a class with the background color set to the class. Its always better to use classes with styling attached rather than amendifing the CSS via the javascript.
var button1 = document.querySelector("button");
var isPurple = false;
button1.addEventListener("click", function(){
isPurple = !isPurple;
isPurple
? document.body.classList.add('purple')
: document.body.classList.remove('purple')
});
.purple {
background: purple;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>click me</button>
<script src="MyTitle.js"></script>
</body>
</html>
Of course - you could actually remove the variable totally - its always better if you can move away from global variables when possible - the following simply toggles the class on the button click.
var button1 = document.querySelector("button");
button1.addEventListener("click", function(){
document.body.classList.toggle('purple')
});
.purple {
background: purple;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="MyTitle.js"></script>
</head>
<body>
<button>click me</button>
<script src="MyTitle.js"></script>
</body>
</html>
The problem is that at the time the JavaScript is run the button element does not yet exist in the DOM. Load it afterwards and it should then exist OK.
In general it is wise to load such JS, i.e. that is going to run immediately on load, at the end OR put it into a window.onload function (especially if the code relies on images being already loaded).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>click me</button>
<script src="MyTitle.js"></script> </body>
</html>

Categories