Alarm clock's submit button

How to Create Alarm Clock in HTML CSS & JavaScript

In this article you will learn how to create Alarm Clock using HTML CSS and JavaScript. Already I have shared tutorials on many types of digital clocks and analog clocks.

Now you know how to create JavaScript Alarm Clock. This project(How to make an alarm clock in HTML CSS and JavaScript?) is fully functional i.e. here you can set the alarm at your desired time. I have made this Digital Clock with Alarm in a very advanced way.

Alarm Clock in HTML CSS JavaScript

You can make this JavaScript Alarm Clock with Sound very easily if you know basic html css and javascript. Here you will find the necessary source code, live preview and explanation.

JavaScript Alarm Clock with Sound

An alarm clock is a useful tool for setting reminders and ensuring that you wake up on time. With the advent of web development, it is now possible to create an alarm clock using JavaScript. This type of alarm clock can be accessed through a web browser, making it convenient to use on any device with internet access.

The basic functionality of a JavaScript alarm clock is to set a specific time for the alarm to go off and display a message or play a sound when that time is reached. This can be achieved using the JavaScript Date object and the setTimeout or setInterval functions.

See the Pen Alarm Clock in HTML CSS & JavaScript by Ground Tutorial (@groundtutorial) on CodePen.

As you can see above I have created a box in a web page for this Simple Alarm Clock in HTML. This box contains all the information of this Alarm Clock. This alarm clock has a small box at the front which shows the time. Then there are two input boxes in which you can add your alarm time.

Basically here you can add hours and minutes time. Then there is a button below that will generate an alarm for the time you input.

Build A Simple Alarm Clock in HTML CSS & JavaScript

If you want to create this advanced JavaScript Alarm Clock then there is no reason to worry. Here I will tell you step by step and share the necessary source code how to create Alarm clock in Vanilla Javascript. If you just want the source code then use the download button below the article

Step 1: Basic structure of Alarm Clock

I first created a basic structure using the HTML and CSS code below. This box has width: 90%, max-width: 27.25em and background color is white.

				
					<div class="wrapper">
 
</div>
				
			
				
					* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #377dff;
}
.hide {
  display: none;
}
				
			
				
					.wrapper {
  background-color: #ffffff;
  width: 90%;
  max-width: 27.25em;
  padding: 3.12em 5em;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border-radius: 0.5em;
}
				
			
Basic structure of Alarm Clock

Step 2: Place to see time in alarm clock

Now I have created a place to see the time ie real time can be seen here. Here the basic area is created. Later I will arrange to show the time from your device by javascript. Also this time area is designed by some css and different colors are added.

				
					<div class="timer-display">00:00:00</div>
				
			
				
					.timer-display {
  font-size: 2.18em;
  text-align: center;
  box-shadow: 0 0 20px rgba(0,139,253,0.25);
  padding: 10px 30px;
  font-family: "Roboto Mono", monospace;
}
				
			
Place to see time in alarm clock

Step 3: A place to input the time of the alarm

Now we have to add various functions of Elam Clock ie input box, submit button and alarm list. We will add all these by following html css.

First here I have created two input boxes in which you can input the time in hours and minutes. Here I have used type=”number” of input box so only number can be input.

				
					<div class="container">
 
</div>
				
			
				
					<div class="inputs">
    <input type="number" id="hourInput" placeholder="00" min="0" max="23" />
    <input type="number" id="minuteInput" placeholder="00" min="0" max="59"/>
</div>
				
			
				
					.inputs {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1em;
  margin-top: 2em;
}
.inputs input {
  width: 2.8em;
  font-size: 1.3em;
  border: 1px solid #000000;
  border-radius: 0.1em;
  padding: 0.4em 0.2em;
}
				
			
A place to input the time of the alarm

Step 4: Alarm clock's submit button

Now we will create a button in this html Alarm clock. Which will basically work as a submit button. When you add your alarm time in that input box then clicking on this button will make that time effective for alarm.

				
					<button id="set">Add Alarm</button>
				
			
				
					#set {
  background-color: #377dff;
  border: none;
  padding: 1em 2.2em;
  display: block;
  margin: 1.5em auto 0 auto;
  border-radius: 0.2em;
  color: #ffffff;
}
				
			
Alarm clock's submit button

Now we will create an area in which the parameters you input are listed. Here only we have created basic area by html. Later we will activate everything with javascript.

				
					<div class="activeAlarms"></div>
				
			

Step 5: Activate the alarm clock with JavaScript

Now we will implement the various information of this JavaScript Alarm Clock with Sound by JavaScript. Here I have used a lot of javascript because I have made this design very advanced.

