Basic Javascript Example
by Raymond @ http://www.csstinderbox.com . September 10, 2009 . 10:28AM
Right off the bat I need to go on the record and say that this example is definitely not earth-shattering or all that useful beyond an introduction for people just wading into Javascript. At the very most it could be used as a simple hack for someone looking to edit a single file that contains the same content being used across their site or at least multiple pages. Let’s get started.
If you take a gander at this example, you’ll see that each page is pretty much the same: links, main content and a right-floated message box. Page one and three are exactly the same but page two has different copy in the message box.
The main copy is hard-coded into each HTML page but the special message box and its content is being pulled into each separate page from a single source located in the external Javascript file.
If you look in the HTML or do a view source you’ll just see the empty DIV tags:
‹div id="snippet1"›‹/div›
because for all intents and purposes it’s merely a placeholder or shell within structure of the HTML page, telling the Javascript where the content needs to go when its called.
Basically what we’re doing with the Javascript is an A/B thing. There are only two options or blocks of content available. Option A is the special or alternate message and will only appear on pages within the subdirectory defined in the Javascript on line #6:
if ( location.href.indexOf("/sub/") > -1) {
and for this example, the subdirectory is called, oddly enough, “sub”. Option B is the general message and will appear on all other pages on the site NOT within the defined subdirectory. Pretty much as easy as falling off a log.
This set-up can easily be copied and adapted or applied to an existing site with little or no pain and misery. I left some notes in the HTML and Javascript if anyone is interested. Here’s the zip of all the files.
See, I told you it wasn’t earth-shattering.
RSS 2.0 //
Respond // trackback
What Do You Think?
Check out the latest designs I've done and the other ideas I have on the proverbial drawing board.
Take a look...
