Michael Michael - 1 year ago 104
jQuery Question

Alter CSS dynamically using JQuery (or simple Javascript) based on date comparison

I am hand-coding a small calendar of events. All that I wish to display is some basic event information (date, time, location, link to learn more). Since this page will rarely have more than 10-20 events listed at any given time (and onlye even once or twice per year), I'm not over-engineering it by using a calendar plugin or anything.

All I wish to do is to compare the current date against the HTML5 < time date="" >< /time > attribute and alter CSS on a parent element if the date specified is in the past (by at least one day).

By default the background color of the < li > element with class .event is white (#fff). If the date is in the past, I want the background color on the < li > .event class to change to grey (#ddd) when the page loads.

Thanks in advance for any help!

<doctype html>
.event {
background-color: #fff;

<ul class="row block-grid events">
<li class="small-12 medium-6 large-4 column event">
<dt><time date="2016-02-02">Feb 2</time></dt>
<dd>Boston Public Library at 7:00pm</dd>
<dd>Book launch</dd>
<dd>Boston, MA</dd>
<dd><a href="http://www.bpl.org">More details</a></dd>

Answer Source

Here is a jQuery solution. You could use "addClass()" or a similar method for more flexibility.


$('time').each(function() {
  var submitted_date = new Date($(this).attr('date'));
  var now = new Date();
  console.log(submitted_date.getTime() < now.getTime());
  if (submitted_date.getTime() < now.getTime()) {
    $(this).parent().parent().css('background', 'gray')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download