Changing background color animation not working - javascript

I am trying to make the background color of the body change every second using the button.
I need the background to change on the click of the button for other reasons (I cannot use a normal interval, timeout, or #keyframes).
I can not figure out what is wrong with my code. Any ideas?
<!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>Stack Overflow</title>
</head>
<body>
<button id="click_me">Loaded</button>
<script type="text/javascript" defer>
const btn = document.getElementById("click_me");
const body = document.querySelector("body");
btn.onclick = () => {
if(body.style.backgroundColor == "white"){
body.style.backgroundColor = "black";
} else if(body.style.backgroundColor == "black"){
body.style.backgroundColor = "white";
}
}
setTimeout(()=>{
btn.click();
},1000);
</script>
</body>
</html>

So looks like the defautl background color for the body is really "transparent". So when you check for the white value its never found. So you just need too add an OR statment to check for the transparent 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>Stack Overflow</title>
</head>
<body>
<button id="click_me">Loaded</button>
<script type="text/javascript" defer>
const btn = document.getElementById("click_me");
const body = document.querySelector("body");
// debug stuff
console.log(`Here is the default value of your body color:`)
console.log(body.style.backgroundColor)
btn.onclick = () => {
if(body.style.backgroundColor == "white" || body.style.backgroundColor == ""){
body.style.backgroundColor = "black";
} else if(body.style.backgroundColor == "black"){
body.style.backgroundColor = "white";
}
}
setTimeout(()=>{
btn.click();
},1000);
</script>
</body>
</html>
If you don't want to do this you could just always set the body color to white on load. But you really probably should be using some type of reset Reset CSS. This way you know values like this are the same across all browser instead of finding out later what went wrong. Never know, maybe the default value of the background color could change in the future to something else.

there is a mistake in your code you didn't setted the background color for the body and trying to get it so you are getting empty value every time and you have if conditions on the basis of white and black color so didn't working try this code I had runned this on my local system its working now
<!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>Stack Overflow</title>
</head>
<body style="background-color: white;">
<button id="click_me">Loaded</button>
<script type="text/javascript" defer>
const btn = document.getElementById("click_me");
const body = document.querySelector("body");
btn.onclick = () => {
console.log(body.style.backgroundColor);
if(body.style.backgroundColor == "white"){
body.style.backgroundColor = "black";
} else if(body.style.backgroundColor == "black"){
body.style.backgroundColor = "white";
}
}
setTimeout(()=>{
btn.click();
},1000);
</script>

<!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>Stack Overflow</title>
</head>
<body id="body">
<button onclick="color();" id="click_me">Loaded</button>
<script type="text/javascript">
function color(){
var body1 = document.getElementById("body");
if(body1.style.backgroundColor == "white"){
body1.style.backgroundColor = "black";
} else if(body1.style.backgroundColor == "black"){
body1.style.backgroundColor = "white";
}
}
setTimeout(()=>{
document.body.style.backgroundColor = "white";
var btn = document.getElementById("click_me");
btn.click();
},1000);
</script>
</body>
</html>
Set white as default!

Related

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>

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";
};

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>

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