Skip to main content

jQuery Highlight Element Based on Current Date Time

By Sam Deering



Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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.


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



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

Your HTML code should look something like this:

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

Related Articles

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn the basics of programming with the web's most popular language - JavaScript

A practical guide to leading radical innovation and growth.

Integromat Tower Ad