external .js variable coming back undefined? - javascript

I am trying to get an external .js variable into my index.html however the variable just comes back undefined. It works if the variable is in the HTML file but not when I call it from an outside .js file it just reads undefined ?
<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="assets/css/main.css" />
<title>LoginSystem</title>
<script src="../server.js"></script>
</head>
<body>
<div id="display"></div>
<script>
var t = setInterval(function() {
// you can change `random` to any variable you want to be displayed
document.getElementById("display").innerHTML = random;
}, 500);
</script>
</body>
and the javascript file
var random = Math.random();
any help would be greatly appreciated thank you.

I can't explain why you're getting undefined; however, Since you set random in a variable outside of the scope of the function passed into setInterval, it will always display the same random number. You need to set random inside the function passed to setInterval if you want a new random number to show up.
server.js
function getRandomNumber() {
return Math.random();
}
index.html
var t = setInterval(function() {
document.getElementById("display").innerHTML = getRandomNumber();
}, 500);
Demo
https://repl.it/#AnonymousSB/RemarkableBowedNagware

i think you may be looking in the wrong directory for your server.js see this line:
<script src="../server.js"></script>
Make sure the file path is correct, if your index and server.js are in the same fodler it should be:
<script src="./server.js"></script>
I have tested the same code and it works perfectly for me.
Hope this helps.

Youu external javascript file path isn't correct. Replace ../server.js with /server.js

Related

How to make a network call to an endpoint each time a page loads