This code appears to be setting up a JavaScript program for an alarm clock. The first line selects an element with the class “timer-display” and assigns it to the variable “timerRef.” The next three lines select elements with the IDs “hourInput,” “minuteInput,” and “activeAlarms,” and assigns them to the respective variables. 

The next line selects an element with the ID “set” and assigns it to the variable “setAlarm.” The “alarmsArray” variable is an empty array that will later be used to store alarms. 

The “alarmSound” variable is a new instance of the HTML5 “Audio” object, which is set to play the file “./alarm.mp3.” You can use whatever audio you want in this alarm clock. Finally, the “initialHour,” “initialMinute,” and “alarmIndex” variables are all set to 0.

				
					let timerRef = document.querySelector(".timer-display");
const hourInput = document.getElementById("hourInput");
const minuteInput = document.getElementById("minuteInput");
const activeAlarms = document.querySelector(".activeAlarms");
const setAlarm = document.getElementById("set");
let alarmsArray = [];
let alarmSound = new Audio("./alarm.mp3");

let initialHour = 0,
  initialMinute = 0,
  alarmIndex = 0;
				
			

This is a JavaScript function that takes a single argument, “value”, and returns a string. If the value is less than 10, it adds a leading “0” to the value, otherwise it returns the value as is. This function can be used to ensure that a single-digit number is represented as a two-digit number (e.g. “07” instead of “7”).

				
					//Append zeroes for single digit
const appendZero = (value) => (value < 10 ? "0" + value : value);
				
			

This is a JavaScript function that takes two arguments: “parameter” and “value”. The function looks for an object inside the alarmsArray array, where the value of the key equal to the “parameter” passed to the function is equal to the “value” passed to the function. 

If it finds a match, the function sets exists to true, assigns the matching object to the variable alarmObject and assigns the index of that object in the alarmsArray array to objIndex.

				
					//Search for value in object
const searchObject = (parameter, value) => {
  let alarmObject,
    objIndex,
    exists = false;
  alarmsArray.forEach((alarm, index) => {
    if (alarm[parameter] == value) {
      exists = true;
      alarmObject = alarm;
      objIndex = index;
      return false;
    }
  });
  return [exists, alarmObject, objIndex];
};
				
			

This is a JavaScript function that displays the current time in a specific format and also check if any alarm is active and its time matches with the current time, if it matches it plays an alarm sound. As I said earlier the time can be seen in this advanced alarm clock in javascript.

It creates a new Date object, which is used to get the current hours, minutes, and seconds. The function uses the appendZero function to ensure that single-digit values are represented as two-digit values.

It then displays the current time in the format hours:minutes:seconds by updating the innerHTML of an element referred by timerRef.

Then it checks if any alarm is active by iterating over the alarmsArray, it compares alarm hour and alarm minute with the current hour and current minute, if it matches it plays an alarm sound using alarmSound.play() function. The alarmSound is looped continuously using alarmSound.loop = true.

				
					//Display Time
function displayTimer() {
  let date = new Date();
  let [hours, minutes, seconds] = [
    appendZero(date.getHours()),
    appendZero(date.getMinutes()),
    appendZero(date.getSeconds()),
  ];

  //Display time
  timerRef.innerHTML = `${hours}:${minutes}:${seconds}`;

  //Alarm
  alarmsArray.forEach((alarm, index) => {
    if (alarm.isActive) {
      if (`${alarm.alarmHour}:${alarm.alarmMinute}` === `${hours}:${minutes}`) {
        alarmSound.play();
        alarmSound.loop = true;
      }
    }
  });
}
				
			

This is a JavaScript code that adds an event listener to two input elements, hourInput and minuteInput, to check the input value when it changes.

The inputCheck function takes a single argument, inputValue, which is the value of the input element. It converts the input value to an integer using parseInt(), and checks if the input value is less than 10, if so, it calls the appendZero function to add a leading “0” to the input value.

The function then returns the input value, which is then used to update the value of the input element.

The event listener is added to both hourInput and minuteInput, so when the value of either input changes, the inputCheck function is called and the value of the input element is updated. This ensures that any input that is less than 10 is represented as a two-digit number (e.g. “07” instead of “7”).

				
					const inputCheck = (inputValue) => {
  inputValue = parseInt(inputValue);
  if (inputValue < 10) {
    inputValue = appendZero(inputValue);
  }
  return inputValue;
};

hourInput.addEventListener("input", () => {
  hourInput.value = inputCheck(hourInput.value);
});

minuteInput.addEventListener("input", () => {
  minuteInput.value = inputCheck(minuteInput.value);
});
				
			

This is a JavaScript function that creates an HTML element for this simple javascript alarm clock, given an alarm object. It takes a single argument, alarmObj, which is an object containing information about the alarm.

