rodboc
rodboc

Reputation: 175

Addclass for period of time on Jquery

I have a following HTML

<div id="btn_1">Button 1</div>
<div id="btn_2">Button 1</div>
<div id="btn_3">Button 1</div>

I want add a css class for period of time, for example: If the hour is between 00:00 to 06:59 add class "select" to id "btn_1", for between 07:00 to 10:59 am add the class to id "btn_2", and finally 11:00 to 16:00 add class to id "btn_3".

Any help please?

Upvotes: 0

Views: 1119

Answers (2)

Jeff B
Jeff B

Reputation: 30099

$(function() {
    // get hour of time
    var hour = (new Date).getHours();

    // remove select class if already applied
    $('.select').removeClass('select');

    if (hour < 7) {  // 0:00 to 6:59
        $('#btn_1').addClass('select');
    } else if (hour < 11) {  // 7:00 to 10:59
        $('#btn_2').addClass('select');
    } else if (hour < 16) {  // 11:00 to 15:59
        $('#btn_3').addClass('select');
    }

})

Demo: http://jsfiddle.net/fS3jj/

Upvotes: 1

alex
alex

Reputation: 490263

This should do the trick...

var classes = ['select', 'btn_1', 'btn_2', 'btn_3');

$('div')
// Remove any of the existing defined classes added to elements.
.removeClass(classes.join(' '))
// Add the class based on the hour of the day.
.addClass(function() {
    var hour = (new Date).getHours();

    if (hour < 6) {
        return classes[0];
    } else if (hour < 10) {
        return classes[1];
    } else if (hour < 15) {
        return classes[2];
    }

    return classes[3];
});

jsFiddle.

Alternatively, you could use an object to hold the classes where each value is the upper hour bound, and pass Object.keys(classes).join(' ') to removeClass().

Then you could greatly, simplify the body of the addClass() function.

However, I didn't go with this solution because Object.keys() does not have the best browser support and shimming it inline with a for ( in ) is verbose.

Upvotes: 0

Related Questions