function write(message) not working - javascript

I'm doing the PluralSight JavaScript Fundamentals course and he enters this code into the JavaScript window of jsbin (jsbin.com)
function write(message) {
document.getElementById('message').innerHTML += message + '<br/>';
}
var streetNumber = 49;
var streetName = "Brunswick";
write(typeof streetNumber + " " + streetNumber);
write(typeof streetName + " " + streetName);
and when he Previews it writes out the types and values. The video is a year old and now jsbin has a Render (not Preview) button. When I enter the above code and Render I get a blank screen.
I tried pasting the code into an .html file
<!DOCTYPE html>
<html>
<head>
<!--<meta charset=utf-8 />-->
<title>JS Test</title>
</head>
<body>
<p id="hello">Hello World</p>
<script>
function write(message) {
document.getElementById('message').innerHTML += message + '<br/>';
}
var streetNumber = 49;
var streetName = "Brunswick"';
write(typeof streetNumber + " " + streetNumber);
write(typeof streetName + " " + streetName);
</script>
</body>
</html>
and then opened the file in IE9, and the latest version of Chrome, Firefox, Safari and Opera (my OS is Win7 Ult). They all display Hello World and nothing else. I'm probably missing something really simple here, can someone help me out?

You don't have a message element. Change the #hello element to #message.
<p id="hello">Hello World</p>
To this
<p id="message">Hello World</p>
This is what is needed for the getElementById code to have a place to print your output. Without an element having the requested ID, nothing will turn up, and hence nothing will be printed.
You have a syntax error as well:
/* v----- This little guy here doesn't belong. */
var streetName = "Brunswick"';
Note the umatched single quote at the end of this string. Remove that and you should be good to go:

Related

ReferenceError: event is not defined - Firefox

I have a problem running this code with Firefox (version 32.0)
<!DOCTYPE html>
<html>
<head>
<title>Test A</title>
<script>
function showCoords(evt){
alert(
"clientX value: " + evt.clientX + "\n" +
"clientY value: " + evt.clientY + "\n"
);
}
function begin(){
parag = document.getElementById("parag");
parag.addEventListener("click", function () {showCoords(event); }, false);
}
</script>
</head>
<body onload = "begin()">
<p id="parag">To display the mouse coordinates click in this paragraph.</p>
</body>
</html>
It works in Chrome and other browsers, though when I run it with Firefox 32.0 it gives me this error:
ReferenceError: event is not defined
On the contrary, this code works in Firefox without errors:
<!DOCTYPE html>
<html>
<head>
<title>TestB</title>
<script>
function showCoords(evt){
alert(
"clientX value: " + evt.clientX + "\n" +
"clientY value: " + evt.clientY + "\n"
);
}
</script>
</head>
<body>
<p onclick="showCoords(event)">To display the mouse coordinates click in this paragraph.</p>
</body>
</html>
Can anyone tell me why the former code doesn't work while the latter does?
Again, both work in Chrome but the first is buggy in Mozilla Firefox (32.0).
Thank you in advance.
Note: don't tell me to update the browser (I must use it) nor to use jquery or similar.
Not sure if it worked in Firefox because I don't want to use Firefox.
<!DOCTYPE html>
<html>
<head>
<title>Test A</title>
<script>
function showCoords(evt){
alert(
"clientX value: " + evt.clientX + "\n" +
"clientY value: " + evt.clientY// + "\n"
);
}
function begin(){
parag = document.getElementById("parag");
parag.addEventListener("click", function(e) {showCoords(e);}, false);
}
</script>
</head>
<body onload="begin()">
<p id="parag">To display the mouse coordinates click in this paragraph.</p>
</body>
</html>
Firefox does not have the global window.event available, even the latest version(53.0), but Chrome has.
Try sending event to the begin function like this begin(event) and then send it to the showCoords function on the js side
Also in the js when accepting the event, u can try this,
event = e || windows.event so u can be sure that all browsers get covered

I can't get my program to go down a line and I'm using document.write because its in html using JavaScript

