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

How do I create more space in Vitepress to prevent the text from feeling cramped and allow it to display in a larger area?

Below is the content of my index.md file: --- # https://vitepress.dev/reference/default-theme-home-page layout: home hero: name: "TP2" text: "Analyzing the code of TP2 by Breno Mazzali Medeiros Tomazelli and Philippe Bouchard" ta ...

Utilizing the power of AngularJS directives along with the functionality of a

I am completely new to angular js, but I have successfully integrated a jQuery UI datepicker into my Angular JS project. Now, I am facing the challenge of formatting the date selected by the jQuery datepicker into ISO date format. Here is the code snippet: ...

Navigating the landscape of asynchronous asset loading can present challenges. Attempting to access assets immediately may result in receiving

I have encountered an issue while trying to load my assets into an array using a function called LoadJSON(). This function utilizes THREE.ObjectLoader() to load JSON files. The problem arises when I attempt to access the members of the array immediately af ...

Ways to retrieve the most recent state in a second useEffect call?

Currently, I am encountering a situation where I have implemented two useEffect hooks in a single component due to the presence of two different sets of dependencies. My challenge lies in the fact that even though I update a state within the first useEffec ...

What is the best way to extract user input from a bootstrap search bar and integrate it into an ajax request to fetch information?

I am currently utilizing HTML, Javascript, and bootstrap to develop a web application. However, I have encountered an obstacle. When using the code document.getElementById("input here"), it only returned an array of 0. My goal is to retrieve data from an A ...

The for loop does not pause until the ajax response is received

When I enter the for loop, an ajax call is made. However, the for loop does not wait for the ajax call to receive a response before incrementing the value, causing the response to update to the wrong div element. For example: Let's say we have ' ...

Searching for a JavaScript tool that offers syntax highlighting capabilities

I have come across some excellent RTE HTML text editors such as jsredaktor, TinyMCE, and FCK Editor, but I am in search of an HTML/JavaScript component that functions similarly to a TEXTAREA with built-in code syntax highlighting. ...

CSS - Resizing Images

I am experiencing an issue with the width of an image on my website. I want it to span 100% of the browser frame, but it is currently limited to only 1000px wide. Please take a look at: The image in question is located at the top of the page. Is there a ...

Can someone provide a list of events for the .on function in Vanilla NodeJS?

Currently experimenting with NodeJS by testing basic backend functionalities like sending various HTTP requests from my index.html file to the server.js file. I plan to delve into Express soon. I've noticed a lack of documentation on NodeJS 'eve ...

mongoose.js now prevents update methods from returning documents

Is it feasible to avoid fetching any data from the database after performing the SOME_MODEL.findOneAndUpdate() operation? I could potentially utilize the lean() and select() methods. However, all I really require is a callback confirming the successful up ...

I need to input text into a specific element on the page, however there are four elements on the page that have identical properties

I am facing a dilemma where I need to input text into an element on the page. However, there are four elements with identical properties, making it challenging to find a unique locator. Does anyone have experience using Protractor for AngularJS web pages a ...

Getting query parameter with hyphen in nextJS 13 - step by step tutorial

One of the challenges I am facing involves accessing a query parameter with a hyphen in its name within a route: /?previous-page=building-details Within my Page component: import EnergyEfficiency from "@/ui/energy-check/energy-efficiency" cons ...

What is the best way to make a select tag read-only before the Ajax request is successful

Is there a way to make a select tag read-only before an Ajax success? I tried using this code, but it didn't work: $("#tower").prop('readonly', true); Then I tried this alternative, but I couldn't get the value from the select tag: ...

Error in Next.js: The element type is not valid. Please make sure it is either a string (for built-in components) or a class/function (for composite components) and not undefined

I've encountered an issue while working on my Next.js project where I am trying to import the Layout component into my _app.js file. The error message I received is as follows: Error: Element type is invalid: expected a string (for built-in componen ...

Press the button using the spacebar

I am facing an issue where I have a button with an anchor element that I need to trigger with the spacebar key for accessibility purposes. However, instead of triggering the button, pressing the spacebar causes the page to jump down when the button is in f ...

Move two markers on Google Maps simultaneously

After researching various articles and posts on Stack Overflow about selecting multiple markers in Google Maps, I have been unable to find a solution for dragging two markers simultaneously. While I've managed to make it work so that one marker can tr ...

Conditional rendering of a component in ReactJS while maintaining the "empty" space

Is there a way to conditionally render a component without affecting the layout of other components? I'm trying to avoid unwanted shifts caused by this div Do you have any suggestions? Here is a snippet of my code: const [displayFeedbackMessage, s ...

Ways to align a DIV in the center of another DIV?

I am currently working on building a footer. My goal is to center the 4 divs in the footer, similar to the first paragraph or the 5 icons that are not rendering correctly. What would be the most effective approach to achieve this? Demo: http://jsfiddle.n ...

Restrict the quantity of items retrieved from an AJAX response

An AJAX call has returned a response consisting of a list of <a> elements: <a href="/1/">One</a> <a href="/2/">Two</a> <a href="/3/">Three</a> I am looking to select only the first n a elements from this response ...

The Javascript/Jquery code executes just once on the initial event, doubles on the subsequent event, and continues to increase in

There is a JS function attached to an HTML button's onclick attribute: function AddFbLikes() { $('#fbform').on('submit', function(e) { e.preventDefault(); // stop form submission $("input:checkbox:checked").each(function(i ...