MadDecent
MadDecent

Reputation: 23

Conditional .addClass()

I cannot figure this out for the life of me. I need to have three classes given to a series of 7 tabs (based on the day of the week), .past, .today, and .future

I have the .today working wonderfully using the .getDay(), but I am having trouble assigning all the li's that come before .today to .past, and all the li's that come after .today to .future

HTML:

<ul class="days-of-the-week tabs clearfix">
  <li class="sunday"><span><a href="#">Sunday</a></span></li>
  <li class="monday"><span><a href="#">Monday</a></span></li>
  <li class="tuesday"><span><a href="#">Tuesday</a></span></li>
  <li class="wednesday"><span><a href="#">Wednesday</a></span></li>
  <li class="thursday"><span><a href="#">Thursday</a></span></li>
  <li class="friday"><span><a href="#">Friday</a></span></li>
  <li class="saturday"><span><a href="#">Saturday</a></span></li>
</ul>

jQuery:

// Add class .today to the correct day-of-week tab
$('ul.days-of-the-week li:eq(' + new Date().getDay() + ')').addClass('today');

Thanks in advance!

Upvotes: 2

Views: 961

Answers (3)

adeneo
adeneo

Reputation: 318182

$('ul.days-of-the-week li').each(function() {
    var c = new Date().getDay() <= $(this).index() ? new Date().getDay() == $(this).index() ? 'today' : 'future' : 'past';
    $(this).addClass(c);
});

Upvotes: 0

Blake Mitchell
Blake Mitchell

Reputation: 2787

I think you are looking for netxAll and prevAll:

var today = $('ul.days-of-the-week li:eq(' + new Date().getDay() + ')');
today.prevAll().addClass('past');
today.addClass('today');
today.nextAll().addClass('future');

Upvotes: 1

Jack Franklin
Jack Franklin

Reputation: 3765

You can use prevAll() to get all previous siblings of the current element, and nextAll() for all the following siblings.

Docs for prevAll: http://api.jquery.com/prevAll/

Docs for nextAll: http://api.jquery.com/nextAll/

Using these it's easy. JSFiddle: http://jsfiddle.net/qYt2p/

var today = $('ul.days-of-the-week li:eq(' + new Date().getDay() + ')').addClass('today');
today.prevAll().addClass("past");
today.nextAll().addClass("future");​

Upvotes: 4

Related Questions