Javascript div output in html not working - javascript

I am using this innerhtml property to print my output from javascript into a div in html. I have checked other topics with the same problem, but nothing seems to work.
The following code is all between the 'body' tags in my html.
Code:
<script> function firstGame(); </script>
<div id="outputgame"> </div>
<button onclick="functionGame()"> Starten </button>
<script type="text/javascript">
function firstGame()
{
var output = document.getElementById('outputgame');
output.innerHTML('<p>First test</p>');
// Check if the user is ready to play!
confirm("Are you ready to play this epic game?")
var age = prompt("What is your age?");
if (age < 13)
{
document.getElementById('outputgame').innerHTML= "You are to young to play this game. You can proceed, however i do not take any responsibility";
}
else
{
document.getElementById('outputgame').innerHTML= "Sweet, Let's go!";
}
}
</script>

Let's talk about page rendering upon initialization and global scope. A scope is the context in which values and expressions are "visible," or can be referenced. The global scope is the context for the whole document. If a value or function is declared here it's visible in every function or expression.
The JavaScript in your page is being parsed one script block at a time. When the script block is parsed without errors the script block is transferred into the global scope. The thread (stored in the window object) where all public values and expressions are available.
Functions are parsed first, then the rest of the block. However script blocks are parsed one at a time I wrote earlier. So if you make a call to a function not yet in the global scope since it's in another script block that hasn't been parsed yet your code will fail and throw and undefined error.
Consider this:
<script>
function test()
{
alert(1);
}
test();
</script>
A nice alert is shown. the function test is parsed first and test is executed thereafter.
<script>
test();
function test()
{
alert(1);
}
</script>
This also works. Since functions are parsed first test() still works and alerts 1.
<script>
test();
</script>
<script>
function test()
{
alert(1);
}
</script>
This however won't work. Since the function test in the second script block isn't yet parsed calling test() will result in a script error.
<script>
function test()
{
alert(1);
}
</script>
<script>
test();
</script>
This does work. The function is declared first and added to the global scope. In the second script block test() looks for a function test in the global scope, finds it and executes it.
This is the explanation above applied to your code:
<div id="outputgame"> </div>
<button onclick="functionGame()"> Starten </button>
<script type="text/javascript">
function firstGame()
{
var output = document.getElementById('outputgame');
output.innerHTML = '<p>First test</p>';
// Check if the user is ready to play!
// Do you really need this?
//Confirm returns a Boolean (true or false), you can do something with the result. If not just show an alert or nothing. Latter is preferred.
confirm("Are you ready to play this epic game?")
var age = prompt("What is your age?");
//You should make this more robust. What if someone enters "asaaslk". Use a select box with birth years.
if (age < 13)
{
document.getElementById('outputgame').innerHTML = "You are to young to play this game. You can proceed, however i do not take any responsibility";
}
else
{
document.getElementById('outputgame').innerHTML = "Sweet, Let's go!";
}
}
</script>
<script> function firstGame(); </script>

<div id="outputgame"> </div>
<button onclick="firstGame()"> Starten </button>
<script type="text/javascript">
function firstGame()
{
var output = document.getElementById('outputgame');
output.innerHTML = '<p>First test</p>';
// Check if the user is ready to play!
confirm("Are you ready to play this epic game?")
var age = prompt("What is your age?");
if (age < 13)
{
document.getElementById('outputgame').innerHTML= "You are to young to play this game. You can proceed, however i do not take any responsibility";
}
else
{
document.getElementById('outputgame').innerHTML= "Sweet, Let's go!";
}
}
</script>

HTML
<div id="outputgame"> </div>
<button onclick="firstGame()"> Starten </button>
javascript
<script type="text/JavaScript">
function firstGame()
{
var output = document.getElementById('outputgame');
output.innerHTML='<p>First test</p>';
// Check if the user is ready to play!
confirm("Are you ready to play this epic game?")
var age = prompt("What is your age?");
if (age < 13)
{
document.getElementById('outputgame').innerHTML= "You are to young to play this game.You can proceed, however i do not take any responsibility";
}
else
{
document.getElementById('outputgame').innerHTML= "Sweet, Let's go!";
}
}
</script>

Two problems: You named your function the wrong name?, and you are calling innerHTML as a function instead of assigning it a value.
Also, where is functionGame() defined? You cannot use forward declarations like in C.
function firstGame() {
var output = document.getElementById('outputgame');
var text = '';
output.innerHTML = '<p>First test</p>';
// Check if the user is ready to play!
confirm("Are you ready to play this epic game?")
var age = parseInt(prompt("What is your age?"), 10);
if (age < 13) {
text = "You are to young to play this game. You can proceed, however I do not take any responsibility.";
} else {
text = "Sweet, Let's go!";
}
document.getElementById('outputgame').innerHTML = text;
}
<div id="outputgame"></div>
<button onclick="firstGame()">Starten</button>

