Unable to load HTML before Javascript - javascript

I am new to Javascript, and know how can I load html before javascript is executed.
I did check the questions on stackoverflow and tried to implement the solutions given but none worked.
Following is the code of various code that I tried.
Wrote script tag before the body ends
wrote the javascript code inside a function and called it inside onload of body but it didn't work either. (Also tried to comment documnet.onload = cal(); and execute).
<!DOCTYPE html>
<html>
<head>
<title>Age Calculator</title>
</head>
<body onload="cal();">
<h1>Age Calculator</h1>
<p>Enter your age and find how many days you have been alive</p>
<script type="text/javascript" src="Age.js"></script>
</body>
</html>
//Javascript code
function cal(){
var age = prompt("How old are you?");
var days = age * 365.25;
alert("You are approx " + days + " days");
}
documnet.onload = cal();
I want the html to be displayed before user is asked How old are you?

The problem is that prompt and similar functions like alert block the browser - they prevent rendering until the pop-up box has been submitted or canceled.
<h1>Age Calculator</h1>
<p>Enter your age and find how many days you have been alive</p>
<script>
var age = prompt("How old are you?");
</script>
If you want to make sure the HTML displays before the prompt comes up, you might use setTimeout, giving the browser a chance to paint the HTML before the prompt gets called:
<h1>Age Calculator</h1>
<p>Enter your age and find how many days you have been alive</p>
<script>
setTimeout(() => {
var age = prompt("How old are you?");
});
</script>
But an even better solution would be to use a proper modal, such as an input box with a submit button, which won't block the browser. (best to never use alert, prompt, and confirm if at all possible)

First of all, I suggest to read this article. Now, based on the source of this document, the best way (using only Javascript) to wait for the document to fully render before executing some code, will be using a listener on the load event of the window element, like this:
window.addEventListener('load', function() {
// Everything has loaded!
});
I have added an image to your code just to test how this approach waits the image to render before prompt to the user:
<h1>Age Calculator</h1>
<p>Enter your age and find how many days you have been alive</p>
<img src="https://via.placeholder.com/500?text=Test+Image">
<script>
function cal()
{
var age = prompt("How old are you?");
var days = age * 365.25;
alert("You are approx " + days + " days");
}
window.addEventListener('load', function()
{
// Everything has been rendered and loaded!
cal();
});
</script>

Related

Calling variable from javascript in an html doc

