JSFiddle - React, Tailwind, and code Playground
by Ty
HTML
<!DOCTYPE>
<html>
<head>
<title>RocketU - Javascript - exercises</title>
<script src="exercise-functions.js/exercise-functions.js"></script>
</head>
<body>
<h1>Javascript Exercises</h1>
<p>Week 1 Javascript exercises</p>
<button onclick="sayHello();">Click me to say hello</button>
<button onclick="sayPersonalHello();">Double-click me to say a personal hello</button>
<button onclick="doTimesTable()">Times table button</button>
<p id="greeting"></p>
<p id="timestable"></p>
<p>Greeting</p>
</body>
</html>
CSS
h1 {
color: green;
}
button {
color: red;
background: black;
}
JavaScript
function sayHello() {
var message = getGreeting();
message += ", World";
window.alert(message);
}
function getGreeting() {
// Declare variables
var greeting;
var today = new Date(),
hour = today.getHours();
// Test the hour value and assign the appropriate message
if (hour < 12) {
greeting = "Good morning";
} else {
greeting = "Good afternoon";
}
// Return the message string
return greeting;
}
function sayPersonalHello() {
// Declare variables
var greeting;
var userName = getUserName();
var addToPage; // Used in exercise 4
// Prompt the user for their name
// Test that they enetered something
// If the field was left empty the value will be an empty string ("")
// If the user clicked 'Cancel' the value will be null
if (userName === "" || userName === null) {
// Nothing entered - display message and exit function (return)
window.alert("Sorry, I don't talk to strangers...");
return;
} else {
// Get the greeting and use it to display a message
greeting = getGreeting();
greeting += ", " + userName + ", how are you?";
// Exercise 3 - use Alert dialog
// window.alert(greeting);
// Exercise 4 - use Confirm dialog
addToPage = confirm(greeting + "\n Would you like this greeting added to the page?");
if (addToPage) {
// Add the greeting text to the placeholder paragraph
document.getElementById("greeting").innerHTML = greeting;
} else {
// Clear any existing text from the paragraph
document.getElementById("greeting").innerHTML = "";
}
}
}
function getUserName() {
return window.prompt("Hi, what is your name?", "");
}
function doTimesTable() {
//...