Bit of a newb to stackoverflow and spending way too much time thinking about this, but in a nutshell I’m trying to figure out the best approach and least amount of code for this to happen. I’ve got a conditional that will perform an action based on the time of day. See below:
var date = new Date();
var time = date.getHours();
if(time < 12){
header.prepend('Morning ');
link.attr('href', 'css/morning.css');
} else if (time >= 12 && time <= 18){
header.text('its afternoon time');
link.attr('href', 'css/day.css');
} else {
header.prepend('Night ');
link.attr('href', 'css/night.css');
}
I’ve also got a similar action happening with a click event:
$('button').click(function(){
var styleswitcher = $(this).text().toLowerCase();
link.attr('href', 'css/' + styleswitcher + '.css');
});
Is there a way to combine them into one function, I feel like I’m repeating myself by calling the stylesheet twice in the conditional and on the click event. So something along the lines of if the time and the click event match show the proper stylesheet. Thanks for all the help!
Yes, just package up the code and put it into the function.
Note: I haven’t had time to test this code, but the idea is correct.