Picnic Website Code Tutorials

Replace document.write Javascript - Insert HTML With Javascript - Graceful Degradation Tutorial

View Demo

Graceful degradation: in order to ensure your webpages degrade well in the absence of javascript one often has to add some of it's content with JS. Here is how it's accomplished.

Method 1: JS/CSS Hybrid

This JS adds the class of "js" to the html tag BEFORE page load. When JS is off, the class is no longer there. Using this method, you can put all your JS at the bottom of your page and just put this one liner after your CSS links and directly above the head tag.

The JS

<script type="text/javascript">
  document.documentElement.className = 'js';
</script>
		

The CSS

#method1 p {
display:none;
}
html.js #method1 p {
display:block;
}
		

The HTML

<div id="method1"><p>I am Method 1. I am some text/html. I will disappear if JS is turned off.</p></div>
		

Method 2: getElementById

This is pretty self explanatory. The only thing you must rember is that the script must come after the html with the id.

The JS

<script type="text/javascript">
document.getElementById('method2').innerHTML =
'<p>I am Method 2. I am some text/html. I will disappear if JS is turned off.</p>';
</script>
		

The HTML

<div id="method2"></div>
		

Method 2-B: Multiple getElementById On Same Page

<script type="text/javascript">
set = function (id, txt) {document.getElementById(id).innerHTML = txt;}
set('method2-B1','I am Method 2-B1. I am some text/html. I will disappear if JS is turned off.');
set('method2-B2','I am Method 2-B2. I am some text/html. I will disappear if JS is turned off.');
set('method2-B3','I am Method 2-B3. I am some text/html. I will disappear if JS is turned off.');
</script>
		

The HTML

<div id="method2-B1"></div>
<div id="method2-B2"></div>
<div id="method2-B3"></div>
		

Method 2-C: Only getElementById if Corresponding ID is Physically on Page

<script type="text/javascript">
var Get = document.getElementById("method2-C"); // null if it doesn't exist
if (Get) {
  Get.innerHTML = "I am Method 2-C. I am some text/html. I will disappear if JS is turned off.";
}
</script>
		

The HTML

<div id="method2-C"></div>
		

Sponsors

Top Donators

Friends of Mine