Toggle stylesheets in JavaScript file | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 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 }

24th May 2020, 5:12 AM
Marina Khamis
Marina Khamis  - avatar
6 Respostas
+ 3
My approach is somewhat more basic using a single Object.assign call. https://code.sololearn.com/WFAxU1l820oQ/?ref=app
24th May 2020, 5:28 PM
Ore
Ore - avatar
+ 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.
24th May 2020, 6:29 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
Marina Khamis try not to set rel attribute Read here https://stackoverflow.com/a/45119502/8265242
24th May 2020, 4:29 PM
CalviÕ²
CalviÕ² - avatar
+ 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
24th May 2020, 7:20 AM
CalviÕ²
CalviÕ² - avatar
+ 1
CalviÕ² You're really brilliant ! āœØšŸ’•
24th May 2020, 5:15 PM
Marina Khamis
Marina Khamis  - avatar
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 ..
24th May 2020, 3:36 PM
Marina Khamis
Marina Khamis  - avatar