JavaScript
Article

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 && finish > datetimestamp)
        {
            elem.addClass('selected');
            log(elem);
        }
        else
        {
            elem.removeClass('selected');
        }

    });
};

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).

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • http://profile.yahoo.com/H7T6MMFYQ7EFJLQFIBJ5LNLSGM DARK JEDI

    very good and useful

    • http://jquery4u.com/ jQuery4u

      Thanks mate, i’ve just added the HTML snippet too.

  • Pingback: jQuery Highlight Element Based on Current Date Time » PHP Script Blog()

  • Danish Rajkotiya

    how to highlight the div line with current time like google week calender using javascript???

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.