I want to set up a very basic project with Vite vanilla
I scaffolded the project with yarn create #vitejs/app
Now I adjusted the following files:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
<link rel="stylesheet" href="style.css">
<script type="module" src="main.js"></script>
</head>
<body>
<div id="app">
<h1>Chat</h1>
Message
<br/>
<textarea placeholder="Message"></textarea>
<button onclick="sendMessage()">Send</button>
</div>
</body>
</html>
style.css
h1 {
color: blue;
}
main.js
console.log('hello main.js')
const chatInput = document.querySelector('textarea')
export function sendMessage() {
let message = chatInput.value
window.alert(message)
chatInput.value = "";
}
I am now getting the following error in the browser console when I click the "Send" button
client.ts:13 [vite] connecting...
main.js:35 hello main.js
client.ts:43 [vite] connected.
(index):18 Uncaught ReferenceError: sendMessage is not defined
at HTMLButtonElement.onclick ((index):18)
Workaround
I can work around the problem by adding an event listener to the button instead of adding the onclick directly in the HTML
const sendButton = document.querySelector('button')
sendButton.addEventListener('click', sendMessage)
But why can't you use the first approach with onclick="sendMessage()" within the HTML?
Main.js is added as a type=module. Module creates a scope to avoid name collisions.
You can either expose your function to the window object
import { sendMessage } from './events.js'
window.sendMessage = sendMEssage
Or use the addEventListener method to bind the handler like you're doing.
Related
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=, initial-scale=1.0">
<link rel="stylesheet" href="./index.css">
<title>Youpotify</title>
</head>
<body>
<div class="download">
<div class="video">
<button id="video">Download this video</button>
</div>
<div class="playlist">
<button id="playlist">Download this playlist</button>
</div>
<div class="channel">
<button id="channel">Download this channel</button>
</div>
</div>
<script>
document.getElementById("video").addEventListener("click", () => {
document.getElementById("video").style.backgroundcolor = "red";
});
</script>
</body>
</html>
I loaded this addon on Temporary Extension and I click the button but the background color did not change.
I wanted to run my JavaScript file in firefox addon popup HTML file, but it didn't work.
There are a couple of potential issues here:
First, inline Javascript (inside <script></script> tags) is not permitted by default.
To include Javascript to your popup, you need to put it into a separate Javascript file and reference is with:
<script src="index.js"></script>
where your index.js is in the same folder and has your code:
document.getElementById("video").addEventListener("click", () => {
document.getElementById("video").style.backgroundColor = "red";
});
Second,
document.getElementById("video").style.backgroundcolor = "red";
has incorrect attribute, it should be style.backgroundColor with a capital C.
[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'm trying to use an amp-script but I get this error:
"[amp-script] Script hash not found. amp-script[script="hello-world"].js must have "sha384-BdjJFLYaZaVK-HgidJ2OFtpYsczYQc4N42NgKo7MOkF88iPbpdDWPgf86Y6PyEKO" in meta[name="amp-script-src"]. See https://amp.dev/documentation/components/amp-script/#security-features."
error image
<!doctype html>
<html amp lang="en">
<head>
<meta charset="utf-8">
<meta class="trackPerformanceTag" content="AMP">
<script src="https://cdn.ampproject.org/v0.js" async></script>
<script async custom-element="amp-script" src="https://cdn.ampproject.org/v0/amp-script-0.1.js"></script>
<meta name="amp-script-src" content="sha384-generated-sha">
<title>title</title>
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
</head>
<body>
<amp-script layout="container" script="hello-world" class="amp-script-sample">
<button id="hello2">Click!</button>
</amp-script>
<script id="hello-world" type="text/plain" target="amp-script">
const button = document.getElementById('hello2');
button.addEventListener('click', () => {
const h1 = document.createElement('h1');
h1.textContent = 'Hello World 2!';
document.body.appendChild(h1);
});
</script>
</body>
</html>
You need to copy full hash shown in the error message in dev tools console.
In this case;
sha384-BdjJFLYaZaVK-HgidJ2OFtpYsczYQc4N42NgKo7MOkF88iPbpdDWPgf86Y6PyEKO
and paste it to meta in the header:
<meta name="amp-script-src" content="PUT_THE_SHA_HERE">
Every time you will change something in the script new hash will be generated and you need copy/paste it again.
See the screen with error form the dev tools console
This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 3 years ago.
I am completely new to JavaScript, and I can't figure out why I'm getting this error: Uncaught TypeError: Cannot read property 'addEventListener' of null.
I followed the advice posted in response to a similar question and put the file containing my JavaScript in the bottom of my body, but that didn't fix it. I also tried making the button onclick=checkValidity(), but that didn't work either.
document.getElementById("loginButton").addEventListener("click",
checkValidity);
function checkValidity() {
var usrName = document.getElementById("inputUsername").value;
var usrPswd = document.getElementById("inputPswrd").value;
if(usrName == "admin" && usrPswd == "123"){
window.open("HtmlPage2.html");
}
else {
alert("Your username and password are incorrect.");
}
}
and the 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" type="text/css" href="stylesheet.css">
<title>Document</title>
</head>
<body>
<div class=wrap>
<input type="text" id="inputUsername">
<p>Username</p>
<input type="password" id="inputPswrd">
<p>Password</p>
<button id="loginButton">Log in</button>
<p id="login"></p>
</div>
<script type="text/javascript" src="Script.js" async></script>
</body>
</html>
What I want the code to do is check whether the input in the inputUsername and inputPswrd match that specified in the if...else function, and if so, open a new window; otherwise alert an error message.
EDIT: If I move all the code above to the top of my JS file, it will work as intended and open a new window, but then the code for that new page won't run (but the new page code does run it's at the top of my JS file). The error message I get when the new window opens is line 1: Uncaught TypeError: Cannot read property 'value' of null at Script.js:1.
Additional code:
JS for HTML page 2:
document.getElementById("greeting").innerHTML="Welcome";
document.getElementById("productButtonOne").addEventListener("click",
addToCart);
document.getElementById("productButtonTwo").addEventListener("click",
addToCart);
document.getElementById("productButtonThree").addEventListener("click",
addToCart);
var clicks = 0;
function addToCart() {
clicks = clicks + 1;
document.getElementById("cartProductsTotal").innerHTML = "You have " +
clicks + " items in your shopping cart.";
}
Beginning of HTML for page 2:
<!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" type="text/css" href="stylesheet.css">
<title>Document</title>
</head>
<body>
<div class=wrap>
<h1 id="greeting"></h1>
<div id="productOne" class="cartItem">
<button id="productButtonOne" class="cartItems">Add to cart</button>
<img src="monaLisa.jpg" id="monaLisaImage">
<h2 class="productDescriptions">Mona Lisa</h2>
<p>This painting is great.</p>
<span class=price>This item costs $10.</span>
</div>
Place the scirpt tag after body it will work
<!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" type="text/css" href="stylesheet.css">
<title>Document</title>
</head>
<body>
<div class=wrap>
<input type="text" id="inputUsername">
<p>Username</p>
<input type="password" id="inputPswrd">
<p>Password</p>
<button id="loginButton">Log in</button>
<p id="login"></p>
</div>
<script type="text/javascript" src="Script.js" async></script>
</body>
<script>
document.getElementById("loginButton").addEventListener("click", checkValidity);
function checkValidity() {
var usrName = document.getElementById("inputUsername").value;
var usrPswd = document.getElementById("inputPswrd").value;
if(usrName == "admin" && usrPswd == "123"){
window.open("HtmlPage2.html");
}
else {
alert("Your username and password are incorrect.");
}
}
</script>
</html>
remove this line <script type="text/javascript" src="Script.js" async></script>, I think your code loads the wrong script.
I want to change the meta tag content i.e. refresh rate and url dynamically using javascript. Using a button to enable javascript function. Tried 3 alternatives but not working. Please help.
Thanks,Amresh
<!DOCTYPE html>
<html>
<head>
<meta HTTP-EQUIV="refresh" name="description" id="mymetatag"
content="5;URL=http://localhost:6985/ChartJSDemo/Is_Mainpage.html">
<meta charset="ISO-8859-1">
<title>Processing Details</title>
<link rel="stylesheet" type="text/css" href="css/MF_job_failTable.css">
</head>
<body>
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
<!--document.querySelector('meta[name="description"]').setAttribute("content","5;URL=http://google.co.in");-->
<!--document.getElementById("mymetatag").setAttribute("content", "5;URL=http://google.co.in");-->
var m = document.createElement('meta');
m.name = 'description';
m.id = 'mymetatag';
m.content = '5;URL=http://google.co.in';
m.HTTP-EQUIV= 'refresh';
document.head.appendChild(m);
}
</script>
This works for me.
The issue could have been that you tried a first code which did not work and you commented the code with HTML comments <!-- [...] -->instead of Javascript comments: // [...] or /** [...] */.
<!DOCTYPE html>
<html>
<head>
<meta HTTP-EQUIV="refresh" name="description" id="mymetatag" content="5;URL=http://localhost:6985/ChartJSDemo/Is_Mainpage.html">
<meta charset="ISO-8859-1">
<title>Processing Details</title>
<link rel="stylesheet" type="text/css" href="css/MF_job_failTable.css">
</head>
<body>
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
document.getElementById("mymetatag").setAttribute("content", "5;URL=http://google.co.in");
}
</script>
</body>
</html>
I looks like you misuse the functionality of metatags, JS doesn't save the state between requests. And, BTW, you can do reload/redirect using the javascript itself.