Here is my code :
// And my javascript file verbatims.js :
class Verbatims {
list() {
return ["c'est super", "j'aime pas", "ça marche bien"];
}
}
module.exports = Verbatims;
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta content="X-Content-Type-Options: nosniff">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.18/vue.min.js"></script>
<script src="/src/verbatims.js" type="application/javascript"></script>
<title>My Project</title>
</head>
<body>
<div id="PRISME_data">
Le nombre de requête est de : {{ nb_request }}<br>
<button v-on:click="change">Change value</button>
<button v-on:click="stop">Arrêter</button>
</div>
<script>
let app = new Vue({
el:'#PRISME_data',
data: {
nb_request: "toto",
ite: 0
},
methods: {
change: function() {
changeNbRequest()
},
stop: function() {
clearInterval()
}
}
});
changeNbRequest = function() {
var timer = setInterval(function() {
let verbatim = new Verbatims().list()[ite];
}, 5000);
}
</script>
</body>
</html>
When I try to display my page with my node server I have this error :
Uncaught ReferenceError: Verbatims is not defined at index:45
on this line : let verbatim = new Verbatims().list()[ite];
I don't see why, I have try a lot of things but nothing work ! Do you have any idea ?
Thank you :)
This might be happening because of the following:
The verbatims.js file is not loading in the browser because of
wrong path.
The verbatims.js file that reached the browser does
not contain your class.
You did not import the Verbatims class on the referencing script.
Fix for 3rd option should be like this:
<script type="module">
import {Verbatims} from './src/vebatim.js';
....ommitted for brevity
changeNbRequest = function() {
var timer = setInterval(function() {
let verbatim = new Verbatims().list()[ite];
}, 5000);
}
</script>
Additional TIP
To improve your code, try to place all the JS code inside your index.html to an external file so you can take advantage of ES6 import/export features.
Related
Background
I've been using Vue 2 for a long time and am currently exploring Vue 3 to see what converting our existing website will entail. Because this is a conversion I plan to use the options interface for Vue 3. For the most part it seems like the conversion should be fairly painless. But I have encountered one Vue3 behavior that I find very puzzling.
Vue 2 Example
In Vue 2 if I have the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="https://unpkg.com/vue#2.5.16/dist/vue.min.js"></script>
</head>
<body>
<h1>Vue2 app.variable example</h1>
<!-- vue template -->
<div id="appTemplate">
<div style="margin-bottom:20px">Count: <span v-text="count"></span></div>
<button v-on:click="increment()">Increment</button>
</div>
<script type="text/javascript">
//Vue2 Example
var app = new Vue({
el: '#appTemplate',
data: {
count: 101
},
methods: {
increment: function() {
this.count++;
}
},
created: function(){
_app = this;
}
});
alert("app.count is:" + app.count)
</script>
</body>
</html>
When the page loads, the alert looks like this:
This demonstrates that after the vue object is created I can access the data properties as though they hang directly off of the vue object. This is as expected since it's documented behavior.
However, Vue 3 Behaves Differently for Me
Here is a block of analogous Vue3 code with a bit of extra code you will probably notice:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="https://cdn.jsdelivr.net/npm/vue#3.0.5/dist/vue.global.js"></script>
</head>
<body>
<h1>Vue3 app.variable example</h1>
<!-- vue template -->
<div id="appTemplate">
<div style="margin-bottom:20px">Count: <span v-text="count"></span></div>
<button v-on:click="increment()">Increment</button>
</div>
<script type="text/javascript">
//Vue3 OptionsAPI
var _app;
var app = Vue.createApp({
data: function() {
return {
count: 101
}
},
methods: {
increment: function() {
this.count++;
}
},
created: function(){
_app = this;
}
}
);
app.mount("#appTemplate");
//It's really odd that we can't access the property this way:
alert("app.count is:" + app.count);
//but this works.
alert("_app.count is:" + _app.count);
</script>
</body>
</html>
When this page loads and the first alert box is shown, app.count is undefined.
To explore this a bit more you can see in the code that I set the value of an _app variable to the value of this in the created method. And I show a 2nd alert on load that displays _app.count. And sure enough that works and displays the correct value:
So that's pretty interesting. Is it by design in Vue 3 data properties can't be accessed directly from the vue object or is something wrong with my code? It seems like a really big change from Vue 2 if it's by design. So I'd like to hope that it's not.
So here is the question: Why can't I access count via app.count after the var app = Vue.createApp ?
In Vue 2, new Vue() returns the root component.
In Vue 3, createApp() returns the application instance, and the root component is returned from the application instance's mount():
var app = Vue.createApp({
data() {
return {
count: 101,
}
}
})
👇
var root = app.mount('#appTemplate')
console.log(root.count) // => 101
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="https://cdn.jsdelivr.net/npm/vue#3.0.5/dist/vue.global.js"></script>
</head>
<body>
<h1>Vue3 app.variable example</h1>
<!-- vue template -->
<div id="appTemplate">
<div style="margin-bottom:20px">Count: <span v-text="count"></span></div>
<button v-on:click="increment()">Increment</button>
</div>
<script type="text/javascript">
//Vue3 OptionsAPI
var app = Vue.createApp({
data: function() {
return {
count: 101
}
},
methods: {
increment: function() {
this.count++;
}
},
created: function(){
_app = this;
}
}
);
var root = app.mount("#appTemplate");
alert("root.count is:" + root.count);
</script>
</body>
</html>
Alternatively, you could chain the mount() call off of createApp():
var app = Vue.createApp().mount('#appTemplate')
console.log(app.count) // => 101
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="https://cdn.jsdelivr.net/npm/vue#3.0.5/dist/vue.global.js"></script>
</head>
<body>
<h1>Vue3 app.variable example</h1>
<!-- vue template -->
<div id="appTemplate">
<div style="margin-bottom:20px">Count: <span v-text="count"></span></div>
<button v-on:click="increment()">Increment</button>
</div>
<script type="text/javascript">
//Vue3 OptionsAPI
var app = Vue.createApp({
data: function() {
return {
count: 101
}
},
methods: {
increment: function() {
this.count++;
}
},
created: function(){
_app = this;
}
}
).mount("#appTemplate");
alert("app.count is:" + app.count);
</script>
</body>
</html>
You could also access that property before mounting the app :
app._component.data().count
How can I run my function "title()" in HTML?
I have created a "main.js" File, in there, there is following Code:
"use strict";
document.addEventListener("DOMContentLoaded", function() {
let newScript = document.createElement("script");
newScript.src = "javascript/head.js";
let heads = document.getElementsByTagName("head")[0];
console.log(heads)
heads.prepend(newScript);
});
in the "main.js" File load an another Script which is called "head.js" and here is the Code of this File:
function title(titleName) {
let title = document.createElement("title");
document.title = titleName;
document.head.appendChild(title);
}
Maybye you need my HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="javascript/main.js"></script>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script> title("Framework"); </script>
</head>
<body>
</body>
</html>
in head.js add:
window.addEventListener("load", () => title("my desired title name"));
Not sure why someone downvoted, but to clarify, you can run this code anywhere so long as the head.js file has been loaded, it doesn't have to be directly in head.js.
You can add it into main.js:
let newScript = document.createElement("script");
newScript.addEventListener("load", () => title("my desired title name"));
newScript.src = "javascript/head.js";
// ...
You can also run it directly in the HTML in a <script> tag but you'll have to ensure the script is loaded first.
I'm making a site that, depending on the user's time of the day, will show a night, afternoon or morning image.
But as it seems, the JS isn't working due to a Syntax Error on calling the function with "onload=" in the tag <body>. My VS Code Javascript higlighter isn't working on the words window, document nor getElementById.
Which part of my JS could be wrong?
Here's the HTML
<!DOCTYPE html>
<html lang="pt-br">
<head>
<script type="javascript" src="/script.js"></script>
<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">
</head>
<body onload="load()">
<section>
<div id="msg">
Message here
</div>
<div id="foto">
<img id="image" src="img/afternoon.png">
</div>
</section>
<footer>
<p>© Koala</p>
</footer>
</body>
</html>
And here's the JS
function load(){
var msg = window.document.getElementById('msg');
var img = window.document.getElementById('image');
var dt = new.Date();
var hour = dt.getHours();
msg.innerHTML = 'Now it is ${hour} hours.';
if (hour>= 0 && hour < 12) {
img.src = 'img/morning.png';
} else if (hour => 12 && hour < 18) {
img.src = 'img/afternoon.png';
} else {
img.src = 'img/night.png';
}
}
PS: I've tried running it on Mozilla and Chrome. No success.
The error appears to be with this line:
var dt = new.Date();
To instantiate a new Date object, you need to use this syntax:
var dt = new Date();
Once this syntax error is fixed, then the JS file should be loaded properly and then the onload attribute will be able to fire the load function.
Here's a working demo: https://codesandbox.io/s/stack-overflow-onload-8opgp?file=/script.js
I am trying to import https://github.com/tkurki/dnssd.js and make html file like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1">
<script src="/index.js"></script>
</head>
<body>
<section>
<h1>DNS-SD Browser</h1>
<div id="services"></div>
</section>
<script>
const dnssd = require('dnssd2');
// advertise a http server on port 4321
const ad = new dnssd2.Advertisement(dnssd.tcp('http'), 4321);
ad.start();
// find all chromecasts
const browser = dnssd2.Browser(dnssd.tcp('_http'))
.on('serviceUp', service => console.log("Device up: ", service))
.on('serviceDown', service => console.log("Device down: ", service))
.start();
</script>
</body>
</html>
But somehow it shows me error in console log:
Uncaught ReferenceError: require is not defined at index.js:1
Uncaught ReferenceError: require is not defined at index.js:18
What am I doing wrong please?
index.js contains:
var Advertisement = require('./lib/Advertisement');
var Browser = require('./lib/Browser');
var ServiceType = require('./lib/ServiceType');
var validate = require('./lib/validate');
var resolve = require('./lib/resolve');
var NetworkInterface = require('./lib/NetworkInterface');
module.exports = {
Advertisement: Advertisement,
Browser: Browser,
ServiceType: ServiceType,
tcp: ServiceType.tcp,
udp: ServiceType.udp,
all: ServiceType.all,
validate: validate,
resolve: resolve.resolve,
resolveA: resolve.resolveA,
resolveAAAA: resolve.resolveAAAA,
resolveSRV: resolve.resolveSRV,
resolveTXT: resolve.resolveTXT,
resolveService: resolve.resolveService,
};
The browser doesn't support require function
Use requirejs. You can also use it with jquery
You can learn about requirejs from here
Browser doesn't support require out-of-box. try adding this script tag to manually import require from its cdn.
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js"></script>
<script src="/index.js"></script>
I have an external javascript file,say, first.js which contains a variable named "score". I want to use this variable inside a <script> tag in body ( only after the variable has finished updating inside the first.js, in other words, I also want to control when this <script> inside body fires and obviously, use "score" in it ) . Any way to do so?
EDIT-------
Basically I want to store this variable to the data browser in parse.com . Here is my script--
<script>
function giveit(){
var temp=whatScore();
Parse.initialize("myID", "myJDID");
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.set("score", temp);
gameScore.save(null, {
success: function(gameScore) {
// Execute any logic that should take place after the object is saved.
alert('New object created with objectId: ' + gameScore.id);
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.message);
}
});
}
</script>
giveit() function gets called when a button gets clicked. I have used the onlogin attribute.
Now whatScore() is a function defined in first.js which looks as follows:
function whatScore()
{
return score;
}
I stored the result in temp and used the temp in the code below, but it doesn't work.
In the console it says, "whatScore" is not defined. What can I do so that the whatScore function of first.js is actually defined inside the <script> tag ??
Thank You.
With this code:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<title>Test</title>
<script src="first.js" type="text/javascript"></script>
</head>
<body><script type="text/javascript">console . log ( { foo : score } );</script></body>
</html>
and file named: "first.js" content:
var score = 5;
I get in console:
Object { foo: 5 }
Make sure:
Your HTML5 / CSS3 / JavaScipt syntax is valid.
The variable score is in global scope.
The file named: "first.js" is loaded before your script tag and the variable score is declared and set before you use it.
You can also wait for variable using this code:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<title>Test</title>
</head>
<body>
<script type="text/javascript">
function logScore () { console . log ( { foo : score } ); }
var interval = setInterval ( function ()
{
if ( typeof score !== "undefined" ) // if is declared use variable named: "score" and exit interval
{
logScore ();
clearInterval ( interval );
}
}, 1000 ); // wait one second ...
</script>
<script type="text/javascript">var score = 5; /* score loaded after interval */ </script>
</body>
</html>
Update:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<title>Test</title>
</head>
<body>
<button onclick="giveit ();">Test your function here ...</button>
<script type="text/javascript">
function giveit ()
{
var interval = setInterval ( function ()
{
if ( typeof whatScore === "function" ) // now check if function is declared, use return variable named: "score" and exit interval
{
var temp = whatScore ();
console . log ( { foo : temp } ); // log: Object { foo: 5 }
/* your code here */
clearInterval ( interval );
}
}, 1000 ); // wait one second ...
}
</script>
<script type="text/javascript">
var score = 5; /* set global variable named: "score" - loaded after interval */
function whatScore ()
{
// var score = 5 /* or set local variable named: "score" - loaded after interval */
return score;
}
</script>
</body>
</html>