The function starts by destructuring the properties of the alarm object, such as id, alarmHour, and alarmMinute, which are used to create the alarm element. It creates a div element with the class “alarm” and a data-id attribute equal to the id of the alarm. It sets the innerHTML of the div to show the alarm time in the format of alarmHour:alarmMinute.

Then it creates an input element which is a checkbox, the checkbox attribute type is set to ‘checkbox’. An event listener is added to the checkbox element so that whenever it’s clicked it calls the startAlarm() or stopAlarm() function depending on the checkbox state.

Then it creates a delete button element with a trash icon, an event listener is added to the delete button so that when it’s clicked it calls the deleteAlarm() function.

Finally, the function appends the checkbox, delete button, and the alarmDiv to the activeAlarms element.

				
					//Create alarm div

const createAlarm = (alarmObj) => {
  //Keys from object
  const { id, alarmHour, alarmMinute } = alarmObj;
  //Alarm div
  let alarmDiv = document.createElement("div");
  alarmDiv.classList.add("alarm");
  alarmDiv.setAttribute("data-id", id);
  alarmDiv.innerHTML = `<span>${alarmHour}: ${alarmMinute}</span>`;

  //checkbox
  let checkbox = document.createElement("input");
  checkbox.setAttribute("type", "checkbox");
  checkbox.addEventListener("click", (e) => {
    if (e.target.checked) {
      startAlarm(e);
    } else {
      stopAlarm(e);
    }
  });
  alarmDiv.appendChild(checkbox);
  //Delete button
  let deleteButton = document.createElement("button");
  deleteButton.innerHTML = `<i class="fa-solid fa-trash-can"></i>`;
  deleteButton.classList.add("deleteButton");
  deleteButton.addEventListener("click", (e) => deleteAlarm(e));
  alarmDiv.appendChild(deleteButton);
  activeAlarms.appendChild(alarmDiv);
};
				
			

This is a JavaScript code that adds an event listener to a button element, setAlarm, so that when the button is clicked, an alarm is created and added to the alarmsArray.

The event listener is added to the setAlarm button, so when it’s clicked the following actions are taken:

  1. The alarmIndex variable is incremented by 1

  2. It creates an alarm object, alarmObj, which contains the following properties:

  • id: A unique identifier for the alarm in the format of alarmIndex_hourInput_minuteInput
  • alarmHour: The hour of the alarm, taken from the hourInput element
  • alarmMinute: The minute of the alarm, taken from the minuteInput element
  • isActive: A boolean value that indicates whether the alarm is active or not, initially set to false.
  1. It pushes the alarm object to the alarmsArray

  2. It calls the createAlarm function, passing the alarm object as an argument, to create an HTML element for the alarm.

  3. It resets the hourInput and minuteInput to their initial values by calling the appendZero function, and initialHour and initialMinute should be defined before calling the function.

				
					//Set Alarm
setAlarm.addEventListener("click", () => {
  alarmIndex += 1;

  //alarmObject
  let alarmObj = {};
  alarmObj.id = `${alarmIndex}_${hourInput.value}_${minuteInput.value}`;
  alarmObj.alarmHour = hourInput.value;
  alarmObj.alarmMinute = minuteInput.value;
  alarmObj.isActive = false;
  console.log(alarmObj);
  alarmsArray.push(alarmObj);
  createAlarm(alarmObj);
  hourInput.value = appendZero(initialHour);
  minuteInput.value = appendZero(initialMinute);
});
				
			

This is a JavaScript function that initializes this Element(Build A Simple Alarm Clock in HTML CSS & JavaScript). It takes a single argument, e, which is an event object that gets passed when the function is called.

The function starts by getting the value of the data-id attribute of the parent element of the event target, which should be the alarm div element. It then calls the searchObject() function passing in the parameter “id” and the value of the data-id attribute as arguments. This function will search the alarmsArray for an alarm object that has a matching id and returns an array containing a boolean value indicating whether the alarm object was found, the alarm object, and the index of the alarm object in the alarmsArray.

				
					//Start Alarm
const startAlarm = (e) => {
  let searchId = e.target.parentElement.getAttribute("data-id");
  let [exists, obj, index] = searchObject("id", searchId);
  if (exists) {
    alarmsArray[index].isActive = true;
  }
};
				
			

This is a javascript function to stop this javascript alarm clock. It takes a single argument, e, which is an event object that gets passed when the function is called.

The function starts by getting the value of the data-id attribute of the parent element of the event target, which should be the alarm div element. It then calls the searchObject() function passing in the parameter “id” and the value of the data-id attribute as arguments. This function will search the alarmsArray for an alarm object that has a matching id and returns an array containing a boolean value indicating whether the alarm object was found, the alarm object, and the index of the alarm object in the alarmsArray.

