Javascript prompt command executes before the documents writes - javascript

I have a problem with the code below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/main.css">
<title>The Ultimate Quiz Challenge</title>
</head>
<body>
<div class="container">
<h1>The Ultimate Quiz Challenge</h1>
<script>
document.write("<h3> " + "Welcome to the ultimate quizz challenge" +"</h3>");
document.write("<p> "+"Hi I will ask you five questions and then rank you" + "</p>");
var question1 ="<p>What is the capital of England</p>";
var firstanswer ="London";
var question2 = "<p>How many sides are there to a square</p>";
var secondanswer = 4;
var noofquestions = 2;
var count = 1
/*var temp = eval('question' +1); */
/*document.write(temp);*/
/* main loop asking questions */
while (count <= 2) {
var temp = eval('question' + count);
document.write(temp);
var answer = prompt("Please type your answer ");
count++;
}
</script>
</div>
</body>
</html>
When I load the file into a browser such a chrome or safari it does not execute as hoped.
In short the document.write commands do not come out onto the screen until the prompt window as asked for two inputs. I thought the first thing to be seen would be the Ultimate Quiz Challenge followed by the commands in the open script tag down to the bottom ?

You should use the onload event on your body, so your script executes once the html page is rendered. It should work with :
<body onload="displayText()">
displayText() being a function you define in your script :
var displayText = function () {
while (count <= 2) {
var temp = eval('question' + count);
document.write(temp);
var answer = prompt("Please type your answer ");
count++;
}
};
or something similar.

Related

Why doesn't my element update during the else part but during the if part?

