2

I am creating a calendar and need to be able to select (to show/hide) div.event who's data-dates (which may be string or array, depending on number of days the event appears in) by determining if any of the unix timestamp dates stored there are such that they fall between the unix timestamps which represent the start and end of the currently chosen month. So for example:

It is April 2013, so I wish to see only events that occur in April (1364774400 [April 1st, midnight] and 1367366399 [April 30th, 23:59:59]).

I have many event divs. They look something like this:

<div class="event" data-dates="[1367539200, 1367625600]">...</div>
<div class="event" data-dates="[1364947200]">...</div>

Let's assume one or more of those have timestamps that fall sometime in April 2013. How do I select them?

tckmn
  • 57,719
  • 27
  • 114
  • 156
GhostToast
  • 477
  • 1
  • 6
  • 16
  • Looks like a job for .filter http://api.jquery.com/filter/ select all event divs, then filter with a custom callback that loops through and compares dates. – Kevin B Apr 09 '13 at 21:13
  • I doubt that this can be accomplished with pure selectors... – Alex Shesterov Apr 09 '13 at 21:14
  • @KevinB looking into this – GhostToast Apr 09 '13 at 21:17
  • Might be best if you modified the code that creates the DIVs to add `data-month` attributes. – Barmar Apr 09 '13 at 21:21
  • @Barmar True, would reduce complexity of this selection, but I will later need to have a method for selecting a `week` or `day` at a time, so I thought this `data-dates` method would work for all. – GhostToast Apr 09 '13 at 21:25

1 Answers1

5

Try to make use of filter:

var rangeStart = 1364774400,
    rangeEnd   = 1367366399;

$('.event').filter(function() {
    return $(this).data('dates').some(function(date) {
        return date >= rangeStart && date < rangeEnd;
    });
})
.addClass('active');

http://jsfiddle.net/HJ9Xj/1/

Note. some method is not available in IE<9 so you can shim it or use simple for loop to check if data array contains any value between start and end. Demo 2.

dfsq
  • 191,768
  • 25
  • 236
  • 258