If the alarm object is found, it will update the isActive property of the alarm object to false, which means the alarm is now inactive. And it will pause the alarmSound by calling the pause() method on the alarmSound object.

				
					//Stop alarm
const stopAlarm = (e) => {
  let searchId = e.target.parentElement.getAttribute("data-id");
  let [exists, obj, index] = searchObject("id", searchId);
  if (exists) {
    alarmsArray[index].isActive = false;
    alarmSound.pause();
  }
};
				
			

This code defines a function called “deleteAlarm” that takes in an event object as an argument. This project(Simple Vanilla Javascript Alarm Clock) will activate the delete button inside the alarmList. The function uses the event object to target the parent element of the element that triggered the event and gets the “data-id” attribute of that element. 

It then uses the searchObject function to find the object in the alarmsArray that has a matching “id” property. If the object is found, the function removes the element from the DOM and splices the object from the alarmsArray.

				
					//delete alarm
const deleteAlarm = (e) => {
  let searchId = e.target.parentElement.parentElement.getAttribute("data-id");
  let [exists, obj, index] = searchObject("id", searchId);
  if (exists) {
    e.target.parentElement.parentElement.remove();
    alarmsArray.splice(index, 1);
  }
};
				
			

This code sets an interval to call the “displayTimer” function every time the window loads. That is, every time the page is loaded, the JavaScript Alarm Clock with Sound information will be deleted. It also initializes several variables: “initialHour” and “initialMinute” to 0, “alarmIndex” to 0, and “alarmsArray” to an empty array. The values of the “hourInput” and “minuteInput” elements are set to “appendZero(initialHour)” and “appendZero(initialMinute)” respectively. 

The function appendZero is not defined in this piece of code, it may be defined in another parts of the codebase or it may be a custom function that ensures that the input value has a leading zero if the input value is less than 10.

				
					window.onload = () => {
  setInterval(displayTimer);
  initialHour = 0;
  initialMinute = 0;
  alarmIndex = 0;
  alarmsArray = [];
  hourInput.value = appendZero(initialHour);
  minuteInput.value = appendZero(initialMinute);
};
				
			

We have created this alarm clock using JavaScript above. Now we will design this multiple alarm clock in js by some amount of css.

				
					.alarm input[type="checkbox"] {
  appearance: none;
  height: 2em;
  width: 3.75em;
  background-color: #e2e2ec;
  border-radius: 1em;
  position: relative;
  cursor: pointer;
  outline: none;
}
.alarm input[type="checkbox"]:before {
  position: absolute;
  content: "";
  background-color: #757683;
  height: 1.43em;
  width: 1.43em;
  border-radius: 50%;
  top: 0.25em;
  left: 0.25em;
}
.alarm input[type="checkbox"]:checked {
  background-color: #d2e2ff;
}
.alarm input[type="checkbox"]:checked:before {
  background-color: #377dff;
  left: 2em;
}
				
			
				
					.deleteButton {
  background-color: transparent;
  font-size: 1.5em;
  color: #377dff;
  border: none;
  cursor: pointer;
}
				
			
Alarm Clock in HTML CSS JavaScript

Hopefully from this article you have learned how to Build A Simple Alarm Clock in HTML CSS & JavaScript. Next time I will make it more advanced. As a result, even after you reload the page, all this information will be stored in your local storage. Be sure to comment how you liked this tutorial.

A snooze alarm clock in JavaScript would be a program that sets an alarm to go off at a specific time and then allows the user to snooze the alarm for a certain period of time before it goes off again.

This functionality could be implemented using JavaScript’s built-in timing functions, such as setTimeout() and setInterval(), to schedule the alarm and the snooze function. The program would likely also include UI elements, such as buttons for setting the alarm time and snoozing the alarm, that are controlled by JavaScript code.

To build an alarm clock using JavaScript, you will need to use the JavaScript setTimeout() function to schedule the alarm to go off at a certain time. The basic steps to building an alarm clock using JavaScript are as follows:

  1. Create an input field for the user to enter the time they want the alarm to go off.

  2. Use JavaScript to get the value entered by the user and convert it to a JavaScript Date object.

  3. Use the setTimeout() function to schedule the alarm to go off at the specified time.

  4. Create a function that will be called when the alarm goes off. This function can display an alert or play a sound to indicate that the alarm has gone off.

  5. Add a button for the user to turn off the alarm.

A Simple Vanilla Javascript Alarm Clock is a clock that uses only plain JavaScript (without any additional libraries or frameworks) to set and display the time, and also allows the user to set an alarm that will trigger at a specific time. The clock may also include features such as the ability to stop and start the alarm, snooze the alarm, and display the current date.