0

I have a static event listing in HTML where I would like to add a CSS class to past and current events dynamically using javascript.

Each event listed will need to display either a single date or a date range, therefore parsing the date (I'm thinking) will need to be done using a data-* attribute—something which I've never worked with before in this sense.

HTML Markup:

<div class="events-list-wrapper">
  <div class="event">
    <p class="date" data-date="21-01-2017"><span>Jan</span> 17-21</p>
    <h3>Event Title</h3> ...
  </div>
  <div class="event">
    <p class="date" data-date="29-08-2017"><span>Aug</span> 29</p>
    <h3>Event Title</h3> ...
  </div>
  <div class="event">
    <p class="date" data-date="12-09-2017"><span>Sept</span> 10-12</p>
    <h3>Event Title</h3> ...
  </div>
</div>

Here's the fiddle I've been working with, https://jsfiddle.net/t2v21oh6/1/ edit: https://jsfiddle.net/t2v21oh6/4/. I'm not that strong with javascript, and my code isn't working. Not sure why.

Leah
  • 1
  • 3
  • You can do that either with a library such as JQuery or either through plain JS code: https://stackoverflow.com/questions/7388626/how-do-i-add-a-class-to-the-html-element-without-jquery – guilhebl Aug 28 '17 at 21:16

1 Answers1

0

You can use a simple if {} else {} statement and the now() static method from Date to get today's time in seconds.

The Date.now() method returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.

- MDN web docs

See code below:

let today = Date.now()

$('div.event').each(function() {

  let div = $(this);
  let divDate = Date.parse($('.date', this).text());

  if (divDate < today) {
    div.addClass('past');
  } else {
    div.addClass('today');
  }

});
.past {
  border: 1px solid gray;
}

.today {
  border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="events-list-wrapper">
  <div class="event">
    <p class="date"><span>Jan</span> 17-17</p>
    <h3>Event Title</h3> ...
  </div>
  <div class="event">
    <p class="date"><span>Aug</span> 30-17</p>
    <h3>Event Title</h3> ...
  </div>
</div>
Community
  • 1
  • 1
Ivan
  • 34,531
  • 8
  • 55
  • 100
  • Works, but the date parsing isn't ideal. Some dates might span multiple days, so the date won't always be written Month DD-YY. Perhaps I need to parse the date from somewhere else, such as a data-* attribute? – Leah Aug 28 '17 at 23:46
  • @Leah it is unclear what you are asking for, edit your question so I can help you out. – Ivan Aug 29 '17 at 09:04