JavaScript
Article
By Sam Deering

jQuery Highlight Element Based on Current Date Time

By Sam Deering

This is a little jQuery function I wrote to add a selected class to an element based on the current date and time (using date timestamp). The idea being to set a current session which is currently showing, like shown in the screenshot below.

set-current-datetimestamp

$.dateTimeHighlightNow() function

/**
  * $.dateTimeHighlightNow()
  * Author: Sam Deering
  * Adds/removes a selected class on elements based on the current date and time.
  * usage: $('.program p').dateTimeHighlightNow();
  */
jQuery.fn.dateTimeHighlightNow = function()
{
    return this.each(function()
    {
        var datetimestamp = Math.round(new Date().getTime() / 1000)
            elem = $(this),
            start = elem.attr('start'),
            finish= elem.attr('finish');

            log('datetimestamp = '+datetimestamp);

        if (start  datetimestamp)
        {
            elem.addClass('selected');
            log(elem);
        }
        else
        {
            elem.removeClass('selected');
        }

    });
};
--ADVERTISEMENT--

Usage:

$('.program p').dateTimeHighlight();

Your HTML code should look something like this:
program-times

Further usage could be to run the event every 1 minute (or so) for auto refresh:

/* monitor for auto change of current active session based on date/time */
setInterval(function()
{
    //run every minute
    $('.program p').dateTimeHighlight();
}, 60000);

Even Further thoughts

  • PHP timestamp is executed on the server side (your servers system clock).
  • JavaScript timestamp is executed on the client-side (your pc system clock).
  • A futher check to convert the clients Time Zone settings to the servers to highlight current session (this is something I may look into implementing in the near future so stay tuned for that).
Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account