How to use .innerHTML with a var created by let [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 years ago.
I'm trying to make a very simple app in javascript in order to get rgb color to be divided by 255. I want the result to appear on the index.html page but it hasn't worked can anyone tell me how to fix it.
Here is my HTML code:
<!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>app</title>
</head>
<body>
<script src="app.js"></script>
<p id="red"></p>
</body>
</html>
Here is my javascript code:
let red = prompt("Enter the red number here");
let green = prompt("Enter the green number here");
let blue = prompt("Enter the blue number here.");
let resultR = red/255;
let resultG = green/255;
let resultB = blue/255;
document.getElementById("red").innerHTML = resultR;

It works fine though...
The problem may be that you call the JavaScript before Html so can't find the element.
let red = prompt("Enter the red number here");
let green = prompt("Enter the green number here");
let blue = prompt("Enter the blue number here.");
let resultR = red/255;
let resultG = green/255;
let resultB = blue/255;
document.getElementById("red").innerHTML = resultR;
<!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>app</title>
</head>
<body>
<script src="app.js"></script>
<p id="red"></p>
</body>
</html>

Related

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

Cancel out a prompt if something equals something

I got this prompt that makes it change the document.title when the prompt has been submitted, but i want it to make it so that if my prompt equals something, it cancels out the prompt, how to do that?
here is my HTML and JS, also it changes the h1 text, in the snippet it wont change the stackoverflow title cause it's already pre defined.
P.S: i know it's gonna be something small i missed, but pardon me for that i'm still a beginner >_<
const h1 = document.getElementById('h1');
function myFunction() {
let mainTitle = "Enter website title..."
let websiteTitle = prompt("What is your website title?", mainTitle)
if(websiteTitle != null ) {
document.title = websiteTitle;
h1.innerText = websiteTitle;
} else if(document.title === mainTitle) {
websiteTitle = null;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="pets.css">
</head>
<body>
<h1 id="h1">Website Title here!</h1>
<button onclick="myFunction()">Change Website Title</button>
<script src="pets.js"></script>
</body>
</html>
I'm not sure if I understood what you are trying to do, but I'll leave here a snippet with the solution to the problem I think you have:
const h1 = document.getElementById('h1');
function myFunction() {
let mainTitle = "Enter website title..."
let websiteTitle = prompt("What is your website title?", mainTitle)
if(websiteTitle != null ) {
document.title = websiteTitle;
h1.innerText = websiteTitle;
}
if(websiteTitle === mainTitle) {
window.location.reload();
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="pets.css">
</head>
<body>
<h1 id="h1">Website Title here!</h1>
<button onclick="myFunction()">Change Website Title</button>
<script src="pets.js"></script>
</body>
</html>
I can't close a prompt yourself, the user has to do it, you may want to use an input and manually hide it / show it to simulate a prompt.

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>

Trying to learn addEventListener and my code isn't working

I am trying to create a magic 8 ball. I've added the answers at the top in an array, added the code to choose a random answer, and when the button is clicked, it's supposed to place said random answer in a p tag in a div. It actually worked very well a few times in codePen and then stopped. I didn't change a thing. Can anyone tell me what I'm missing if anything?
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">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<title>8 Ball</title>
</head>
<body>
<div class="ball">
<div id="display">
<p id="output"></p>
</div>
</div>
<button id="button">Answer</button>
</body>
</html>
JavaScript
var answers = ["Yes!", "Absolutely!", "Not A Chance", "No",
"Ask Me Later", "Not Yet"];
//random answer function displays random in the output id
var randomAnswer = answers[Math.floor(Math.random()*answers.length)];
function myFunction(){
document.getElementById('output').innerHTML = randomAnswer;
}
document.getElementById('button').addEventListener('click', myFunction);
I've tried moving things around and looking addEventListener up. There's a few questions here on that, too, but I haven't found anything that solves my issue.
Try reordering the placement of your <script> tag in you HTML , so that the script is run after the DOM is loaded/parsed.
When your script is run, the button that you're trying to add a click listener to is not going to be present because the script is run from the <head> tag before the <body> DOM contents are loaded and ready.
Try the following adjustment:
<!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">
<link rel="stylesheet" href="style.css">
<title>8 Ball</title>
</head>
<body>
<div class="ball">
<div id="display">
<p id="output"></p>
</div>
</div>
<button id="button">Answer</button>
<!-- Put script here instead -->
<script src="script.js"></script>
</body>
</html>
Also, consider revising your javascript so the the randomAnswer is recomputed each time the user clicks the button, so that the answer shown to the answer is able to change per button click:
var answers = ["Yes!", "Absolutely!", "Not A Chance", "No",
"Ask Me Later", "Not Yet"];
function myFunction(){
//[UPDATE] Move the random answer computation inside of myFunction()
var randomAnswer = answers[Math.floor(Math.random()*answers.length)];
document.getElementById('output').innerHTML = randomAnswer;
}
document.getElementById('button').addEventListener('click', myFunction);
Your script is loaded in the header. It's executed whereas the page didnt finished to load, so you're trying to attach a listener to the button element that doesnt exist yet. Move it to the bottom of the body section:
<!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">
<link rel="stylesheet" href="style.css">
// deleted
<title>8 Ball</title>
</head>
<body>
<div class="ball">
<div id="display">
<p id="output"></p>
</div>
</div>
<button id="button">Answer</button>
<script src="script.js"></script> // pasted here
</body>
</html>
The problem is that your randomAnswer needs to be defined inside of the function, so that the answer gets decided upon each time you press the button. Outside of the function it gets defined on page load, and the answer will be the same each time.
Here's an updated snippet:
var answers = ["Yes!", "Absolutely!", "Not A Chance", "No",
"Ask Me Later", "Not Yet"
];
function myFunction() {
//random answer function displays random in the output id
var randomAnswer = answers[Math.floor(Math.random() * answers.length)];
document.getElementById('output').innerHTML = randomAnswer;
}
document.getElementById('button').addEventListener('click', myFunction);
<!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">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<title>8 Ball</title>
</head>
<body>
<div class="ball">
<div id="display">
<p id="output"></p>
</div>
</div>
<button id="button">Answer</button>
</body>
</html>
Move
//random answer function displays random in the output id
var randomAnswer = answers[Math.floor(Math.random()*answers.length)];
inside of your function like this:
function myFunction(){
var randomAnswer = answers[Math.floor(Math.random()*answers.length)];
document.getElementById('output').innerHTML = randomAnswer;
}
document.getElementById('button').addEventListener('click', myFunction=()=>{
//[UPDATE] Move the random answer computation inside of myFunction()
var randomAnswer = answers[Math.floor(Math.random()*answers.length)];
document.getElementById('output').innerHTML = randomAnswer;
});
Place the logic inside the function and it will be created everytime that it is called.
Or ou could assign the function to a variable like this:
var answers = ["Yes!", "Absolutely!", "Not A Chance", "No",
"Ask Me Later", "Not Yet"];
let myFunction = function(){
//[UPDATE] Move the random answer computation inside of myFunction()
var randomAnswer = answers[Math.floor(Math.random()*answers.length)];
document.getElementById('output').innerHTML = randomAnswer;
}
document.getElementById('button').addEventListener('click', myFunction);

Categories