Listings 17.03 and 17.04 - Adding content to a paragraph with JavaScript
JS Bin
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>My Movie Ratings</title>
</head>
<body>
<p id="greeting">Welcome!</p>
</body>
</html>
JS:
(function () {
function getGreeting () {
var hellos = [
"Nanu nanu!",
"Wassup!",
"Yo!",
"Hello movie lover!",
"Ay up me duck!",
"Hola!"
];
var index = Math.floor(Math.random() * hellos.length);
return hellos[index];
}
function updateGreeting () {
para.innerHTML = getGreeting();
}
var para = document.getElementById("greeting");
updateGreeting();
})();
Listings 17.03 and 17.04 - Adding content to a paragraph with JavaScript - Tasks 1 to 3
- Add a heading to the HTML, before the paragraph.
- Give the heading an id attribute.
- Use JavaScript to update the heading.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>My Movie Ratings</title>
</head>
<body>
<h1 id="title">Random Greetings</h1>
<p id="greeting">Welcome!</p>
</body>
</html>
JS:
(function () {
function getGreeting () {
var hellos = [
"Nanu nanu!",
"Wassup!",
"Yo!",
"Hello movie lover!",
"Ay up me duck!",
"Hola!"
];
var index = Math.floor(Math.random() * hellos.length);
return hellos[index];
}
function updateGreeting () {
para.innerHTML = getGreeting();
}
var para = document.getElementById("greeting");
updateGreeting();
var heading = document.getElementById("title");
heading.innerHTML = "This Heading was added with JavaScript";
})();