I am new to programing and I am trying to learn how to do JavaScript. The problem in my book says I have to write a program using loops in my html page but they are all on the same line.
This is the program:
<html>
<body>
<script>
var sheepCounted = 0;
while (sheepCounted < 10) {
document.write("I have counted " + sheepCounted + " sheep!");
sheepCounted++;
}
</script>
</body>
</html>
but all it returns is:
I have counted 0 sheep!I have counted 1 sheep!I have counted 2 sheep!I have counted 3 sheep!I have counted 4 sheep!I have counted 5 sheep!I have counted 6 sheep!I have counted 7 sheep!I have counted 8 sheep!I have counted 9 sheep!
(all on one line)
I'm also having the problem on this code
My First proper HTML page
<body>
<h1>Hello</h1>
<p>My First web page.</p>
<script>
var name = "Nick ";
document.write("Hello, " + name);
if (name.length > 7) {
document.write("Wow, you have a REALLY long name!");
}
else {
document.write("Your name isnt very long")
}
</script>
</body>
</html>
please HELP ME!!!!!
First of all, using document.write is not recommended. You should do DOM manipulation. However, since you are new to programming, let's not do that.
All whitespace, that is tabs, newlines and spaces, in HTML is truncated to a single space. In order to actually get a line break on the page, use the tag <br />. Alternatively, you can make each text a paragraph, which semantically makes more sense. To do that, just wrap the text in the <p> tag like <p>text</p>
document.write("<p>I have counted " + sheepCounted + " sheep!</p>");
This also applies to your second problem. Just wrap the text in <p>text</p>
If you want to use DOM manipulation, do something like the below code. Please note that this is a bit more advanced, and it's OK to use document.write while taking your baby steps
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8" />
</head>
<body>
<script>
document.addEventListener("DOMContentLoaded", function() {
for (var i = 0; i < 10; i++) {
var p = document.createElement("p");
p.textContent = "I have counted " + i + " sheep!";
document.body.appendChild(p);
}
});
</script>
</body>
</html>
You almost had it. You just need to add a <br /> element after "sheep!" to force a line break:
....
<script>
var sheepCounted = 0;
while (sheepCounted < 10) {
document.write("I have counted " + sheepCounted + " sheep! <br />");
sheepCounted++;
}
</script>
...

NaN error - Dealing with strings and integers

Making my own version of cookie clicker for the lols at school, having some problems;
<!DOCTYPE html>
<html>
<head>
<title>Patrick Clicker</title>
<script>
var patricks = parseInt(localStorage.getItem("patrickcount"));
function increment(n) {
localStorage.setItem("patrickcount", patricks + n);
document.getElementById("patrickcounter").innerHTML = "Patricks: " + patricks;
}
</script>
</head>
<body>
<img src="patrick.jpg" onclick="increment(1)">
<p id="patrickcounter">
Patricks: 0
</p>
</body>
</html>
When I click my face, it says "Patricks: NaN"
I know what NaN means, but I don't know why the error is being caused.
Any help would be appreciated.
It won't work initially because you don't have a value at first in localStorage.
You can do this :
var patricks = parseInt(localStorage.getItem("patrickcount"))||0;
Do you intentionally display the value before increment ? If that's not your intent, change your function to
function increment(n) {
patricks += n;
localStorage.setItem("patrickcount", patricks);
document.getElementById("patrickcounter").innerHTML = "Patricks: " + patricks;
}
If you want the page to show the right value right before you click, add this at the end of the body :
<script>increment(0)</script>

Call Javascript function from Perl

