change css href attributes to multiple html pages onclick
I would like to have users choose a colour theme for their experience on my site. I have created different themed external css files and have created a function to successfully switch between all the colour options I have created.
The only problem is when I click on a link to another page on the site the theme returns to the default colour in which I created the page.
Is there a way to dynamically change the href attribute of every html page so the css colour file is changed on every page. Or would I need cookies to remember this? I have not learned about cookies yet but wondered if this could be a function.
Below is my code which changes between each colour fine on that page, but only on that page.
HTML: Orange Theme Purple Theme Red Theme
Javascript: function setStyleSheet(url) { var stylesheet = document.getElementById("stylesheet"); stylesheet.setAttribute('href', url); }
I have the required css files saved externally. Any help would be gratefully welcome. Thanks.
Ideally you would use cookies, but if you really really wanted to do it without cookies you could try running something like:
var links = document.querySelectorAll("a");
for (i = 0; i < links.length; i++) {
var existingHref = links[i].href;
links[i].href += (links[i].href.indexOf("?") + 1 ? "&" : "?") + "theme=" + encodeURIComponent(theme);
}
(Untested code, and there are a few other edge cases you would want to check for, but the general idea is there)
This would update each link on the page, adding a theme=[theme]
property to its URL, which you could then load in later pages by parsing window.location.search
:
function getTheme() {
if (window.location.search.split("theme=").length < 2) return null;
return window.location.search.split("theme=")[1].split("&")[0];
}
Note when I say "ideally" I really mean that you should be using cookies - they were made and are used almost exactly for this purpose, you don't have to deal with sketchy edge cases like if there's already a theme
in the URL or if it's going to another domain that also uses theme
in the URL, if you change pages with Javascript it will still work, etc. - but I believe this method should work as well.