I work in schools and use google forms to keep track of a number of things.
One of these forms emails people with information from the sheet that is entered.
I have managed to cobble together a good script that provides this service, however, I want it to look good.
My question is simple (or so I believe it is):
When I put in my HTML for the body of the email, how do I call the variables that I have defined earlier in the script?
Do I need to define them in the HTML or can I call them from the JavaScript?
I am not a serious coder by any means but this one has seemed to escape my ability to google it.
Any help would be appreciated.
calling a value of the variable created in javascript, outside the script.
<html>
<script>
var somevariable = "hi"; //this is the variable you create in JavaScript
window.onload = function() {
document.getElementById("blabla").innerHTML = somevariable; //here you send the value of 'somevariable' to html.
}
</script>
<body>
<input type="text" id="blabla" name="someInput"></input>
</body>
</html>
I am not too sure what your code looks like so this is only an attempt to answer what I understand so far.
In you HTML document you don't call variables, you call functions. for example when you click a button, the text would change to what your variable is by calling the onclick Event inside the button, ChangeText() will be the function for the first example:
<!DOCTYPE html>
<html>
<body>
<p id="p1">Hello</p> <br />
<button onclick="ChangeText()">Button</button> <!-- onclick event -->
<script>
var p1 = document.getElementById("p1"); //variable created
function ChangeText () {
//when you click the button this function will be called
p1.innerHTML = "Changed text on button click!";
}
</script>
</body>
</html>
You could also call on the load of the document (but this would mean that you would't see what it was before):
<!DOCTYPE html>
<html>
<body>
<p id="p1">Hello</p> <br />
<script>
var p1 = document.getElementById("p1"); //variable created
p1.innerHTML = "Changed text on page load!"; //change text on load
</script>
</body>
</html>
hope this helps.

How do I insert a GEOIP callout within an Alert Script?

I'm looking for a way to call out the user's city within the alert script, I have tried document.write but I'm no coder and spent several hours to no avail. I can use
<span id="city">{cityname}</span>
on the page itself, but cannot get it to work in the alert script.
<head>
<script type="text/javascript" src="http://www.jsgeoip.com/geoip.js"> </script>
</head>
<body>
<script>
$(document).ready(function() {
$('#city').html(geoip_city());
});
</script>
<script>alert('Welcome CITY HERE User');</script>
</body>
Just move the alert call to after you get the geoip. No use having that second script block, do it all in the one ready function:
$(document).ready(function() {
var geoip = geoip_city();
$('#city').html(geoip);
alert('Welcome ' + geoip + ' User');
});

How To Make a Score Event Script for On-click game using purely HTML, css and Javascript

I need help on my game, in this chase I need help for On-click event. I have a image that for each time I click on it I get 1 score point. I need help to create this quite basic event or someone who be kind enough to write a script for me.
I created a basic code for the clicker game:
<html>
<head>
<title>My Work</title>
</head>
<body>
<img id="nokia" src="phone.jpg" />
</body>
</html>
I haven't made that much progress as you can see, I need help with a on-click event in either html or in JavaScript also a score board system would be a nice touch however I can probably figure this out.
I got a friend to write some code but time was limited I got a half done code if you like to finish it or to tell me what he was trying to do here is that code:
<html>
<head>
<title>My Work</title>
<script>
(function() {
var score = 0;
var phone = document.getElementById("nokia");
phone.onclick=function(){
score++;
output = document.getElementById("score");
output.innerHTML = score;
};
})();
</script>
</head>
<body>
<img id="nokia" src="phone.jpg" />
<div id="score"></div>
</body>
</html>
All help is greatly appreciated! :)
You would do something like this (plain js)
document.getElementById('nokia').onclick=function(){
var score = parseInt(document.getElementById("score").innerHTML);
score++;
document.getElementById("score").innerHTML = score;
}
Here a full example as fiddle: https://jsfiddle.net/sbunu38g/
Note: You will need to set the content of your score div to 0 at the beginning. Otherwise you will receive NaN after clicking the image
Update:
As asked in comments - to be able to use this in your header element you will need to wrap window.onload function around it. By this you will ensure the needed elements are loaded before trying to attack the onclick eventhandler
window.onload = function() {
document.getElementById('nokia').onclick=function(){
var score = parseInt(document.getElementById("score").innerHTML);
score++;
document.getElementById("score").innerHTML = score;
}
};

Function tag seems to not work?

