Oxnard Montalvo
Oxnard Montalvo

Reputation: 7

adding a class depending on time of the day

I am trying to add a class to my #top depending on what time it is. I can't get the code to work properly.

What am I doing wrong here?

      jQuery(document).ready(function(){
            var A = [0,1,6,7,12,13,18,19];
            var B = [2,3,8,9,14,15,20,21];
            var now = new Date();
            var hours = now.getHours();
              if (hours = A) {
                jQuery('#top').addClass('A');
            } else if (hours = B) {
                jQuery('#top').addClass('B');
            } else {
                jQuery('#top').addClass('C');
            }
        });

Upvotes: 0

Views: 52

Answers (2)

Anthony B
Anthony B

Reputation: 13

Similarly to Evik's answer you can instead use the includes function:

jQuery(document).ready(function(){
            var A = [0,1,6,7,12,13,18,19];
            var B = [2,3,8,9,14,15,20,21];
            var now = new Date();
            var hours = now.getHours();
              if (A.includes(hours)) {
                jQuery('#top').addClass('A');
            } else if (B.includes(hours)) {
                jQuery('#top').addClass('B');
            } else {
                jQuery('#top').addClass('C');
            }
        });

Upvotes: 1

Evik Ghazarian
Evik Ghazarian

Reputation: 1791

To find if an element is in an array you should use .indexOf ().

For example: array.indexOf(something) > -1 returns true if something is in the array

jQuery(document).ready(function(){
            var A = [0,1,6,7,12,13,18,19];
            var B = [2,3,8,9,14,15,20,21];
            var now = new Date();
            var hours = now.getHours();
              if (A.indexOf(hours) > -1) {
                jQuery('#top').addClass('A');
            } else if (B.indexOf(hours) > -1) {
                jQuery('#top').addClass('B');
            } else {
                jQuery('#top').addClass('C');
            }
        });

Upvotes: 0

Related Questions