In this article, we will create an alarm clock using JavaScript with the following features:
- Display the current time on screen
- Allow users to set an alarm
- Display the alarm time once set
- Allow users to clear exisiting alarm
We will first learn how to display the current time on screen using JavaScript Date. Next, we will create a JS form to allow users to set a new alarm and clear existing alarm values.
1. Create <div></div> to display current time
First, we will create <div></div> container in HTML to display the current time.
<div id="app">
<h1>Current Time</h1>
<div id="current-time"></div>
</div>
2. Function to render current time on screen
Once we have the HTML container in place, we need to add JavaScript code to inject the current date text into the HTML container. We will create two JS functions to accomplish this feature:
- The getTimeString() generates the time string for the provided hours, minutes, seconds and zone.
- The renderTime() displays current time on the screen.
In renderTime() function, we find the current time using “new Date()” JS code and retrieve string value of the time from getTimeString() function before displaying it on screen using .innerHTML dom property.
// Function to convert time to string value
const getTimeString = ({ hours, minutes, seconds, zone }) => {
if (minutes / 10 < 1) {
minutes = "0" + minutes;
}
if (seconds / 10 < 1) {
seconds = "0" + seconds;
}
return `${hours}:${minutes}:${seconds} ${zone}`;
};
// Function to display current time on screen
const renderTime = () => {
var currentTime = document.getElementById("current-time");
const currentDate = new Date();
var hours = currentDate.getHours();
var minutes = currentDate.getMinutes();
var seconds = currentDate.getSeconds();
var zone = hours >= 12 ? "PM" : "AM";
if (hours > 12) {
hours = hours % 12;
}
const timeString = getTimeString({ hours, minutes, seconds, zone });
currentTime.innerHTML = timeString;
};
// Update time every second
setInterval(renderTime, 1000);
3. JS form for creating alarm
To allow users to provide input for creating alarms, we need to first add an HTML form. Further, we will use the “required” property to throw errors when the user tries to submit empty fields. Specifying “min” and “max” properties disallow users from entering invalid values.
<div class="create-alarm">
<div>Set Alarm</div>
<div class="form-actions">
<form>
<div class="alarm-inputs">
<input
type="number"
name="hour"
placeholder="Enter hours"
min="0"
max="12"
required
/>
<input
type="number"
name="min"
min="0"
max="60"
placeholder="Enter minutes"
required
/>
<input
type="number"
name="sec"
min="0"
max="60"
placeholder="Enter seconds"
required
/>
<select name="zone" required>
<option value="" selected disabled>Zone</option>
<option value="AM">AM</option>
<option value="PM">PM</option>
</select>
</div>
<button>Submit</button>
</form>
</div>
</div>
</div>
4. Handle create alarm form submit
Now we need to add JavaScript code to handle the HTML form submit by creating handleSubmit() function. The “event.preventDefault()” code prevents reloading of the page on submit and we can access all the form input values by “name” property through document.form array.
Further, we set the alarmString variable with the string value of alarm time from the input form and reset the form. The alarmString variable will be used in later steps to decide to trigger the alarm.
// String value of current active alarm
var alarmString = null;
// Handle Create Alarm submit
const handleSubmit = (event) => {
// Prevent default action of reloading the page
event.preventDefault();
const { hour, sec, min, zone } = document.forms[0];
alarmString = getTimeString({
hours: hour.value,
seconds: sec.value,
minutes: min.value,
zone: zone.value
});
// Reset form after submit
document.forms[0].reset();
};
// Attach submit event to the form
document.forms[0].addEventListener("submit", handleSubmit);
5. <div></div> to display active alarm
Once the alarm is set, we need to show a confirmation of the exact time at which the alarm is set. We accomplish that by first adding <div></div> container for active alarm.
<div id="active-alarm">
<div id="alarm-text"></div>
</div>
6. Display Active alarm time
Now we will add JavaScript code to display the active alarm on the HTML container created in the previous step. Hence we update the handleSubmit() function to hide the create-alarm container and display active-alarm container which is hidden by default. Additionally, we will also assign the alarm string to the inner HTML of alarm-text container thus displaying it on the screen.
// Select DOM element of active alarm container
const activeAlarm = document.getElementById("active-alarm");
// Select DOM element of active alarm text
const alarmTextContainer = document.getElementById("alarm-text");
// Update function to display active alarm on screen
const handleSubmit = (event) => {
// Prevent default action of reloading the page
event.preventDefault();
const { hour, sec, min, zone } = document.forms[0];
alarmString = getTimeString({
hours: hour.value,
seconds: sec.value,
minutes: min.value,
zone: zone.value
});
// Reset form after submit
document.forms[0].reset();
// Hide create alarm
createAlarm.style.display = "none";
// show active alarm with text
activeAlarm.style.display = "block";
alarmTextContainer.innerHTML = alarmText(alarmString);
};
7. Trigger alarm sound when current time == alarm time
To trigger an alarm sound, we will first add an HTML5 audio tag to index.html.
<audio id="alarm-audio"></audio>
Next, we will select the declared audio tag using the DOM selector and initialize the audio tag with the alarm file URL. Now to trigger the alarm, we will add checkAlarm() function to renderTime() which is triggered every second.
The checkAlarm() function compares the alarm time with the current time and plays the alarm audio if both are equal.
// Select DOM element of active alarm text
const alarmTextContainer = document.getElementById("alarm-text");
const alarmText = (time) => `Alarm set at time ${time}`;
// Initialize alarm sound
alarmAudio.src = "http://soundbible.com/grab.php?id=1252&type=mp3";
alarmAudio.load();
// Function to check if alarm needs to be triggered
const checkAlarm = (timeString) => {
if (alarmString === timeString) {
alarmAudio.play();
}
};
// Update function to check alarm along while rendering current time
const renderTime = () => {
var currentTime = document.getElementById("current-time");
const currentDate = new Date();
var hours = currentDate.getHours();
var minutes = currentDate.getMinutes();
var seconds = currentDate.getSeconds();
var zone = hours >= 12 ? "PM" : "AM";
if (hours > 12) {
hours = hours % 12;
}
const timeString = getTimeString({ hours, minutes, seconds, zone });
checkAlarm(timeString);
currentTime.innerHTML = timeString;
};
8. Function to clear created alarm and reset
Once the alarm is set, the user might want to the clear existing alarm and set a new alarm time. In order to support this, we update the active alarm container by adding an HTML button with the id “clear-alarm”.
<div id="active-alarm">
<div id="alarm-text"></div>
<button id="clear-alarm">Clear Alarm</button>
</div>
Next, we add handleClick() function as click event of HTML button with id “clear-alarm”. In handleClear() function we set alarmString to empty string, hide the active-alarm container and display create-alarm. Thus the alarm clock is reset to its initial state.
const handleClear = () => {
alarmString = "";
activeAlarm.style.display = "none";
createAlarm.style.display = "block";
};
const clearAlarm = document.getElementById("clear-alarm");
// Trigger handleClear on button click
clearAlarm.addEventListener("click", handleClear);
Final Solution Code
index.html
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
</head>
<body>
<div id="app">
<h1>Current Time</h1>
<div id="current-time"></div>
<div class="create-alarm">
<div>Set Alarm</div>
<div class="form-actions">
<form>
<div class="alarm-inputs">
<input
type="number"
name="hour"
placeholder="Enter hours"
min="0"
max="12"
required
/>
<input
type="number"
name="min"
min="0"
max="60"
placeholder="Enter minutes"
required
/>
<input
type="number"
name="sec"
min="0"
max="60"
placeholder="Enter seconds"
required
/>
<select name="zone" required>
<option value="" selected disabled>Zone</option>
<option value="AM">AM</option>
<option value="PM">PM</option>
</select>
</div>
<button>Submit</button>
</form>
</div>
</div>
</div>
<div id="active-alarm">
<div id="alarm-text"></div>
<button id="clear-alarm">Clear Alarm</button>
</div>
<audio id="alarm-audio"></audio>
<script src="main.js"></script>
</body>
</html>
main.js
import "./styles.css";
var alarmString = null;
// Select HTML5 Audio element
const alarmAudio = document.getElementById("alarm-audio");
// Select DOM element with create-alarm id
const createAlarm = document.querySelector(".create-alarm");
// Select DOM element of active alarm container
const activeAlarm = document.getElementById("active-alarm");
const clearAlarm = document.getElementById("clear-alarm");
// Select DOM element of active alarm text
const alarmTextContainer = document.getElementById("alarm-text");
const alarmText = (time) => `Alarm set at time ${time}`;
// Initialize alarm sound
alarmAudio.src = "http://soundbible.com/grab.php?id=1252&type=mp3";
alarmAudio.load();
// Handle Create Alarm submit
const handleSubmit = (event) => {
// Prevent default action of reloading the page
event.preventDefault();
const { hour, sec, min, zone } = document.forms[0];
alarmString = getTimeString({
hours: hour.value,
seconds: sec.value,
minutes: min.value,
zone: zone.value
});
// Reset form after submit
document.forms[0].reset();
// Hide create alarm
createAlarm.style.display = "none";
// show active alarm with text
activeAlarm.style.display = "block";
alarmTextContainer.innerHTML = alarmText(alarmString);
};
const handleClear = () => {
alarmString = "";
activeAlarm.style.display = "none";
createAlarm.style.display = "block";
};
// Trigger handleClear on button click
clearAlarm.addEventListener("click", handleClear);
// Attach submit event to the form
document.forms[0].addEventListener("submit", handleSubmit);
// Function to check if alarm needs to be triggered
const checkAlarm = (timeString) => {
if (alarmString === timeString) {
alarmAudio.play();
}
};
// Function to convert time to string value
const getTimeString = ({ hours, minutes, seconds, zone }) => {
if (minutes / 10 < 1) {
minutes = "0" + minutes;
}
if (seconds / 10 < 1) {
seconds = "0" + seconds;
}
return `${hours}:${minutes}:${seconds} ${zone}`;
};
// Function to display current time on screen
const renderTime = () => {
var currentTime = document.getElementById("current-time");
const currentDate = new Date();
var hours = currentDate.getHours();
var minutes = currentDate.getMinutes();
var seconds = currentDate.getSeconds();
var zone = hours >= 12 ? "PM" : "AM";
if (hours > 12) {
hours = hours % 12;
}
const timeString = getTimeString({ hours, minutes, seconds, zone });
checkAlarm(timeString);
currentTime.innerHTML = timeString;
};
// Update time every second
setInterval(renderTime, 1000);
styles.css
body {
font-family: monaco;
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
#current-time {
font-size: 32px;
}
#current-time,
.create-alarm,
h1,
#active-alarm {
text-align: center;
}
.create-alarm,
.alarm-inputs,
#active-alarm {
margin-top: 20px;
}
input {
width: 100px;
height: 30px;
}
.alarm-inputs,
#alarm-text {
margin-bottom: 30px;
}
button {
font-size: 18px;
}
#active-alarm {
display: none;
}