Related

Stop a portion of Javascript function from auto firing

Is it possible to stop the script and wait for user input before continuing it?
Here is the portion that I need to stop:
var nName = document.getElementById("b1");
nName.innerHTML = "Continue";
document.getElementById("b1").onclick = newName();
So "b1" is a HTML button, I want to stop it after
nName.innerHTML = "Continue";
and wait for user click on the button before firing
document.getElementById("b1").onclick = newName();
using return completely stop the script. Is there any other possible way to do this?
You do not need to stop the script. You cannot.
Pass references to the functions (no paranthesis on the function names) like so:
document.getElementById("b1").onclick = newName;
Example:
function firstClick(){
document.getElementById('b1').innerHTML = "Continue"
// override the first click listener. "firstClick" will no longer be called.
document.getElementById('b1').onclick = newName;
}
function newName(){
document.getElementById('b1').innerHTML = "Good Job!"
}
// listen for first click
document.getElementById('b1').onclick = firstClick
<button id=b1>Click Me!</button>
In order to fully understand what is going on, I do must refer you do Google and Documentation, and most of all - Experimentation.
But in short, in not technical terms.
onclick does nothing on its own. It needs to be told what it does. The browser will do what you tell it to. There can only be 1 function assigned to it. So if you do onclick=a; onclick=b; onclick=c, only c will be called.
If you assign the function name with paranthesis onclick = newName(), what you are doing is you are running the newName() and assigning its return to the onclick. So in this case - nothing. If you do onclick=newName the borwser will automatgically add the paranthesis.
You could even create a 'triaging' function to decide what the next steps are:
function triage(){
var el = document.getElementById('b1');
if (el.innerHTML == "Continue"){
el.innerHTML = 'Good Job!';
}else{
el.innerHTML = 'Continue';
}
}
// listen for first click
document.getElementById('b1').onclick = triage
<button id=b1>Click Me!</button>

call javascript function only once inside if statment

