Toggle stylesheets in JavaScript file | SoloLearn: Learn to code for FREE!

+3

Toggle stylesheets in JavaScript file

I wanna create 4 themes for a website I'm working on for weather forecast, and i wanna call each theme when the temperature is in a certain range . So i wanna do something like this : If ( temprature is low ) { apply stylesheet that contains style of cold weather (like background of ice and blue colors..etc) } else if ( temprature is high ) { apply the stylesheet of hot weather }

5/24/2020 5:12:46 AM

Marina Khamis

6 Answers

New Answer

+3

My approach is somewhat more basic using a single Object.assign call. https://code.sololearn.com/WFAxU1l820oQ/?ref=app

+4

You should be able to get the link element using querySelector and then access its href attribute to change the sheet. Unfortunately, it won't work on SL afaik. But, you can try using; var stylesheet = document.querySelector('link'); stylesheet.href = "newstyles.css" There are other ways to do it depending on how you're wanting to do so. You can Google for those answers.

+3

Marina Khamis try not to set rel attribute Read here https://stackoverflow.com/a/45119502/8265242

+2

Here a code for dynamically load an external stylesheet in head tag, var head = document.getElementsByTagName('head')[0]; var style = document.createElement('link'); style.href = filename; style.type = 'text/css'; style.rel = 'stylesheet'; head.append(style); https://code.sololearn.com/W3skl18TyoGI/?ref=app

+1

Calviղ You're really brilliant ! ✨💕

0

The resource from “http://localhost:2525/website/themes/cold.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff It gives me this error ..