Using a select element to change the active stylesheet for a web page.

Ben Key:

This page demonstrates the use of a select element to change the active stylesheet for a web page. It also provides step by step instructions on how to create the select element.


This example is fully functional. It does lack one key feature, the ability to store the selected style in a cookie. The article Store and Retrieve Cookies demonstrates the use of the localStorage.setItem and localStorage.getItem functions.

Modify the SetStyle function by adding the folloing line just above the 'return true;' line at the bottom of the function.


window.localStorage.setItem(
  "SeclectedStyle", seclectedStyle);

Note that the localStorage object is only supported on modern web browsers. That said, the Local storage with Window.localStorage page provides JavaScript code to emulate the feature for older browsers.

The next step is to set the style and the selected item in the select element when the web page loads. To acomplish this you need to add the following function.


function SetStyleFromCookie(selectStyleElementId, linkElementId){
  console.log(
    "SetStyleFromCookie('" + selectStyleElementId + "', '" + linkElementId + "') called.");
  let seclectedStyle = window.localStorage.getItem(
    "SeclectedStyle");
  if (isEmptyOrSpaces(seclectedStyle)){
    console.log(
      "Failed to get the value of the 'SeclectedStyle' cookie. Using the default value.");
    seclectedStyle = 'https://www.w3.org/StyleSheets/Core/Swiss';
  }
  let linkElement = document.getElementById(linkElementId);
  if (!linkElement){
    console.log("Could not find the '" + linkElementId + "' element.");
    return false;
  }
  linkElement.setAttribute("href", seclectedStyle);
  let seclectStyleElement =  document.getElementById(selectStyleElementId);
  if (!seclectStyleElement){
    console.log("Could not find the '" + selectStyleElementId + "' element.");
    return false;
  }
  seclectStyleElement.value = seclectedStyle;
  return true;
}

Finally, use the following code to call the SetStyleFromCookie function when the web page is loaded.


window.addEventListener('DOMContentLoaded', (event) => {
  SetStyleFromCookie('SeclectW3CCoreStyle', 'W3C-Core-Styles');
});

References