I am trying to write a simple "Choose your own adventure" style game in Javascript format, mainly because its simple to write, but I have run into a problem. I am trying to get the javascript to run on page load, but it wont start. I am just left with a blank page.
Here is the code:
<!doctype html>
<body>
<title>Dungeons and Dwarves</title>
<script type="text/javascript>
function begin() {
alert("Welcome to Dungeons and Dwarves! A free 'Choose Your Own Adventure' game. In this adventure, you will be faced with many decisions, some of which could potentially lead to your death. If you are willing to put your life on the line, and leap forward into a new world and explore the unexplored, press OK to begin.")
var myAge = prompt("How old are you, adventurer?")
if (myAge < 18)
{
alert("Oh! They start younger and younger every year! You'll be careful out there, wont you?")
}
else
{
alert("I see you have had some experience with adventures! I wish you the best of luck, not that you will need it!")
}
}
</script>
<body onload='javascript:begin()'>
</body>
Im not sure what I have done wrong here, but I think the function tag isn't working properly. Just the way it looks in Notepad++, that might just be me. Could anyone give me assistance?
I apologise if I have formatted this wrong.
The browser thinks your JavaScript is not JavaScript (but some other, unknown kind of script):
<script type="text/javascript>
You omitted the second " from the type attribute.
As of HTML 5, the type attribute may be omited if you are using JavaScript, so just write:
<script>
Additionally, you have two <body> start tags. Only one of them has an onload attribute. Browsers may parse the first one and then ignore the second one.
These (among some other errors) would have been picked up by a validator.
You forgot " at:
<script type="text/javascript>
Make sure you put the " in front of >:
<script type="text/javascript">
And as Quentin notes, you have two body tags.
type="text/javascript" //add a " at the end
Correction
<script type="text/javascript">
Try this:
<html>
<head>
<title>Dungeons and Dwarves</title>
<script>
function begin()
{
alert("Welcome to Dungeons and Dwarves! A free 'Choose Your Own Adventure' game. In this adventure, you will be faced with many decisions, some of which could potentially lead to your death. If you are willing to put your life on the line, and leap forward into a new world and explore the unexplored, press OK to begin.")
var myAge = prompt("How old are you, adventurer?")
if (myAge < 18)
{
alert("Oh! They start younger and younger every year! You'll be careful out there, wont you?")
}
else
{
alert("I see you have had some experience with adventures! I wish you the best of luck, not that you will need it!")
}
}
</script>
</head>
<body onload='javascript:begin()'></body>
</html>
You are missing " at:
<script type="text/javascript>
You have misplaces the <body> tag at line number 2: remove body tag from there.
You need to include your <title> tag in <head> tag.
<script type="text/javascript>
would be
<script type="text/javascript">
and <body onload='javascript:begin()'></body>
would be
<body onload='javascript:begin();'></body>
all your alerts need to end like
var myAge = prompt("How old are you, adventurer?");

Variable for img src=

I have a question.
Firstly, I am not going to pretend that I know what I am talking about here. I am a newbie to http and JavaScript.
I think my question may be answered in this post
IMG SRC tags and JavaScript
but I thought I would explain the exact thing I am trying to achieve in case there is an easier way.
I have a webpage, I want to display an image on it. Only thing is, the image is coming from an automated system monitor, the image is automatically generated each day and placed in a new directory depending on date.
e.g. On April 4 = "http://host/partition/2009/apr/04/cpu.gif"
e.g. On April 5 = "http://host/partition/2009/apr/05/cpu.gif"
To facilitate this, I have created some basic JavaScript to give me the date in the format I need it. I have all that working. Now I just want to use that variable I created to show the image.
I have the JavaScript code stored in a function called displaydate()
If I do this <script language="JavaScript"> displaydate() </script> I see
"http://host/partition/2009/apr/05/cpu.gif" and that is correct.
Now how do I display this on the site correctly?
<img src="displaydate()" </td> //This does not work. I am just adding it to show where I have been heading.
P.S. I have read a lot of pages on this and been trying a lot of things, but have had no luck so far. Any help, would be much appreciated.
Yes, that page probably does answer your question. Basically, you want this javascript:
<script type="text/javascript">
document.getElementById('image').src = "yourpicture.png";
</script>
Except you want to replace the "yourpicture.png" with the function you wrote to generate the correct path to the image on disk, so...
<script type="text/javascript">
document.getElementById('image').src = displaydate();
</script>
Of course, you might need to modify this a bit for your own uses, the getElementById will take as an argument whatever the id attribute of your < img > tag is. You probably want to execute the above javascript after your page has loaded, i.e.:
<html>
<head>
<script type="text/javascript">
function load()
{
document.getElementById('image').src = displaydate();
}
function displaydate()
{
//your displaydate() function here
}
</script>
</head>
<body onload="load()">
<img src="nothing.jpg" id="image" name="image"/>
</body>
</html>
You should just need to change this line
document.write("http://host1/Shared/" + year + "/" + month + "/" + day + "/cpu_abs.gif");
to
return "http://host1/Shared/" + year + "/" + month + "/" + day + "/cpu_abs.gif";

Categories