I am getting this error while doing simple toggle program - javascript

[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>

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.

Answered: Error when trying to change innertext with a button in html and javascript

I was trying to make a tally counter with buttons but when i press the button i get this error:
Uncaught TypeError: Cannot set properties of null (setting 'innerText')
Here is my HTML 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>
<script src=./test.js></script>
<link rel="stylesheet" href=./test.css></link>
</head>
<body>
<h1 id="count_el">0</h1>
<button id="increase" onclick="increase()">INCREASE</button>
<button id="decrease" onclick="decrease()">DECREASE</button>
</body>
</html>
And here is my JavaScript code:
const count_el = document.getElementById("count_el")
let count = 0
function increase(){
count += 1
count_el.innerText = count
}
function decrease(){
count -= 1
count_el.innerText = count
}
Try and add defer into your script tag like so:
<script src=./test.js defer></script>
this will make the javascript load after the page has loaded and then the error should disappear.
It seems the only problem is the loading phase of your javascript code: When trying to call document.getElementById('count_el') it can't find such element because it is not loaded in the DOM, so to avoid that you can use the defer attribute in your script tag.
There are three main ways to load an external js script, and I quote:
If async is present: The script is downloaded in parallel to parsing the page, and executed as soon as it is available (before parsing
completes)
If defer is present (and not async): The script is downloaded in parallel to parsing the page, and executed after the page has finished
parsing
If neither async or defer is present: The script is downloaded and executed immediately, blocking parsing until the script is completed
const count_el = document.getElementById("count_el")
let count = 0
function increase(){
count += 1
count_el.innerText = count
}
function decrease(){
count -= 1
count_el.innerText = count
}
<!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 src=./test.js defer></script>
<link rel="stylesheet" href=./test.css></link>
</head>
<body>
<h1 id="count_el">0</h1>
<button id="increase" onclick="increase()">INCREASE</button>
<button id="decrease" onclick="decrease()">DECREASE</button>
</body>
</html>
I assume the problem with your code is that the script runs before the dom has been loaded, so I've edited it to run after the page has been loaded. I've also added the event listeners using javascript instead of html.
if (document.readyState === "complete") onLoad();
else addEventListener("load", onLoad);
function onLoad() {
const countDom = document.querySelector("#count_el"),
increaseButton = document.querySelector("#increase"),
decreaseButton = document.querySelector("#decrease");
let count = 0;
increaseButton.addEventListener("click", increase);
decreaseButton.addEventListener("click", decrease);
function increase() {
count += 1;
countDom.innerText = count;
}
function decrease() {
count -= 1;
countDom.innerText = count;
}
}
<!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 src=./test.js></script>
<link rel="stylesheet" href=./test.css></link>
</head>
<body>
<h1 id="count_el">0</h1>
<button id="increase">INCREASE</button>
<button id="decrease">DECREASE</button>
</body>
</html>
You could also just move your scripts to the end of the body instead of inside the head but it's better to have safe scripts that will run regardless of the position and state of the script.

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>

JavaSctipt: Change color of a text element on button click

I am completely new to HTML and JavaScript, and I wanted to do something simple. I want a button, and below it was some text. When I clicked the button, I want the color of the text to change(Let's assume black to red for now). This is my attempt at this problem.
HTML File:
<!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>First Page</title>
</head>
<body>
<button id="BUTTON" onclick="changeColor">Click me</button>
<p id="TEXT">Text</p>
</body>
<script src="first.js"></script>
</html>
first.js:
var button = document.getElementById("BUTTON");
var color = document.getElementById("TEXT").style.color;
function changeColor(color) {
color = "#0EE5D0";
};
button.onclick = changeColor();
Thanks!
Here is a snippet that does what you asked for.
I removed the color variable and replaced it with text, the element that you want to change the color of.
I modified the changeColor function to return the chosen color.
Correctly used the onclick listener.
let button = document.getElementById("BUTTON");
let text = document.getElementById("TEXT")
function changeColor() {
return "#0EE5D0";
};
button.addEventListener("click", () => {
text.style.color = changeColor()
})
<!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>First Page</title>
</head>
<body>
<button id="BUTTON" onclick="changeColor">Click me</button>
<p id="TEXT">Text</p>
</body>
<script src="first.js"></script>
</html>
There are two main issues with your code. Both have been identified in the comments above.
First, button.onclick = changeColor(); doesn't assign the function to the onclick event. It calls the function and assigns the return value of the function to onclick, and that's not your intention.
Second, color = "#0EE5D0"; is not associated with the DOM element, so changing its value has no impact on the DOM element.
var button = document.getElementById("BUTTON");
button.onclick =function changeColor() {
document.getElementById("TEXT").style.color = "#0EE5D0";
};

Javascript Loading display

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>

Categories