Several popular uses of JavaScript such as content replacement, CSS manipulation, direct link prevention and more are covered here in detail with code samples provided.

Web Technology:More common JavaScript examples
Control the page:
Show table of contents,
Change page style,
Adjust text size
Introduction
T
C
F
<

Continuing from the Common JavaScript examples article, here are more useful JavaScript bits.

Content replacement

<

Content replacement is another popular use for JavaScript. This site uses it to generate the table of contents and to present images on the Photography page. As usual there are multiple ways of getting this done, two of them are presented below.

document.getElementById("paragraph").innerHTML = "<p style="font-style: italic;">Paragraph with italicized text.</p>"
Example 1

Above is a DOM compliant way of changing the content of an element. The document.getElementById function returns a particular element on the page with that unique id, the innerHTML attribute stores the contents of the element. It can also be used to change those contents but simply being reassigned as it is above. If this line were executed in a page and that page contained an element with id paragraph, that element would then contain the string we assigned to innerHTML. This method works very well, it also forces the author to properly organize the page, it is however not appropriate everywhere. Some browsers will not execute JavaScript until the page has completed loading. In this case the next example will work.

<script type="text/javascript" charset="ISO-8859-1"> document.write("<p style="font-style: italic;">Paragraph with italicized text.</p>"); </script>
Example 2

Above code can be included in-line with the html page and it will be executed when the browser encounters it. In general, the first content replacement option is a cleaner solution unless you absolutely must change the page before it is loaded. In addition, using the first method allows for dynamic location of the content container you want to modify. Meaning that the element with id 'paragraph' can appear anywhere in the document and be modified. While using document.write(), the content will be put at the current location.

Dynamic table of contents

<

One of the controls at the top of most pages on this site will generate a page section table with the table of contents. This is done dynamically. Several concepts are used to get this accomplished. One of them is proper content organization described in the Simple website templates article. All page sections are structured in the same fashion, this makes it possible to iterate over all the sections of the page and get the titles. The rest is simple and uses the content replacement technique.

Each of the sections on this or any other page of this site contain an element with id section_titleX, where X is a number from 0 to however many sections the page contains. All we need to do is make a list of these and the table of contents is done.

function buildtoc(){ var toc = document.getElementById("toc_content"); var tocHTML = "<ul>"; for(var i = 0; el = document.getElementById("section_title" + (i++));){ var tocelement = "<li><a href=\"#section" + (i - 1) + "\" >" + el.innerHTML + "<\/a><\/li>"; tocHTML += tocelement; } tocHTML +="<\/ul>"; toc.innerHTML = tocHTML; return; }
Example 3

Starting with section 0 we read the titles and add a link to that section to our HTML buffer. After the loop is complete, we close the list tag. This code assumes that the page contains an element with the id "toc_content", this element will get the list of links to all the sections of the page. To see an implementation of this in action click on the T control at the top of the page.

Changing CSS information with JavaScript

<

We have seen above how HTML elements can be referenced in JavaScript. We can also gain access to their style information and change it much like we can change their content. The following example sets text-align CSS property and the width property.

var element = document.getElementById("paragraph"); element.style.textAlign = "left"; element.style.width = "30px";
Example 4

Note that CSS properties that are hyphenated have the first letter of the second work capitalized and the dash is removed. Also keep in mind that if you want to read some CSS property, you can only read values that you set or the ones that were included in-line with the element using the style attribute. To reference styles loaded from an external CSS file you have to use other methods.

Direct link prevention

<

Often you may want to prevent your visitors from viewing pages of your site via deep links or viewing individual frames with out the containing page. This can be accomplished via JavaScript.

var allowed_sites = new Array(); var allowed_pages = new Array(); var default_url = "http://www.projecttree.com"; function init(){ allowed_sites[0] = "projecttree.com"; allowed_pages[0] = "index.html"; allowed_pages[1] = "web.html"; checkhistory(); return; } function checkhistory(){ var allow = 0; var ref_site = new String(document.referrer); if(ref_site != null){ for(var i = 0; i < allowed_sites.length; i++){ var exp = new RegExp(".*" + allowed_sites[i] + ".*"); if(ref_site.match(exp)){ allow = 1; break; } } } if(allow == 0){ ref_site = new String(location.pathname); for(var j = 0; j < allowed_pages.length; j++){ var exp = new RegExp(allowed_pages[j] + "$"); if(ref_site.match(exp)){ allow = 1; break; } } }else if(allow == 1){ return; }else{ location.replace(default_url); return; } }
Example 5

Above code will check the visitor's browser history and only load the page if the previously viewed page id on the white list. The init method should be called from the onload attribute of the body of the HTML file we want to prevent direct linking to.

The init method populates the white lists we defined just above it, next it calls the checkhistory function. The first loop if this function checks the HTTP_REFERRER and attempts to match it against the list of referrers that are allowed to link to this page. The second loop is not useful in this execution path. It is provided as an example of how to do the same kind of matching against the referring page rather than the referring host. Lastly the if statement at the bottom checks to see if the viewer should be redirected or be allowed to view the page.