ecs
ecs

Reputation: 718

Change class of body and links depending on time of day

I'm trying to change a few classes in my code depending on the time of day. I can get the background to change fine, but I need to change the menu colours as well. I can't seem to add a class to the links in the page to get them to change too! No idea where I'm going wrong, any help would be much appreciated, thanks!

P.S. I've tried the jQuery css() too, no luck there either...

function getDayTime(hours) {
if (hours > 20 || hours < 5)
    return "night";

if (hours > 17)
    return "dusk";

if (hours > 8)
    return "day";

return "dawn";
}

$(function() {
    document.body.className = getDayTime(new Date().getHours());
});

That's all brilliant, thank you so much for everyone's help, I've changed the javascript and it works great too. However, I'm now also trying to change the dawn colours to white as well - it's still staying as red even though I'm coding it just the same as changing to white! Clearly not enough coffee in my system here...

body.dawn #menu a {
    color:#fff !important
}

body.day #menu a {
    color:#8a0000 !important
}

body.dusk #menu a {
    color:#fff !important
}

body.night #menu a {
    color:#fff !important
}

Upvotes: 1

Views: 628

Answers (3)

ZER0
ZER0

Reputation: 25322

In jQuery you don't have className. Take a look to addClass and similar.

However I will suggest to you to have in the CSS something like that:

body.night a {
    /* your style for the 'nightlink' with !important to be sure */
}

So you don't need to ask to JS to retrieve and iterate all the A nodes in the page. In addition, if you will add a link dynamically, using the CSS approach the style will be applied automatically to them as well.

Edit: Not related to the original question, but I think you could simplify the condition in your js code with something like that:

function getDayTime(hours) {
    if (hours > 20 || hours < 5)
        return "night";

    if (hours > 17)
        return "dusk";

    if (hours > 8)
        return "day";

    return "dawn";
}

$(function() {
    document.body.className = getDayTime(new Date().getHours());
});

Upvotes: 3

Lyn Headley
Lyn Headley

Reputation: 11588

$("a").addClass("nightlink")

should work

Upvotes: 0

Lior Cohen
Lior Cohen

Reputation: 9055

I don't know what your CSS looks like, but here's how you can do this:

Assuming your CSS looks like this:

<style type="text/css">
  body { /* some stuff here */ }
  body.day { /* some day stuff here */ }
  body.night { /* some night stuff here */ }
  #menu { /* some stuff here */ }
  #menu a { /* some menu link styling here */ }

  /* To change #menu when body has class="day" */
  body.day #menu { // change menu when it's day }
  body.day #menu a { // change menu links */ }

  /* To change #menu when body has class"night" */
  body.night #menu { /* change menu when it's night */ }
  body.night #menu a { // change menu links */ }
</style>

Upvotes: 0

Related Questions