In this if statement I can call a function to alert a message if the statement are true but the problem I get the message more that one time every time I click on ok button on the message box I get the same message box, again and again, I want to get the message only one time (I want to call the function only one time in the if statement ) are there any way for that ?
My if statement loop
if(brd_side == COLOURS.WHITE) {
firstmassege();
} else {
secondmassege();
}
My functions :
function firstmassege() {
alert('the first massege');
}
function secondmassege() {
alert('the second massege');
}
This Code should simply work. Hope this would be useful. This displays the first message only once and the second message after the button is clicked for the second time as required.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to test the Function</p>
<button onclick="myFunction()">Click </button>
<p id="demo"></p>
<script>
var executed = false;
function myFunction() {
if (!executed){
firstmessage();
executed = true;
} else {
secondmessage();
}
}
function firstmessage() {
alert('the first message');
}
function secondmessage() {
alert('the second message');
}
</script>
</body>
</html>
How about using a flag to store the status. Please see the code below.
$('#btn').click(firstmessage)
var clicked = false;
function firstmessage() {
console.log('other statements...')
if(!clicked){
alert('the first massege');
}
clicked = true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">click</button>
In your case it will be like below
var flag =false;
if (!flag){
firstmessage();
flag = true;
}
You can use one in jquery:
$('#myButton').one('click', function(){ alert('Hi!');});

Javascript: Using while loop to wait for document load not working

I'm trying to create an html document for my coworkers to complete an online test (I have the right answers). When the document loads, it requests your user and password and tries to log in, then fill the answers and submit.
However I can't pass the user and password values to the elements in the page, this is the error:
Cannot set property 'value' of null
The page is not loading completely when my script tries to get its elements, how could I make this work?
<html>
<head>
<title>BCG test</title>
<script type="text/javascript">
function bcg(){
var user = prompt("Enter username: ");
var pass = prompt("Enter password: ");
var site = "http://app.huawei.com/bcg";
location = site;
while(true){
if (document.readyState == "complete"){
break;
}
}
var user_box = document.getElementById("uid");
var pass_box = document.getElementById("password");
var submit_button = document.getElementsByName("Submit")[0];
user_box.value = user;
pass_box.value = pass;
submit_button.click();
}
</script>
</head>
<body onload = "bcg()">
<h1>BCG TEST</h1>
</body>
</html>
You shouldn't use a while(true) loop because that loops infinitely fast, forever. That will cause the browser to freeze. If you need to keep checking something, set a timer with setInterval.
However, for this purpose, it appears you want to wait until the page loads. Put your code to be executed in this block instead:
document.addEventListener("DOMContentLoaded", function() {
var user_box = document.getElementById("uid");
var pass_box = document.getElementById("password");
var submit_button = document.getElementsByName("Submit")[0];
user_box.value = user;
pass_box.value = pass;
submit_button.click();
});
You can't do that in javascript:
while(true){if(document.readyState == "complete"){ break; }}
It will never exit this event frame.
use window.onload = function(){} or $(document).ready(function(){})
Any of these functions will be called when document loads.

after using parenthesis () my function not running?

My first code working but second code not working after adding () parenthesis after myFunction. What is the reason?
Code1
<script type="text/javascript">
function myFunction(){
var status = document.getElementById("status");
status.innerHTML = "The page finishing loading made my function run.";
}
window.onload = myFunction;
</script>
<h3 id="status"></h3>
Code 2
<script type="text/javascript">
function myFunction(){
var status = document.getElementById("status");
status.innerHTML = "The page finishing loading made my function run.";
}
window.onload = myFunction();
</script>
<h3 id="status"></h3>
In first case you're assigning the reference of the function which will be used in callback.
In your second case you're assigning the value that is being returned by the function which is in this case undefined as you're not returing anything.
window.onload or any event handler for that matter, expects a function reference to be executed on callback.
window.onload is an event handler and must be a function, not the result of function. of course you may leave parenthesis, but in this way your function myFunction should return another function
<script type="text/javascript">
function myFunction(){
return function() {
var status = document.getElementById("status");
status.innerHTML = "The page finishing loading made my function run.";
}
}
window.onload = myFunction();
</script>
<h3 id="status"></h3>

Why Won't This Simple Event Listener Work in Javascript?

I was wondering if someone could provide a teaching point for me. I am trying to learn Javascript and the logic of this code seems reasonable to me, but it doesn't work for some reason.
It's basically a button. I'm trying to make it so that when the button is clicked, the variable testingVar changes to one of the conditions of my switch statement. Yet when I click the button, there's no alert that happens.
Can someone please explain why nothing is alerted when I click the button and how I would make it work?
<html>
<body>
<a id="myButton" href="#">CLICK</a>
<script>
var myButton = document.getElementById("myButton");
var testingVar;
myButton.addEventListener("click", function() {
testingVar = "hello";
}, false);
switch (testingVar) {
case "hello" :
alert("You've got the hello condition!");
break;
case "goodbye" :
alert("You've got the goodbye condition");
break;
} // end switch statement
</script>
</body>
</html>
Thanks.
The other answers failed to notice the reason for the question which is to understand why it doesn't work.
The reason why it doesn't work is because of how JavaScript gets executed.
var myvar; // myvar is declared, but not defined yet. myvar === undefined
function foo(){
myvar = true;
console.log('EVENT!');
}
// obviously at this point, `foo` has just been declared, not called/executed.
myButton.addEventListener('click', foo);
// foo still hasn't been executed. It has been assigned as handler to be executed whenever a click event is fired
switch(myvar) { // myvar is still undefined, because foo hasn't been executed
...
}
window.setTimeout(function(){
console.log('Checking myvar');
console.log(myvar);
}, 5000); // the function defined here will be called after 5 secnds
/* time passes, mouse is clicked */
// now foo is executed
EVENT!
/* 5 seconds have passed, the function in setTimeout is executed */
Checking myvar
true
The switch must be inside the function of the event Listener:
myButton.addEventListener("click", function() {
testingVar = "hello";
switch (testingVar) {
case "hello" :
alert("You've got the hello condition!");
break;
case "goodbye" :
alert("You've got the goodbye condition");
break;
} // end switch statement
}, false);
In your example, the variable testingVar is initalized, but has no value assigned when the switch part of the code is executed.
Also, if you had defined a default case, you would have recognised that the switch is called on pageload.
Try this:
<script>
var myButton = document.getElementById("myButton");
var testingVar;
myButton.addEventListener("click", function() {
testingVar = "hello";
switch (testingVar) {
case "hello" :
alert("You've got the hello condition!");
break;
case "goodbye" :
alert("You've got the goodbye condition");
break;
} // end switch statement
}, false);
</script>
As a side note, it's usually better to put your script tags in the head of your html.

Categories

Resources