I'm running website on the local server at (http://127.0.0.1:8080).
I have a file named track located at api/track where api is simply a folder.
I have a file name main.js located at js/main.js.
Finally, I have my index.html file located at the same level with /api and /js.
I would like to make a network call to this endpoint (api/track) each time a page index.html loads.
Also, I'd like to include a timestamp ts (in milliseconds since EPOCH). An Example of the url would be /api/track?ts=1594280202864. I don't need to use the results of this call.
Here is what I did, but I'm not sure it's doing what I want especially the network call part. Can somebody help, please? Thanks
const update = () => {
var dt = new Date();
document.getElementById("date").innerHTML = dt;
//date in millisecodn since EPOCH
var dtInMilSec = dt.getTime();
fetch('/api/track/dtMilSec')
.then(response => response.json())
.then(data => {
console.log(data)
});
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>The Date</title>
<link href="style/main.css" rel="stylesheet" />
</head>
<body onload="update()">
<h1>What's today's date?</h1>
<p>Today is: <span id="date"></span></p>
<script src="js/main.js"></script>
</body>
https://stackoverflow.com/a/25984032/14649968
Maybe take a look at this answer on a related thread, and call your update() function from within the event listener for DOMContentLoaded within the main.js script, rather calling it from the onload attr in the html itself?
document.addEventListener('DOMContentLoaded', () => update(), false);
Seems like you want your fetch URL to be something like
fetch('/api/track?ts=' + dtInMilSec)

How to set redirect to links provided by JS function

I'm having an issue where I'm trying to set a page's redirect destination to a URL from a JS function.
I've tried calling the function by using <meta http-equiv="refresh" in the header, but I either have the syntax wrong or <meta> simply doesn't allow for calling functions. I'm honestly not sure.
<head>
<script src="extFile.js"></script>
<meta http-equiv="refresh" content="1; go2();" id="levP" name="levP">
<title>SO Question</title>
</head>
go2() is a function from extFile.js which contains an if/then statement that provides different URLs depending on time of day. I'd like to have index.html redirect users via function go2() either by a method in the header or in the body.
If this should be handled in the body then I'd appreciate any feedback as to how that should look.
Like this? this code will redirect your page after 5 seconds
<head>
<script src="extFile.js"></script>
<script>
setTimeout(function (){
window.location = "https://stackoverflow.com/questions/57717282/how-to-set-redirect-to-links-provided-by-js-function";
}, 5000);
</script>
<title>SO Question</title>
</head>
if you want a to call a function do this:
<head>
<script src="extFile.js"></script>
<script>
var check = function(){
window.location = "https://stackoverflow.com/questions/57717282/how-to-set-redirect-to-links-provided-by-js-function";
}
check();
</script>
<title>SO Question</title>
</head>

JS doesn't recognizes function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have the problem that even while I call a Function from a different JS-Script correctly I get the error that that function doesn't exist.
I have following function in stopwatch.js:
function timeOut() {
return time;
}
This function is part of a constructor function and time is a variable is that function.
I call it like this in main.js:
time = watch.timeOut();
watch is the object I created using the constructor function.
I have both scripts in index.html like this at the end of the body:
<script type="text/javascript" src="js/stopwatch.js"></script>
<script type="text/javascript" src="js/main.js"></script>
now i get following error code:
main.js:86 Uncaught TypeError: watch.time is not a function
I can't find the reason why this is happening
This is the snippet I stripped it down to the problem:
//stopwatch.js
function stopwatch() {
var time = 3254; //Example Time
function timeOut() {
return time;
}
}
//main.js
var watch = new stopwatch();
var time;
time = watch.timeOut();
console.log(time);
<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>Timer</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script type="text/javascript" src="js/stopwatch.js"> </script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
Something to add is that I have other functions in stopwatch.js and calling them just works fine.
Close. The timeOut function is declared within the scope of the stopwatch function, but there's nothing indicating that it should be visible from outside of that scope. A simple way to do that in this case would be to set it to a property on this within the stopwatch function. Something like this:
function stopwatch() {
var time = 3254; //Example Time
this.timeOut = function() {
return time;
};
}
var watch = new stopwatch();
var time = watch.timeOut();
console.log(time);

How can I make a JavaScript function wait for input or value?

As you can see below, I have a function,createCharacter(), that calls another function, getUserInput(). This function is intended to grab the value of a text input element and return that value to be stored in the "name" variable within the createCharacter. However, if you run this code. It completely runs through both functions, never giving the opportunity for the user to input a value. Perhaps a more specific question is, how can I make this function wait for the variable to be defined before returning it to createCharacter? I've tried to wrap the code in a while loop that will run for as long as value is undefined. Didn't work, created an infinite loop and crashed. ANY solution to this problem will be greatly appreciated. I feel like the solution is so simple, but I just can't figure it out for the life of me. Thanks.
var messageDisplay = document.querySelector(".message-display");
var menuInput = document.querySelector(".menu-input");
var playerInput = document.querySelector(".player-text")
function createCharacter() {
messageDisplay.textContent = "Welcome! What is your name?";
var name = getUserInput();
messageDisplay.textContent = "Hello " + name + "!";
}
function getUserInput() {
var textValue = playerInput.value;
return textValue;
}
createCharacter();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="message-display"></div>
<div class="menu-input">
<form class="menu-input-content">
<input class="player-text" type="text">
<input class="submit-button" type="submit">
</form>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
I think you have a misunderstanding of how the DOM and the user interact. The DOM is event based. You can start by add an change event listener to your input element (or on the submit button):
menuInput.onchange = createCharacter;
And then remove the call to createCharacter, the last line in the code you posted.
This will then call the createCharacter() method when you change the text in the input at all, which is probably not what you want. You could also try:
var menuSubmit = document.querySelector(".submit-button");
menuSubmit.onclick = createCharacter;
And that is probably more on the right track.
However, given your misunderstanding in the first place, perhaps you need to reconsider how you approach your design?
The reason it runs through the code immediately is because of the last line. The browser loads the JS and executes everything in the global scope. Your query selectors are run and stored in those variables, the functions defined, and then on the last line you call one of the defined functions.
To fix this you need to redesign your app to be event based. Keep defining needed variables and functions in the global scope, as you are doing here, but then change your execution to be in response to events.
I think you are looking for something like this. You should be using the events to get what you wanted. You are executing createCharacter() before even the user clicked the Submit button. Hence you see "Hello !" as there is no user input initially.
function submitClicked(event) {
var messageDisplay = document.querySelector(".message-display");
var playerInput = document.querySelector(".player-text");
messageDisplay.innerHTML = "Hello " + playerInput.value;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="message-display"></div>
<div class="menu-input">
<input class="player-text" type="text">
<input class="submit-button" onclick="submitClicked()" type="submit">
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>

Js, document.getElementById("ID").innerHTML, error

Hello I'm new to javascript, and I'm try to write out some code for a test site and I'm having some problems, dow below is my code and I keep getting this error and i can't figure out why.
TypeError: null is not an object (evaluating 'document.getElementById("h3").innerHTML = "<h3>You Are up to date!</h3>"')
This is my second method i tried using. what I'm trying to do it have a have a version list this first one i had was that it would pull a .js file and build a table, but that didn't work so i thought i would try this, but guess what happened? not working
my code that I'm using now is below. if you can help that would be amazing.
thanks, Dakmessier
var current = "1.0";
function get_latest(){
document.getElementById("bob").innerHTML = current;
}
if (local != current){
document.getElementById("Get").innerHTML = "<button>Get the Latest Update!</button>";
} else if (local == current){
document.getElementById("h3").innerHTML = "<h3>You Are up to date!</h3>";
} else {
document.getElementById("h3").innerHTML = "<h3>Sorry, unable to check for update.</h3>";
}
document.getElementById(id) finds an element with a given id value in your HTML. An id value looks like this:
<div id="myHeader">Some Content</div>
And, then you can find that element with:
document.getElementById("myHeader");
ID values must be unique in each document so there should only ever be one element with a given ID.
If an id isn't what you really want, you can find elements other ways, by tag type, by class name, by attribute, etc... using CSS selectors with document.querySelectorAll().
For example, if you wanted to find all <h3> tags, you could do this:
var items = document.querySelectorAll("h3");
Here are some other reasons that document.getElementById(...) might fail to find what you want it to find:
The Javascript code is running before the DOM elements have been parsed and loaded so thus the element is actually not there yet when you're running the code. This is common with code run from the <head> section of the document.
You have an HTML error in how you are specifying the id value in the HTML.
You have an HTML error that causes the browser not to parse your HTML properly.
You have a script error that cause your script to abort before it gets to the part you want to run.
Indeed document.getElementById returns null if it can't find an element with the Id specified.
Also the statement:
if (local != current){
// ..
} else if (local == current){
// ..
} else {
// ..
}
is a bit odd. If local != current is false then local == current must be true. The else if (...) is redundant and the else part will never be run.
hey man the bast thing you should do is the following example, feel free to copy it on your snippet of code:
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed!";
}
<!DOCTYPE html>
<html>
<body>
<p id="demo" onclick="myFunction()">Click me to change my HTML content (innerHTML).</p>
</body>
</html>
I WILL EXPLAIN YOU THIS ANSWER: this is an html + an inline script that makes the inner html work. As far as concerned with your answer it was unclear where your code stopped, anyway test my snippet of code and let me know
I know it's an old question, but I was having the same issue and was trying hard to find the solution for some time.
The problem was that I was executing the script before the page loaded. Thus it wasn't able to find the object that we're trying to catch.
So either use jquery document.ready function or else move your script to the end of the html.
I hope this helps
fix an error of getting the value of a as null
Uncaught TypeError: a is null
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>
<script>
let a = document.getElementById('i');
document.addEventListener('mouseup',function(){
a.innerHTML='clean';
})
</script>
<body>
<h3 id="i">not clean</h3>
</body>
</html>
this shows as error in console as
Uncaught TypeError: a is null
you can fix it by making your script tag before
<!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>
<h3 id="i">not clean</h3>
<script>
let a = document.getElementById('i');
document.addEventListener('mouseup',function(){
a.innerHTML='clean';
})
</script>
</body>
</html>
this might fix!!

Categories