This should be simple - don't get what I'm doing wrong! This is a very basic test (I'm new to PERL and Javascript) - this is the CGI file:
#! /usr/local/bin/perl
print "Content-type: text/html\n\n";
print "<html>\n" ;
print "<head>Hello\n";
print '<script type="text/javascript" language="javascript" src="wibble.js">\n';
print "</script>\n";
print "</head>\n";
print "<body>\n";
$fred = "Fred";
$numb = 7;
print <<TEST;
<p>Starting...</p>
<p><script type="text/javascript" language="javascript">
theText = "$fred";
theNum = "$numb";
document.writeln("Direct write...");
document.writeln("Number is: " + theNum);
document.writeln("Text is: " + theText);
testWrite(theNum, theText);
</script></p>
<p>...ending JS</p>
TEST
and in wibble.js:
function testWrite(num1, txt1)
{
document.writeln("In testWrite...");
document.writeln("Number is: " + num1);
document.writeln("Text is: " + txt1);
}
In my browser, I get the first set of writeln's but my function is never called. The error on the webpage says 'Object expected' at line 15 (the 'print <<TEST' line).
I mostly suspect I haven't got the right path in my src element but I've tried every combination I can think of ('.', './', full path etc) - nothing works. The js file is in the same dir as the CGI file.
(I actually originally had the function call with no parameters, hoping that theNum and theText are global and will still work (that was the original point of this test program)).
Please put me out of my misery...
As requested, here is source code from browser:
<html>
<head><script type="text/javascript" language="javascript" src="wibble.js"></script>
</head>
<body>
<p>Starting...</p>
<p><script type="text/javascript" language="javascript">
theText = "Fred";
theNum = "7";
document.writeln("Direct write...");
document.writeln("Number is: " + theNum);
document.writeln("Text is: " + theText);
testWrite(theNum, theText);
</script></p>
<p>...ending JS</p>
</body>
</html>
and this is the actual output on the web page:
Starting...
Direct write... Number is: 7 Text is: Fred
...ending JS
Did you check your server's log to see if wibble.js is ever requested? If it's not, then there's your problem. As well, while not really the problem, this line:
print "<head>Hello\n";
is generating bad html. You can't have "bare" text in the <head> block.
For global JS variables, you use the var keyword.
x = 7; // local
var y = 7; // global

Geolocation API in Chrome: coord property of Position undefined

I'm experimenting with the Geolocation API in Google Chrome (v13). I've produced a simple HTML page to get to grips with the basics:
<html>
<head>
<script type="text/javascript">
navigator.geolocation.getCurrentPosition(doStuff, error, setOptions);
function setOptions(geoLoc) {
geoLoc.enableHighAccuracy = true;
geoLoc.timeout = 30;
geoLoc.maximumAge = 0;
}
function doStuff(geoLoc) {
document.getElementById("refreshTimestamp").innerHTML = "Last refresh: " + Date.now();
document.getElementById("latitude").innerHTML = "Latitude: " + geoLoc.coords.latitude;
document.getElementById("longitude").innerHTML = "Longitude: " + geoLoc.coords.longitude;
document.getElementById("altitude").innerHTML = "Altitude: " + geoLoc.coords.altitude;
document.getElementById("accuracy").innerHTML = "Accuracy: " + geoLoc.coords.accuracy;
document.getElementById("altitudeAccuracy").innerHTML = "Altitude Accuracy: " + geoLoc.coords.altitudeAccuracy;
document.getElementById("heading").innerHTML = "Heading: " + geoLoc.coords.heading;
document.getElementById("speed").innerHTML = "Speed: " + geoLoc.coords.speed;
}
function error(geoLoc) {
document.getElementById("error").innerHTML = "ERROR! Code: " + geoLoc.code + "; Message: " + geoLoc.message;
}
</script>
</head>
<body onload="doStuff()">
<p id="refreshTimestamp"></p>
<p id="latitude"></p>
<p id="longitude"></p>
<p id="altitude"></p>
<p id="accuracy"></p>
<p id="altitudeAccuracy"></p>
<p id="heading"></p>
<p id="speed"></p>
<p id="error"></p>
</body>
</html>
Running this page, everything appears fine - the latitude, longitude and accuracy are displayed as expected. However, looking at the Developer Tools Console, I'm presented with an error:
Uncaught TypeError: Cannot read property 'coords' of undefined (geo.html:14)
Debugging it looks like the Position object is undefined at it's first call - the line dealing with latitude. Yet, there are no errors for any of the further lines. In fact, after the latitude line the Postition object comes into existence.
Things I've tried to prevent this error include:
Moving the getCurrentPosition call to after the callback function declarations
assign geoLoc.coords to an XY variable as the first line of the doStuff() function (after doing this, it was this part of the code that caused the error)
Am I calling the Position object incorrectly? Is the a Chrome quirk? Is this something to do with the time it's taking to determine the position?
Thanks,
Chris.
It is undefined because of this:
<body onload="doStuff()">
Maybe you wanted something like this:
function init() {
navigator.geolocation.getCurrentPosition(doStuff, error, setOptions);
}
...
<body onload="init()">

Categories

Resources