Alarm clock javascript source code 

Not so long ago we were developing a clock using javascript. Today we want to take it a step further and tell you how to implement the alarm clock feature in our clock using the HTML5 tag audio. We’ll need to add the following functionality: provide the ability to set and edit the alarm clock,…

Not so long ago we were developing a clock using javascript. Today we want to take it a step further and tell you how to implement the alarm clock feature in our clock using the HTML5 tag audio.


We’ll need to add the following functionality:

  • provide the ability to set and edit the alarm clock, which will require a dialog box with appropriate fields.
  • We need to check every second whether it is time to make a call. If the hour has struck, we start the audio file and display the “Time’s up!” dialog box.

For these properties, we’ll need to change the HTML, CSS, and jQuery. Let’s get started!

Adding an alarm to the javascript clock


We will have two dialog boxes. The first is for configuring and editing the alarm, and the second will be displayed when the set time arrives.

<div class="overlay">

    <div id="alarm-dialog">

        <h2>Set alarm after</h2>

        <label class="hours">
            Hours
            <input type="number" value="0" min="0" />
        </label>

        <label class="minutes">
            Minutes
            <input type="number" value="0" min="0" />
        </label>

        <label class="seconds">
            Seconds
            <input type="number" value="0" min="0" />
        </label>

        <div class="button-holder">
            <a id="alarm-set" class="button blue">Set</a>
            <a id="alarm-clear" class="button red">Clear</a>
        </div>

        <a class="close"></a>

    </div>

</div>

<div class="overlay">

    <div id="time-is-up">

        <h2>Time's up!</h2>

        <div class="button-holder">
            <a class="button blue">Close</a>
        </div>

    </div>

</div>

Both of these dialog boxes are hidden using CSS, and displayed using the jQuery method fadeIn() if necessary. It should also be noted that the alarm dialog box uses HTML5 input field types with a minimum value of 0. The numeric input fields are very easy to double-check with javascript (more on this in the next section), and they also allow you to display a numeric keypad on mobile devices.

Next comes the HTML5 audio element. It contains source tags with two different audio sources. The first source is mp3 and the second is ogg. The ogg format is only needed for Firefox, which does not support mp3 playback due to inconsistencies in the license agreement. The other browsers that support HTML5 Audio are capable of playing mp3.

<audio id="alarm-ring" preload>
    <source src="assets/audio/ticktac.mp3" type="audio/mpeg" />
    <source src="assets/audio/ticktac.ogg" type="audio/ogg" />
</audio>

The preload attribute tells the browser that these audio files must be downloaded in advance in order to access them immediately when the alarm sound is to be played (otherwise, when the alarm is first experienced, the sound will be delayed until the audio file is downloaded). Thanks to the HTML5 Audio API in javascript, we can play audio files in an incredibly simple way (more on this in the next section).

jQuery

In this section of the tutorial, we’ll add jQuery code to our digital clock so that it supports playing sounds. We won’t review the code we’ve already written, and will only tell you about the innovations.

The first thing we need to do is to define the number of variables needed to make the alarm clock work:

assets/js/script.js

var dialog = $('#alarm-dialog').parent(),
    alarm_set = $('#alarm-set'),
    alarm_clear = $('#alarm-clear'),
    time_is_up = $('#time-is-up').parent();

// This will hold the number of seconds left
// until the alarm should go off
var alarm_counter = -1;

Next, we need to check if an alarm is set while waiting for update_time().

// Is there an alarm set?

if(alarm_counter > 0){

    // Decrement the counter with one second
    alarm_counter--;

    // Activate the alarm icon
    alarm.addClass('active');
}
else if(alarm_counter == 0){

    time_is_up.fadeIn();

    // Play the alarm sound. This will fail
    // in browsers which don't support HTML5 audio

    try{
        $('#alarm-ring')[0].play();
    }
    catch(e){}

    alarm_counter--;
    alarm.removeClass('active');
}
else{
    // The alarm has been cleared
    alarm.removeClass('active');
}

When the counter reaches 0, it means it’s time to play the sound and show the dialog box. Note that even though we specify the audio element #alarm-ring with jQuery, we are also accessing the first DOM element within the collection, and accessing the javascript method play() available in the audio elements.

The last thing we have to do is deal with the “Set an alarm” dialog box and a few buttons:

// Handle setting and clearing alamrs

$('.alarm-button').click(function(){

    // Show the dialog
    dialog.trigger('show');

});

dialog.find('.close').click(function(){
    dialog.trigger('hide')
});

dialog.click(function(e){

    // When the overlay is clicked, 
    // hide the dialog.

    if($(e.target).is('.overlay')){
        // This check is need to prevent
        // bubbled up events from hiding the dialog
        dialog.trigger('hide');
    }
});

alarm_set.click(function(){

    var valid = true, after = 0,
        to_seconds = [3600, 60, 1];

    dialog.find('input').each(function(i){

        // Using the validity property in HTML5-enabled browsers:

        if(this.validity && !this.validity.valid){

            // The input field contains something other than a digit,
            // or a number less than the min value

            valid = false;
            this.focus();

            return false;
        }

        after += to_seconds[i] * parseInt(parseInt(this.value));
    });

    if(!valid){
        alert('Please enter a valid number!');
        return;
    }

    if(after < 1){
        alert('Please choose a time in the future!');
        return;	
    }

    alarm_counter = after;
    dialog.trigger('hide');
});

alarm_clear.click(function(){
    alarm_counter = -1;

    dialog.trigger('hide');
});

// Custom events to keep the code clean
dialog.on('hide',function(){

    dialog.fadeOut();

}).on('show',function(){

    // Calculate how much time is left for the alarm to go off.

    var hours = 0, minutes = 0, seconds = 0, tmp = 0;

    if(alarm_counter > 0){

        // There is an alarm set, calculate the remaining time

        tmp = alarm_counter;

        hours = Math.floor(tmp/3600);
        tmp = tmp%3600;

        minutes = Math.floor(tmp/60);
        tmp = tmp%60;

        seconds = tmp;
    }

    // Update the input fields
    dialog.find('input').eq(0).val(hours).end().eq(1).val(minutes).end().eq(2).val(seconds);

    dialog.fadeIn();

});

time_is_up.click(function(){
    time_is_up.fadeOut();
});

There are a couple of interesting places in this code. Notice how we use the built-in “validity” property on line 35, which is available for use on numeric input fields in modern browsers. It tells us whether the content of the input field is greater than 0 (remember that 0 is the minimum value).

It’s also worth paying attention to the way the code for the alarm dialog box is organized by means of custom events. When the ‘show’-event is triggered, we calculate the remaining hours, minutes and seconds until the alarm, which are then entered into the input field.

At this point our cute digital alarm clock is ready! We hope you enjoyed this tutorial and find it useful in future projects!

Similar Posts

Leave a Reply

Your email address will not be published.