Having trouble getting JavaScript to select a stylesheet based on time?

I am attempting to implement two different styles based on the time of day.

Here is the code I am using to select the CSS file depending on the current time:

<script type="text/javascript">
    function setTimedStylesheet() {
        var currentTime = new Date().getHours();
        console.log(currentTime);
        if (9 <= currentTime&&currentTime < 17) {
            document.write("<link href='/nuvoladigital.com.br/css/stylesnight.css' rel='stylesheet' type='text/css'>");
        }
        if (17 <= currentTime&&currentTime < 9) {
            document.write("<link href='/nuvoladigital.com.br/css/stylesnight.css' rel='stylesheet' type='text/css'>");
        }
    }

    setTimedStylesheet();
</script>

<noscript><link href="/nuvoladigital.com.br/css/stylesnight.css" rel="stylesheet" type="text/css"></noscript>

The paths are correct, and the console log confirms that the JavaScript is correctly determining the time. However, the stylesheet is not being applied. Any ideas on what could be causing this issue?

Answer №1

There are a couple of issues that need to be addressed:

  1. The "night" stylesheet is being included in both if blocks, which is redundant.
  2. The second if condition
    17 <= theTime&&theTime < 9
    can never evaluate to true because it's not possible for theTime to be simultaneously greater than 17 and less than 9. An alternative solution could be changing the && operator to ||, but a more straightforward approach would be to use an else statement without any condition.

Answer №2

Aside from the input provided by @nnnnnn, it is crucial to update your code syntax which appears to be outdated. The utilization of document.write() is strongly discouraged since it can trigger a complete document rewrite and constrain you to write "inline" with the HTML.

Here is an improved and contemporary solution:

<script>
    // Implementing Immediately Invoked Function Expression instead of function declaration
    (function() {

        var head  = document.querySelector('head');
        var link  = document.createElement('link');
        link.rel  = 'stylesheet';

        var theTime = new Date().getHours();
        console.log(theTime);

        if (theTime >= 9 && theTime < 17) {
            link.href = '/nuvoladigital.com.br/css/stylesDAY.css';
        } else {
            link.href = '/nuvoladigital.com.br/css/stylesNIGHT.css';
        }

        head.appendChild(link);
    }());

</script>

<noscript>
  <link href="/nuvoladigital.com.br/css/stylesnight.css" rel="stylesheet">   
</noscript>

Answer №3

Here is a different approach to writing the function. It seems that you have included the same style sheet twice. When working with only two style sheets, consider using an IF statement based on which one applies to more hours of the day (probability).

function applyTimedStyleSheet() {
    var currentTime = new Date().getHours();
    console.log(currentTime);

    if (currentTime < 9 || currentTime >= 17) {
        document.write("<link href='/nuvoladigital.com.br/css/stylesNight.css' rel='stylesheet' type='text/css'>");
    } else {
        document.write("<link href='/nuvoladigital.com.br/css/stylesDay.css' rel='stylesheet' type='text/css'>");
    }
}

You cannot use AND operation twice in this case as it will not yield the desired intervals.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery to obtain the object context while inside a callback function

