Using JavaScript to dynamically load Cascading Style Sheets based on the current

I am trying to dynamically load different CSS files based on the current date (season).

I attempted to tweak an image script that I found on Stack Overflow, but it didn't yield the desired result.

Could someone please guide me on where I might be making a mistake?

<link href="/css_season/default.css" rel="stylesheet" type="text/css" onload="logo(this)">
function logo(link) {
  var d = new Date();
  var today = d.getDate();
  var month = d.getMonth();
  var src;
  if (month === 4 && (today >= 1 && today <= 30)) {
    src = "/css_season/easter.css";
  } else if (month === 7 && (today >= 1 && today <= 31)) {
    src = "/css_season/vacation.css";
  } else if ((month === 8 && today >= 30) || (month === 0 && today <= 2)) {
    src = "/css_season/vacation.css";
  } else if (month === 12 && (today >= 15 && today <= 31)) {
    src = "/css_season/holidays.css";
  } 
  link.href=src;
}

Answer №1

The solution to your issue with the assignment link.href=href not working is because the variable href is not defined. To fix this, move the logo function inside <body onload="logo();"> tag and make sure to give an id attribute to your link tag.

Here is the updated code that should work for you:

<html>
<head>
<link id="cssId" href="/css_season/default.css" rel="stylesheet" type="text/css"/>
</head>
<body onload="logo();">
 <!-- body content here -->
</body>

function logo() {
  var d = new Date();
  var Today = d.getDate();
  var Month = d.getMonth();
  var src;
  if (Month === 4 && (Today >= 1 && Today <= 30))
    src = "/css_season/easter.css"; 
  else if (Month === 7 && (Today >= 1 && Today <= 31))
    src = "/css_season/vacation.css";
  else if ((Month === 8 && Today >= 30) || (Month === 0 && Today <= 2))
    src = "/css_season/vacation.css";
  else if (Month === 12 && (Today >= 15 && Today <= 31))
    src = "/css_season/holidays.css";

  document.getElementById('cssId').href=src;
}

Answer №2

There is a mistake in the assignment at the end of the javascript function.
link.href=href; should actually be link.href = src;

Regards

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

Is it possible to refresh data efficiently using web scraping tools, similar to how it

While researching web scraping in Python, I consistently found references to BeautifulSoup and Selenium as the primary tools for retrieving HTML and JavaScript content from websites. One thing that has eluded me is finding a method to automatically update ...

Incorporate the key as a prop within a Child Component in a React application

I am trying to display a list of elements in React, where the key of each element is used as an index in front of the item. However, when I try to access props.key, it just returns undefined. Does anyone have any suggestions on how to access the key proper ...

Executing MongoDB collection operations with array filtering

I am looking to count records based on tags and filter them before including in specific groups // data in database {tags: ['video', 'Alex'], ... }, {tags: ['video', 'John'], ... }, {tags: ['video', 'J ...

Guide on incorporating arrays into an array using JavaScript

Is there a way to achieve the specified outcome in JavaScript? I attempted to find a method for it on MDN but was unsuccessful. let a, b let allNumbers = [] for (a = 10; a < 60; a = a + 10) { for (b = 1; b <= 3; b++) { allNumbers.push(a ...

Retrieving data from Firestore yields an empty result

Having trouble reading from Firestore within a function, even though writes are working fine. Despite following examples on the given link, the query below and its variations result in an empty promise: module.exports.customerByPhone = phone => { r ...

What is causing setTimeout to not function as intended?

I'm having some trouble moving a <div id="box"> whenever my mouse hovers over it. Currently, the element only moves when I trigger the mouseover event on the div itself instead of when my mouse is actually hovering over it. document.getElements ...

Retrieving results from a Node.js application that utilizes multithreading

A new function called diversify() has been developed to execute an expensive function f() in parallel on all the cores of the machine in which it is being deployed. Additionally, a mechanism has been implemented so that when f() returns a value on one core ...

JavaScript can be used to create a fullscreen experience without any toolbars, scrollbars, and the like, without having

Is there a way for me to expand the current window I am using to fullscreen mode and eliminate all toolbars? ...

Trouble encountered with bootstrap toggling when multiple identical inputs are used

Problem with Bootstrap toggle not working on multiple identical inputs unless the first input is pressed. Even then, not all inputs are checked/unchecked. I've created a small example I want to ensure that when one input is toggled, all others have ...

Tips for verifying the rendered view post data retrieval from an API in Vue JS

Having trouble retrieving data from the API using Vue JS and printing the page? After fetching the data, some elements may not render completely when trying to print, resulting in blank data being displayed. While using a setTimeout function may work for s ...

Issue with fullcalendar: difficulty displaying events using ajax after clicking 'previous' or 'next' button

I am currently working on creating a calendar using fullcalendar. To retrieve data for the month, I make an external ajax request. Here are the key variables I utilize to render the fullcalendar: eventsJsonArray - used to load all events for the month ...

How can I use AJAX to send a dynamically generated PDF file?

I utilized jsPDF to create a PDF object. My goal is to send an email with a PDF attachment using AJAX, but I am facing issues in sending the file correctly. I attempted to convert it into a Blob object for transmission and later decode it to base64 in PHP ...

Clicking 'Submit' triggers a continuous loop upon loading

I set up this form to automatically submit once the page has finished loading. However, I seem to be encountering a problem where the page gets stuck in a continuous loop of reloading. HTML <body onload="document.getElementById('filters').su ...

Setting the maximum height for a tr or td element that is compatible with Chrome

Is there a way to set the max-height for a tr or td element that is specifically supported in Chrome? Previously, an answer suggested at this link did not work for Chrome: How to fix height of TR? ...

The useEffect hook in Next.js does not trigger a re-render when the route changes

I'm currently experiencing an issue with a useEffect inside a component that is present in every component. I've implemented some authentication and redirection logic in this component, but I've noticed that when using Next.js links or the b ...

Upon attempting to add a new component, an error was encountered: Uncaught SyntaxError: Unexpected token export

I have created a React test project and added modules to my package.json as follows: { "name": "untitled", "version": "0.1.0", "private": true, "devDependencies": { "babel-preset-node5": "^12.0.1", "react-scripts": "0.9.5" }, "depe ...

Struggling to navigate the world of JavaScript and find the sum of odd numbers?

Currently facing a roadblock with a codewars exercise and in need of some assistance. The exercise involves finding the row sums of a triangle consisting of consecutive odd numbers: 1 3 5 7 9 11 13 15 17 ...

Experiencing problems with the response from the Netlify Lambda function.. consistently receiving undefined results

I've been working on setting up a lambda function to handle authentication, validation, and sending of a contact form. As I'm new to lambda functions, my code might have some flaws. However, despite my efforts, I am struggling to modify the resp ...

What are some creative ways to animate a highlight effect on a CSS

I'm struggling to implement a sliding underline effect for my top navigation bar on hover. I've tried using transitions and keyframes, but so far it's not working as expected. My current attempt only triggers the effect on the parent elemen ...

How do you vertically span a grid element across 3 rows using Material UI?

This particular scenario may appear to be straightforward, but the official documentation of Material UI lacks a clear example on how to achieve this. Even after attempting to nest the grid elements, I encountered an issue where the grid element on the ri ...