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>
Related
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>
I have an assignment where I have to change h1 to whatever is written in the input. I have to do this through making a function with getElementByID.
This is what I have so far
<!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>Change Text</title>
</head>
<body>
<h1 id="Header">Change header</h1>
<p>Use the input to change the header.</p>
<input type="text" oninput="changeh1(this.value)" />
<script>
function changeh1(newtext) {
document.getElementById("Header").textContent=
}
</script>
</body>
</html>
You passed the value (newtext) to your function but never used it:
<!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>Change Text</title>
</head>
<body>
<h1 id="Header">Change header</h1>
<p>Use the input to change the header.</p>
<input type="text" oninput="changeh1(this.value)" />
<script>
function changeh1(newtext) {
document.getElementById("Header").textContent=newtext;
}
</script>
</body>
</html>
Try changing your script to this:
function changeh1(newtext) {
document.getElementById("Header").innerText = newtext;
}
<script>
function changeh1(newtext) {
document.getElementById("Header").textContent = newtext;
}
</script>
The textContent API is useful to get and also set the text content of a node. In your original code, you did not set the content of the Node you were trying to modify (the header, h1). To fix it, just set it to the argument of the callback function you defined. In the DOM, you are passing this.value as the argument for newtext
<!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>Change Text</title>
</head>
<body>
<h1 id="Header">Change header</h1>
<p>Use the input to change the header.</p>
<input type="text" oninput="changeh1(this.value)" />
<script>
function changeh1(newtext) {
document.getElementById("Header").textContent = newtext
}
</script>
</body>
</html>
I was getting this error in my console while trying to execute a function using the "onclick" event inside of a button. The error I got was,
Uncaught ReferenceError: foo is not defined
onclick http://localhost:3001/bar:1
onclick http://localhost:3001/bar:1
I defined foo like this in the <body> tag followed by a script tag,
function foo(){
fooBar();
}
Thanks.
Edit: Heres my 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">
<meta name="description" content="app lol">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<title><% title %></title>
</head>
<body>
<script>
function foo() {
fooBar();
}
</script>
<button onclick="foo()">bar</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"> <meta name="description" content="app lol"> <script src="unpkg.com/axios/dist/axios.min.js">
</script>
<title></title>
</head>
<body>
<script>
function fooBar()
{
alert("hey");
}
function foo()
{
fooBar();
}
</script>
<button onclick="foo()">bar</button>
</body>
</html>
<html>
<head><title></title></head>
<body>
<button id="btn" onClick="foo()">Click me </button>
<script>
btn = document.getElementById("btn");
function foo(){
btn.style.color = "red";
}
</script>
</body>
</html>
This works!
Add an ID to your button. onclick is kinda buggy, because Google security features prevent you from doing so. It is even a good idea to separate JavaScript and HTML.
I usually assign an ID to a div, and querySelector them.
<div id="an-id">
<input />
</div>
document.querySelector("#an-id").querySelector("input").addEventListener("click", foo);
(Put your script after the button)
Is this how your setup looks? If yes, there shouldn't be any error.
<script>
function foo () {
console.log('Foo function');
}
</script>
<button onclick="foo()"> My Button </button>
[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>
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>