I'm making a program where it has a collection of calculators, and for some reason when I try to change the innerhtml of a certain text it only changes it during the if statement and not during the else part.
function Palindrome() {
//Fix not changing to processing when doing new palindrome.
var Division = 0;
var input = document.getElementById("PalindromeInput").value;
var GiveAnswer = document.getElementById("PalindromeAnswer");
var Answer = String(input);
while (0 < 1) {
if (Answer == Answer.split("").reverse().join("")) {
GiveAnswer.innerHTML = `That is a palindrome of the ${Division}th Division.`;
break
} else {
GiveAnswer.innerHTML = `Processing...`;
Division = Division + 1;
Answer = String(parseInt(String(Answer)) + parseInt(Answer.split("").reverse().join("")));
};
};
};
https://replit.com/#ButterDoesFly/Arcane-Calculators#index.html
I'm not sure but I guess the reason for this is that the function never goes to the else part because it gets break every time. Remember that .reverse() reverses the array in place so the if statement will always be true. Try to add different variable for the reversed answer.
function Palindrome() {
//Fix not changing to processing when doing new palindrome.
var Division = 0;
var input = document.getElementById("PalindromeInput").value;
var GiveAnswer = document.getElementById("PalindromeAnswer");
var Answer = String(input);
GiveAnswer.innerHTML = `Processing...`;
setTimeout(()=>{
while (0 < 1) {
if (Answer == Answer.split("").reverse().join("")) {
GiveAnswer.innerHTML = `That is a palindrome of the ${Division}th Division.`;
break
} else {
Division = Division + 1;
Answer = String(parseInt(String(Answer)) + parseInt(Answer.split("").reverse().join("")));
};
};
},1000)
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<p id="PalindromeAnswer">This will tell you the number its at and then the answer.</p>
<input type="text" id="PalindromeInput" placeholder="What number would you like to enter?">
<br>
<input type="button" onclick="Palindrome()" value="Submit" id="PalindromeButton">
<script src="script.js"></script>
<!--
This script places a badge on your repl's full-browser view back to your repl's cover
page. Try various colors for the theme: dark, light, red, orange, yellow, lime, green,
teal, blue, blurple, magenta, pink!
-->
<script src="https://replit.com/public/js/replit-badge.js" theme="blue" defer></script>
</body>
</html>
result is rendering very fast such that changes are not reflecting in ui..add a timeout so that changes reflect in front end

I want to get two integers from a user via a text input, find the difference between the two numbers and divide that number by 25. How do I do this?

I'm making a small website as a test. Very new to JavaScript and HTML forms so I thought i'd throw myself into what I consider to be the deep end and give it a go.
I'm trying to get an interger to be displayed on the page, that is the result of a few calculations.
I want to find the difference between the first number (current value), and the second number (desired value) and then divide that number by 25 and store that as a variable. I then want to display that variable inside a message.
My current HTML :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<title>MMR calculator</title>
</head>
<body>
<h1>Type in your current MMR, and your desired MMR and click "Calculate"</h1>
<form>
<input type="text" id="currentRating" placeholder="What is your current MMR?">
<input type="text" id="desiredRating" placeholder="What is your desired MMR?">
<input type="submit" onclick="calculate()">
</form>
<script src="js/main.js"></script>
</body>
</html>
My current JavaScript :
function calculate() {
var currentRating = document.getElementById("currentRating");
var desiredRating = document.getElementById("desiredRating");
var difference = desiredRating - currentRating;
var gamesToPlay = difference / 25;
document.write("You need to play " + gamesToPlay + " to get to " + desiredRating);
}
You are 99% there. All you have to do is change
var currentRating = document.getElementById("currentRating");
var desiredRating = document.getElementById("desiredRating");
into
var currentRating = parseInt(document.getElementById("currentRating").value);
var desiredRating = parseInt(document.getElementById("desiredRating").value);
The way you had it, those variables just held the HTML (technically, DOM) elements themselves, and not the values that were in them. This gets the values and then turns them into integers so you can do math with them. If you do this, your site do exactly what you want it to do.
Be careful:
var currentRating = document.getElementById("currentRating").value;
is a String (text) value... to be sure of int value you can do
try{
var currentRatingInt = parseInt(currentRating);
}catch(e){
alert(currentRating + " is not an integer");
}
If you like to display result in page you can use a DIV with and id and do:
document.getElementById("idOfYourDiv").innerHTML = "What you like to display in div";
hope this code will help :
html :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<title>MMR calculator</title>
</head>
<body>
<h1>Type in your current MMR, and your desired MMR and click "Calculate"</h1>
<div>
<input type="text" id="currentRating" placeholder="What is your current MMR?">
<input type="text" id="desiredRating" placeholder="What is your desired MMR?">
<button onclick="calculate();">Calculate</button>
</div>
<script src="js/main.js"></script>
</body>
</html>
javascript :
function calculate() {
var currentRating = document.getElementById("currentRating").value;
var desiredRating = document.getElementById("desiredRating").value;
var gamesToPlay = (desiredRating - currentRating) / 25;
gamesToPlay = Math.abs( parseInt(gamesToPlay) );
alert("You need to play " + gamesToPlay + " to get to " + desiredRating);
}
Subtract first field from the other, and if the value is not greater than 0 multiply by -1.
Divide that by 25.

Cannot set property 'innerHTML' of null while still using window.onload to delay

I am trying to write a script that changes the color of the text if it is an active screen (there are probably more efficient ways to do this). The error I am getting is Uncaught TypeError: Cannot set property 'innerHTML' of null My JavaScript (the entire page)
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
main();
The HTML
<!DOCTYPE html>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<html>
<head>
<title>
</title>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script src="../scripts/essentials.js"></script>
</body>
</html>
The IDE (Visual Studio 2015 Cordova) says that the error is on this line in the JavaScript "var cardDivPrint = cardDiv + card + closer;" I have looked at multiple similar problems and applied what was relevant (also tried changing window.onload to document.onload) but it still throws the same error.
onload expects function to be executed after page is completely loaded. Otherwise it'll treat it as simple assignment statement and execute. Use function as follow:
window.onload = function() {
document.getElementById("header").innerHTML = cardDivPrint;
};
UPDATE
Instead of using main(), use DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = window.location.href.indexOf(Check) !== -1 ? "red" : "white";
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
document.getElementById("header").innerHTML = cardDivPrint;
});
Call the main function at the end of your body content
You are getting this error just because the element dose not exists at the time of its selection by JS DOM
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<script>
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
</script>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script>main();</script>
</body>
</html>

