JS doesn't recognizes function [closed] - javascript

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);

Related

How to initiate a function once page has fully loaded to stop a loader [duplicate]

This question already has answers here:
Detect if page has finished loading
(10 answers)
Closed 2 years ago.
Please could someone help me with this set of code
How can I set an event.listener to initiate code when the page has finished loading.
At the moment I have used a setTimeOut but on slow connections the time out for the loader to disappear is too soon, I would like to do it without having to increase the interval time, to initiate the code only once the page and its content has finished loading.
I would greatly appreciate your help.
please see my code below
$('body').append('<div id="loadingDiv"><div class="loader"><img src="./images/loader/image.gif" alt="loadingImage"></div></div>');
let clearLoader = () => {
$("#loadingDiv").fadeOut(500, function () {
$("#loadingDiv").remove();
});
}
setTimeout(clearLoader, 2000);
You can use onload event for the window object like the vanilla javascript snippet below:
window.onload = function (){
console.log('Window finished loading.');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>After loading window</title>
</head>
<body>
</body>
</html>
OR
jQuery way:
$(window).load(function(){
console.log('Window finished loading.');
});

external .js variable coming back undefined?

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

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>

JavaScript addEventListener makes function run directly

My Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ATM Interfacetest</title>
<link rel="stylesheet" type="text/css" href="css/rahmen/rahmen.css">
<script>
function testwindow(){
var tmp = document.createElement('div');
tmp.id = 'idtest';
tmp.className = 'classtest';
document.getElementById('xbuttonsHeinz-Ulf').appendChild(tmp);
document.getElementById('idtest').addEventListener('click', test(), false);
}
function test(){
alert('Alarm!');
}
</script>
</head>
<body onload="testwindow()">
<div id="xbuttonsHeinz-Ulf" class="xbuttons">
<div id="schließenHeinz-Ulf" class="symbol">x</div>
<div id="minimierenHeinz-Ulf" class="symbol"> - </div>
<div id="maximierenHeinz-Ulf" class="symbol">□</div>
</div>
</body>
</html>
Drives me crazy. Trying to add the Eventlistener makes the test() function to be excuted directly, without waiting to clicked.
Whats my mistake.
I searching for a good idea to dynamically create html tags with option to add eventhandlers.
Trying:
tmp.onclick = test();
also executes the function directly w/o waiting for a click.
Given the expressions
test() - the result of a call to the function test with no
arguments passed.
test - a reference to the function test.
You want the latter. The former calls test as soon as the line is reached. addEventListener(...) wants a reference to an EventListener, not the result of the handled event.

Loading and rendering the contents of the window before displaying alert

I'm new to Electron (just like to English :).
I'm trying to output a simple alert after loading and rendering the contents of the main window.
index.html:
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>Test</title>
</head>
<body>
...
Here's some content and images. A lot of them.
...
<script src="alert.js"></script>
</body>
</html>
alert.js:
//Simple alert with some system information
alert("!##$%^&*");
But an alert appears before the contents of the window are drawn. Defer and async don't help (i.e. <script defer async src="alert.js"></script>). What am I doing wrong? It seems to me that this is a very simple and stupid question, but I can not find an answer.
UPD:
The only way I found for now is to use setTimeout:
setTimeout(function(){
alert("!##$%^&*");
}, 300);
Since your code is at the bottom of the page you can us an IIFE (Immediately Invoking Function Expression):
(function() {
alert("!##$%^&*");
}());
You can also use a setTimeout:
(function() {
setTimeout(function () {
alert("!##$%^&*");
} , 2000)
}());

Categories