Jump to content

Client Side Include of Dynamic CSS Pages


ElectricShaka

Recommended Posts

I'm trying to do a client side include of dynamic css pages with javascript. My code on my main page looks like this:

 

<style type="text/css" id="layout_color_css">
</style>

 

And then the function I'm using on an external javascript page is:

 

function clientSideInclude(id, url) {
  var req = false;
  // For Safari, Firefox, and other non-MS browsers
  if (window.XMLHttpRequest) {
    try {
      req = new XMLHttpRequest();
    } catch (e) {
      req = false;
    }
  } else if (window.ActiveXObject) {
    // For Internet Explorer on Windows
    try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        req = false;
      }
    }
  }
var element = document.getElementById(id);
if (!element) {
  alert("Bad id " + id +
   "passed to clientSideInclude." +
   "You need a div or span element " +
   "with this id in your page.");
  return;
}
  if (req) {
    // Synchronous request, wait till we have it all
    req.open('GET', url, false);
    req.send(null);
    element.innerHTML = req.responseText;
  } else {
    element.innerHTML =
   "Sorry, your browser does not support " +
      "XMLHTTPRequest objects. This page requires " +
      "Internet Explorer 5 or better for Windows, " +
      "or Firefox for any system, or Safari. Other " +
      "compatible browsers may also exist.";
  }
}

I'm calling the function when a user clicks on an image on the page with code like this:

 

<span class="layout" onclick="clientSideInclude('layout_color_css', 'land/land1.css');"><img src="elements/layout/1click/layout_3.gif" width="52" height="41" alt="" /></span>

 

This works in firefox...the external css is called when the button is clicked and everything looks fine. It does NOT work in internet explorer though.

 

Any help is greatly appreciated.

I believe I figured it out with Fang's help. This was the method I ended up using:

function swapStyleSheet(id, cssfileName) {
var ss=document.getElementById(id);
var parent=document.getElementsByTagName('head')[0];
parent.removeChild(ss)
var o = document.createElement('link');
o.setAttribute('type', 'text/css');
o.href = cssfileName;
o.setAttribute('rel', 'StyleSheet');
o.id = id;
parent.appendChild(o);
}

 

Thanks Fang.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.