snippet_highlight

Snippet O’ the Week: jQuery, Highlight Element Based on Current Date

This weeks snippet o the week is brought to you by the letter ‘j’ and the word ‘Query’. This snippet is actually really cool and can solve a lot of usability problems. I found this snippet over at the great jQuery4u.com and it’s a slick litte function that will highlight an element with the current date and time – pretty slick no?

Here’s the function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
  * $.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');
        }
 
    });
};

Here is a screenshot from jquery4u.com:

For the full HTML and implementation example, hit the tutorial here: http://www.jquery4u.com/jquery-functions/jquery-highlight-element-based-current-date-time/. Big thanks to jquery4u.com, I did use this on a project last week and it works splendidly. I did modify the HTML implementation to work with my li’s, rather than the paragraph examples.

About the author

Patrick Cox wrote 98 articles on this blog.

Patrick is a UX Designer and the co-creator of Payba.cc and Aplethora (a two man interwebs design firm). He also enjoys family, snowboarding, sports and sugar free water mix ins and.... this is his blog.

2 comments

  1. Ted

    Hi Patrick. Is there any way you could assist me with applying this code to a table I have where I need a row highlighted based on the current date? Thanks very much.