Suppose I have the following object defined: var myObj = function(){ this.hello = "Hello,"; } myObj.prototype.sayHello = function(){ var persons = {"Jim", "Joe", "Doe","John"}; $.each(persons, function(i, person){ console.log(this.h ...

If the navigation menu contains sub-menus, it should slide to the left

I am currently working on developing a navigation menu with four levels of depth. The menu displays three levels at a time, and when the user reaches the fourth level, the first level should move to the left to make room for the second, third, and fourth l ...

Is it possible to incorporate a variable into the name of a mixin function in Less?

Could it be feasible to implement this in a way I haven't considered yet? I'm attempting to include a variable in the mixin function's name. @mybar: Test; .mymixin() { padding: 10px; } .mymixin@{mybar}() { padding: 10px; } .test { ...

Using React.js to establish a connection with a database

Can someone help me with connecting my reactjs to mysql? I have already installed mysql and followed the usual instructions, but I keep getting an error "TypeError: mysql.createConnection is not a function". Below are the codes I am working with. import ...

Selecting a particular item in a list depending on time using JavaScript, jQuery, or Angular

When working with a JSON file and binding it to list items, I have included a name/value pair in the json for each line indicating audio time, such as "time like 0, 5, 10 in seconds form". In my Cordova application, I am using a media plugin and implement ...

Notification continuously appears when clicking outside of Chrome

I have implemented the use of onblur on a text box to display an alert. However, I encountered an issue where if I click outside my Chrome browser after entering text in the text box and then click on the Chrome browser button in the task bar, the alert ap ...

Difficulty with Django's |safe template functionality

Issue with Django safe template functionality I attempted to utilize a textarea for rich text in the Django admin section, and everything seemed fine. However, when I try to display it on the front end using {{ date|safe }}, only a maximum height of appro ...

I'm wondering why myDivId.toggle() is functioning properly but myDivClass.toggle() is not working as expected

Using JQuery's toggle() function, I have been able to hide and show some DIVs successfully. Recently, I discovered relationships between certain DIVs that allowed me to group them into a class. I decided to try toggling the entire class rather than ...

CSS Selector for when a radio button is selected

I'm currently using images in place of radio buttons: <label class="radio-inline thumbs"><input type="radio" id="type_nee" name="type" value="nee" onkeyup="validate()" onclick=" ...

ways to conceal icon image when the textbox is devoid of content

Is there a way to hide the clear icon from a text box if the length inside the text box is less than 1? I attempted the following code, but it didn't work for me. The inner icon is not hidden when the input field length is less than 1. For a demo ex ...

Angular 6 implement a waiting function using the subscribe method

I need to make multiple calls to a service using forEach, where each call depends on the completion of the previous one. The code is as follows: itemDefaultConfiguration.command = (onclick) => { this.createConfiguration(configuration.components); ...

An error occurred when attempting to set state within a nested fetch

Having difficulty solving an issue with react.js. loadFromServer(pageSize) { fetch('http://localhost:8080/api/employees') .then(response => { return fetch('http://localhost:8080/api/profile/employees', ...

Repositioning the images to a new location

I've been having trouble moving the small images (thumbnails) on my page. They seem to be stuck in place on the left and I've tried adjusting their margins using a div id, but it hasn't had any effect. Below are the relevant code snippets: ...

The CSS class name is not having any impact on the React.js components

Struggling with CSS integration in ReactJS? That's the issue I've been facing while working on a project involving Rails and ReactJS. Despite implementing styles in my JSX files, nothing seems to change visually. Take a look at what my App.jsx fi ...

Is there a way to customize the Master Page in asp.net to resolve the Bootstrap4 dropdown issue? I am encountering an error message that says "Uncaught TypeError: Bootstrap

Hello everyone, I recently encountered an issue while trying to use dropdown in my project after updating to bootstrap 4. It was working perfectly fine before the update, but now I'm getting an error in the JavaScript. The error that pops up when I tr ...

Tips on aligning a v-btn alongside v-expansion-panels on the same row

Struggling with aligning my layout. Trying to get a single set of v-expansion-panels and a v-btn in the same row, both visually centered within a card. I managed to almost achieve it in this codepen: https://codepen.io/anzuj/pen/PoPPbdw with the following ...

Hiding timestamps on an interactive transcript: A step-by-step guide

I am in the process of creating personalized interactive ebooks based on a similar website found here: This website utilizes a VTT file along with an audio file. Although the JavaScript code requires time stamps, I would like to hide them for better read ...

Retrieving the IDs of all socket connections in a Node.js Socket.IO array

I currently have a complex program utilizing socketio 0.9 where I am storing all the sockets id in arrays like so: var clients = {}; To uniquely identify and store my sockets, I assign them a serial and then set the 'socket' key with its actual ...

Guide to executing two child processes sequentially in Node JS

I am working on two processes within a function: one generates a JSON file from an audio while the other normalizes the generated JSON file. However, I'm facing an issue where only one of the processes runs at a time - when the first one runs, the se ...

Utilize Puppeteer for Web Scraping to Extract Products with an Array of Images

I am currently developing my portfolio by working on a variety of small projects, with my current focus on web scraping. Using Puppeteer, I have successfully scraped basic test websites. However, my goal now is to tackle more advanced challenges, such as ...