I am somewhat new to programming and have been working through the Head First HTML5 Programming book. On page 65, they have an exercise that helps you insert a javascript function into the HTML head that will change the text located at bullet points in the body of the page. When I open the HTML file in the browser, the page loads, but the content from the Javascript function isn't added to the bullet points. I have determined it's because the script is running before the DOM is complete because when I change the book's code to <body onload="addSongs()">, the page loads correctly.
Here's the code from the book (that doesn't seem to work):
<!doctype html>
<html>
<head>
<title>My Playlist</title>
<meta charset="utf-8">
<script>
function addSongs() {
var song1 = document.getElementById("song1");
var song2 = document.getElementById("song2");
var song3 = document.getElementById("song3");
song1.innerHTML = "Blue Suede Strings, by Elvis Pagely";
song2.innerHTML = "Great Objects on Fire, by Jerry JSON Lewis";
song3.innerHTML = "I Code the Line, by Johnny Javascript";
window.onload = addSongs;
}
</script>
</head>
<body>
<h1> My Awesome Playlist! </h1>
<ul id="playlist">
<li id="song1"></li>
<li id="song2"></li>
<li id="song3"></li>
</ul>
</body>
</html>
I have read through different posts and many people suggested using JQuery (which I'm hoping to learn in the next few months), but I'm just curious as to whether the window.onload = function; has been deprecated since this book was published or if I am making a mistake somewhere. A lot of the exercises in this book use this principle and I can't move forward until I figure this out. Any suggestions or different approaches are appreciated.
Thanks!
You need to move the line:
window.onload = addSongs;
To outside the function.
"I have determined it's because the script is running before the DOM is complete"
The script is running, but all it does is declare a function, it doesn't ever call it (because the aforementioned line is in the wrong place).
it's just a typo.
you put window.onload = addSong; in the definition of the function addSong. so window.onload will never be set, as addSong will never be called.
function addSongs() {
var song1 = document.getElementById("song1");
var song2 = document.getElementById("song2");
var song3 = document.getElementById("song3");
song1.innerHTML = "Blue Suede Strings, by Elvis Pagely";
song2.innerHTML = "Great Objects on Fire, by Jerry JSON Lewis";
song3.innerHTML = "I Code the Line, by Johnny Javascript";
}
window.onload = addSongs; //move this line out of function definition.
You need to move window.onload = addSongs; after define the function, not before it.
like this:
<!doctype html>
<html>
<head>
<title>My Playlist</title>
<meta charset="utf-8">
<script>
function addSongs() {
var song1 = document.getElementById("song1");
var song2 = document.getElementById("song2");
var song3 = document.getElementById("song3");
song1.innerHTML = "Blue Suede Strings, by Elvis Pagely";
song2.innerHTML = "Great Objects on Fire, by Jerry JSON Lewis";
song3.innerHTML = "I Code the Line, by Johnny Javascript";
}
window.onload = addSongs;
</script>
</head>
<body>
<h1> My Awesome Playlist! </h1>
<ul id="playlist">
<li id="song1"></li>
<li id="song2"></li>
<li id="song3"></li>
</ul>
</body>
</html>
Related
I'm trying to swap two HTML paragraphs with a JavaScript button. The code seems to all check out, so I can't seem to figure out why it's not working!
HTML:
<p id="p1"> Donald Drumpf paced and loomed behind Hillary Clinton at times during Sunday night's second presidential debate -- a decision possibly driven by stress during the intensely bitter event, according to body language expert Janine Driver. </p>
<p id="p2"> "He's decreasing stress by doing all that movement," Driver said of Drumpf's behavior on CNN's "New Day" on Monday. </p>
<button onclick="swapT()"> Swap </button>
JS:
function swapT()
{
var obj1 = document.getElementById('p1');
var obj2 = document.getElementById('p2');
var temp = obj1.innerHTML;
obj1.innerHTML = obj2.innerHTML;
obj2.innerHTML = temp;
}
I get the error:
Uncaught ReferenceError: swapT is not defined
What's going wrong?
From the error message you got, it seems that your swapT() function is bound to an inline handler before it's defined. If you're going to call the function from an inline handler, first define the function within the <head> of your document:
<html>
<head>
<script>
function swapT() {
var obj1 = document.getElementById('p1');
var obj2 = document.getElementById('p2');
var temp = obj1.innerHTML;
obj1.innerHTML = obj2.innerHTML;
obj2.innerHTML = temp;
}
</script>
</head>
<body>
<p id="p1">Donald Drumpf paced and loomed behind Hillary Clinton at times during Sunday night's second presidential debate -- a decision possibly driven by stress during the intensely bitter event, according to body language expert Janine Driver.</p>
<p id="p2">"He's decreasing stress by doing all that movement," Driver said of Drumpf's behavior on CNN's "New Day" on Monday.</p>
<button onclick="swapT()">Swap</button>
</body>
</html>
My suggestion is to bind the listener when you define your function, instead:
<html>
<body>
<p id="p1">Donald Drumpf paced and loomed behind Hillary Clinton at times during Sunday night's second presidential debate -- a decision possibly driven by stress during the intensely bitter event, according to body language expert Janine Driver.</p>
<p id="p2">"He's decreasing stress by doing all that movement," Driver said of Drumpf's behavior on CNN's "New Day" on Monday.</p>
<button id="swap">Swap</button>
<script>
function swapT() {
var obj1 = document.getElementById('p1');
var obj2 = document.getElementById('p2');
var temp = obj1.innerHTML;
obj1.innerHTML = obj2.innerHTML;
obj2.innerHTML = temp;
}
document.getElementById('swap').addEventListener('click', swapT);
</script>
</body>
</html>
Here are some relevant links for further reference:
Why put JavaScript in the footer of a page?
Where to place Javascript in a HTML file?
Should I write script in the body or the head of the html?
Does javascript have to be in the head tags?
Okay So this is the code. When I run it. It just has the h1 tag and 3 subparts. It doesn't take value from getElementByID function and assigns it to respective id.
<!Doctype html>
<html>
<head>
<title>My Playlsit</title>
<meta charset="utf-8">
<script>
function addsongs() {
var song1 = document.getElementById('song1');
var song2 = document.getElementById('song2');
var song3 = document.getElementById('song3');
song1.innerHTML = "Blue Suede Strings, By Elvis Pagely";
song2.innerHTML = "Great Objects on Fire, by Jerry JSON Lewis";
song3.innerHTML = "I code the Line,by Johnny Javascripts"
}
window.onload = "addsongs";
</script>
</head>
<body>
<h1>My awesome Playlist</h1>
<ul id="playlist">
<li id = "song1"</li>
<li id= "song2"</li>
<li id = "song3"</li>
</ul>
</body>
</html>
You have missed the > symbol of starting li element.
Also function cannot be assigned as string value. Remove the quotes.
window.onload = addsongs;
I've been trying to make a "Random Quote Machine" that randomly selects a quote from an array of 5 quotes and inserts the text into a paragraph on a webpage. The Machine uses HTML and JavaScript(jQuery). I suspect my error is pretty simple given how simple the project is.
Here's the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Random Quote Machine</title>
<script src="jquery.min.js"></script>
<script src="quotes.js"></script>
</head>
<body>
<h1>Mason Cooley Quotes</h1>
<div>
<p id="quote"></p>
</div>
<button id="quoteGen">Generate A Random Quote</button>
</body>
</html>
Here's the JavaScript:
var quotes = ["Innocence is thought charming because it offers delightful possibilities for exploitation.",
"Every day begins with an act of courage and hope: getting out of bed.",
"Hatred observes with more care than love does.",
"To understand someone, find out how he spends his money.",
"The educated do not share a common body of information, but a common state of mind."
];
function getQuote() {
return Math.floor(Math.random() * quotes.length);
}
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
Because your scripts are included in the head element, the quoteGen button doesn't exist in the DOM at the time that you try to bind an event handler to it. You need to either include the scripts just before the end of your body tag, or wrap your code in a DOM-ready event handler to ensure that the DOM exists as you expect it to when your code runs.
So, you could either go with this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Random Quote Machine</title>
</head>
<body>
<h1>Mason Cooley Quotes</h1>
<div>
<p id="quote"></p>
</div>
<button id="quoteGen">Generate A Random Quote</button>
<script src="jquery.min.js"></script>
<script src="quotes.js"></script>
</body>
</html>
... or, use a DOM-ready handler, such as this:
$(function () {
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
});
Works just fine?
http://jsfiddle.net/tj3dvz1m/.
make sure to run your code in a
$( document ).ready(function() {
Your code here.
});
The handler is being set before the #quoteGen dom node exists.
You need to move the inclusion of quotes.js to the end of your file, right before the closing of /BODY.
Or register the handler to be installed once the document is ready:
$(document).ready(function(){
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
});
This code works fine. Credit to owner.
// Random Quotes
var Quotation=new Array()
Quotation[0] = "Time is of the essence! Comb your hair.";
Quotation[1] = "Sanity is a golden apple with no shoelaces.";
Quotation[2] = "Repent! The end is coming, $9.95 at Amazon.";
Quotation[3] = "Honesty blurts where deception sneezes.";
Quotation[4] = "Pastry satisfies where art is unavailable.";
Quotation[5] = "Delete not, lest you, too, be deleted.";
Quotation[6] = "O! Youth! What a pain in the backside.";
Quotation[7] = "Wishes are like goldfish with propellors.";
Quotation[8] = "Love the river's \"beauty\", but live on a hill.";
Quotation[9] = "Invention is the mother of too many useless toys.";
var Q = Quotation.length;
var whichQuotation=Math.round(Math.random()*(Q-1));
function showQuotation()
{document.write(Quotation[whichQuotation]);}
showQuotation();
Im using basic html and javascript, and it doesnt work in any of my browsers or other computers. I get TypeError: document.getElementById(...) is null.
It works when I use the dev tools/console though. I cannot find anything wrong with what im writing, so I tried a few different ways and all fail with the same error.
<!doctyp html>
<html>
<head>
<title>Simple JSON</title>
<script type="text/javascript">
var info = { "Name":"My name", "Age":"My age", "links":{"PBS":"http://pbs.org", "Google":"http://google.com"}};
var output = "";
for (key in info.links){
output += "<li><a href='"+info.links[key]+"'>"+key+"</a></li>";
}
document.getElementById('links').innerHTML = output;
</script>
</head>
<body>
<ul id="links">
</ul>
</body>
</html>
The problem is your javascript is in the head element and is executed before the actual elements in the body are ready. Put it in an event that is called when the content is ready
document.addEventListener("DOMContentLoaded", function(event) {
var info = { "Name":"My name", "Age":"My age", "links":{"PBS":"http://pbs.org", "Google":"http://google.com"}};
var output = "";
for (key in info.links){
output += "<li><a href='"+info.links[key]+"'>"+key+"</a></li>";
}
document.getElementById('links').innerHTML = output;
});
Your script is running before the page has finished loading, so at the time of execution, your element with the ID links doesnt exist yet. Move the script to the bottom of the page and it should work fine.
<html>
<head>
<title>Simple JSON</title>
</head>
<body>
<ul id="links">
</ul>
<script type="text/javascript">
var info = { "Name":"My name", "Age":"My age", "links":{"PBS":"http://pbs.org", "Google":"http://google.com"}};
var output = "";
for (key in info.links){
output += "<li><a href='"+info.links[key]+"'>"+key+"</a></li>";
}
document.getElementById('links').innerHTML = output;
</script>
</body>
</html>
Try putting your <script> tag at the bottom of the body. The reason why you get null error is because at the time your javascript code executes <ul> tag has not been initialized yet.
HTML is an interpreted language. You need to put your JavaScript code after the closure of the <ul> markup or more generally before </body>
I'm learning a bit HMTL5 to prepare to the 70-480 exam. I'm trying to do some javascript code. It looks something like this:
function inchestometers(inches) {
if (inches < 0)
return -1;
else {
var meters = inches / 39.37;
return meters;
}
}
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
and I have such html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Htnl 5 test</title>
<script src="script/test.js"></script>
</head>
<body>
<p id="hello">Hello</p>
</body>
</html>
In my VS 2012 i have used the Asp.net Empty Web application project and added the Js file and also the html file. The problem is that The function runs properly without any exeptions. This function is taken from here: http://msdn.microsoft.com/en-us/library/cte3c772(v=vs.94).aspx
But whem I'm trying to run the code where I'm getting the document element it' crashint with the error like in the subject. What I've investigated is that the hello gets the null value. I've also tried the code thaken from here:
http://msdn.microsoft.com/en-us/library/yfc4b32c(v=vs.94).aspx - the example with the div. I have the same effect.
What is wrong? I know that there were simmilar subjects but I can't seem to find one matching to mine. Thank you kindly for your help.
Regards
Rafal
you are getting a problem because your javascript code is running before the element
<p id="hello">
is defined.
the simplest solution is to include your script at the end of the body section instead of in the head section but this would cause the document.write call to occur after the rest of the content.
another solution would be to place the code inside two functions like this
function do_conversion() {
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
}
function say_hello() {
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
}
then change the body section like this
<body onload='say_hello()'>
<script>
do_conversion();
</script>
<p id="hello">Hello</p>
</body>