Javascript/HTML Image Change

My task for my Javascript class is to create a script for this page that changes the image every 3 seconds. I think my code is correct, however Firebug tells me "document.getElementByID is not a function." Can someone show me what I am doing incorrectly?
This is my JS script.
<script type="text/javascript">
var i = 0
var lightArray = ["pumpkinOff.gif", "pumpkinOn.gif"]
var currentLight = document.getElementByID('light')
// ChangeLight Method Prototype
function changeLight() {
currentLight.src = lightArray[i++];
if (i == lightArray.length) {
i = 0;
}
}
setInterval(changeLight, 3000)
</script>
Here is my edited HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript for Programmers</title>
</head>
<body>
<h2>Happy Halloween!</h2>
<img id="pumpkin" src="pumpkinoff.gif" alt="pumpkin">
<script src="../Script/spooky.js"></script>
</body>
</html>
Incorrect capitalisation on
var currentLight = document.getElementByID('light')
Should be:
var currentLight = document.getElementById('pumpkin')
I have attached a working fiddle:
http://jsfiddle.net/11csf4k2/
It's a typo it should be:
var currentLight = document.getElementById('light'); //Not ID
It should be Id not ID:
document.getElementById('light');
Also note that you don't have element with id light on your page. It probably should be
document.getElementById('pumpkin');

How Do You Run the ENTIRE Javascript Page From An Button In HTML?

I have been trying to make all my Javascript Page code from JSBin to work automatically upon the clicking of a button. Problems include not being able to run the code because it says I have multiple variables in my script that do not work together and not being able to put it all in HTML because console.log doesn't work. I tried a couple different ideas, but sadly, I am unable to do it correctly.
My Code Is:
var name = prompt('So what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
var name = prompt('Than what is your name?');
var confirmNamed = confirm('So your name is ' + UCFL(name) + '?');
}
if (confirmNamed === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmNamed === false) {
var name = prompt('Than what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
alert('Oh, guess what? I do not even fucking care what your name is anymore. Lets just
start..');
var start = confirm('Are you ready?');
}
}
if (start === true) {
var x = console.log(Math.floor(Math.random() * 5));
if (x === 1) {
alert('You are an dwarf in a time of great disease.');
alert('');
}
}
And this is what I want you to fix:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="" />
</form>
</body>
</html>
I've created an entry on JSBin suggesting many improvements to what you have now:
http://jsbin.com/epurul/3/edit
Visit the entry to test the code yourself. Here is the content, for convenience:
HTML:
<body>
<button onclick="playGame()">Play Game</button>
</body>
And JavaScript:
// Expose playGame as a top-level function so that it can be accessed in the
// onclick handler for the 'Play Game' button in your HTML.
window.playGame = function() {
// I would generally recommend defining your functions before you use them.
// (This is just a matter of taste, though.)
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
// Rather than capitalize name everywhere it is used, just do it once
// and then use the result everywhere else.
function getName(message) {
return UCFL(prompt(message));
}
var name = getName('So what is your name?');
// Don't repeat yourself:
// If you're writing the same code in multiple places, try consolidating it
// into one place.
var nameAttempts = 0;
while (!confirm('So your name is ' + name + '?') && ++nameAttempts < 3) {
// Don't use 'var' again as your name variable is already declared.
name = getName('Then what is your name?');
}
if (nameAttempts < 3) {
alert('Good. Lets start the roleplay, Sir ' + name + '.');
} else {
alert("Oh, guess what? I do not even fucking care what your name is anymore. Let's just start...");
}
};
Put your code in a function, for example:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
function runGame() {
// put your js code here
}
</script>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="runGame();" />
</form>
</body>
</html>
It would also be a good idea to copy your js code to another file and import that using a script tag, for instance:
<script src="path/to/file.js"></script>

Categories