08
Fri, Nov
10 New Articles

Easing HTML Maintenance

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

This article attempts to explain how the use of JavaScript functions can make coding HTML a little cleaner and a little easier. %% use insertnewsletterStoryad %%
My hope is to give you a few simple functions you can use immediately and to spark your interest in finding creative ways to make maintaining Web pages more manageable. You don't have to understand a lot about JavaScript to implement these techniques, but you may want to refer to a JavaScript reference guide for more detail. One book I'd suggest is Web Design in a Nutshell by Jennifer Niederst (O'Reilly & Associates).

If you're an RPG programmer like me, you've probably experimented with ways of making programs more modular and thus easier to maintain. By now, I suppose you've begun using ILE and have seen the benefits of reusable code. But what about HTML and free-form script languages like JavaScript? How do you carry over to the Web world the efficiencies you've discovered in the RPG world ?

At one time or another, I'm sure you have used RPG "/COPY members" or ILE service programs. The idea behind both of those is that you define or write something once and then copy it to or call it from many other programs. You can implement a similar feature in HTML by using simple JavaScript functions. The technique I show here is similar to using server-side includes (SSIs); I'll briefly explain the differences.

 

To illustrate the technique, I'll show examples of how to externalize "footer links" and footnotes (such as copyright notices).

Footer Links

First, I'll explain how to externalize "footer links," those navigation links at the top, bottom, or side of most Web pages that let you easily switch from page to page. Good design says that those links should look and work the same from page to page. That's simple enough; you can always copy and paste. But if you copy the code that defines your footer links to every page in your Web site, you'll create a maintenance problem; if you need to add a new link or want to make a small change to the look and feel, you'll have to change every page.

Using the /COPY example, you can define the footer navigation links in one simple JavaScript function and add a function call (/COPY in) to any pages where you want the links. Then, when you need to make a change, you make it one time, to the function, and the next time the function is called (when the page is loaded), the change is implemented. Let's look at the syntax of the function and the syntax needed to call it.

Figure 1 defines the function to write footer links. Notice that, in the first line, "// footer links" is a comment. The second line defines the function name as "footerlinks." Any parameters passed in would be listed between the parentheses (). The actual JavaScript code sits between the curly brackets { }.

// footer links
function footerlinks()
{
document.write("
");

document.write("<P ALIGN=Center>[ <A Href='home.htm'>Check
 Messages ] [ <A Href='home.htm'>Subscribe To All ] [ <A
 Href='home.htm'>Message Center ] [ <A Href='home.htm'>My Email
 ] [ <A Href='home.htm'>My Calendar ] [ <A
 Href='home.htm'>Search ] [ <A Href='home.htm'>Preferences ]
 ");


}













Figure 1: This function defines how to write footer (navigation) links.


The JavaScript code part of the function consists of the write method of the document object (called "document.write") and the HTML tags to define the anchor links.

The purpose of document.write is to write text to an HTML document, which is then displayed by the browser. It will also write HTML tags, which the browser will then interpret and parse out correctly on the screen. Notice the first document.write: document.write("


"). If you are familiar with HTML, you know that this is an instruction to place a "horizontal rule" on the screen. The second document.write starts a new paragraph (

) and defines anchor tags for the navigation links. This is the same code you would use in the HTML document.

One important thing about document.write: It cannot be broken across lines. So if you have very much text, you may want to break it up using variables, but there is no harm in extending the code in one long line.

Notice in Figure 1 that every document.write ends with a semi-colon (;), and the text and HTML tags to be written are within double quotes. If you have trouble getting your code to work, that's the first thing to check: Do you have a double quote where you shouldn't? If this is the case, try single quotes or the HTML equivalent: "

Calling the Function

To call the function from your HTML document, place the function name between the tags as shown in Figure 2. If you were passing variables to the function, you would place them within the parentheses; in this case, there are none. Again, notice the semi-colon after the function name.


<Script language=javascript>

footerlinks();

 

 

 

Figure 2: Here's an example JavaScript function call from HTML.


That's all there is to it. This is an extremely easy script and one you can implement quickly without knowing a lot about JavaScript. For other examples of this technique, download the sample code. There, you'll find a sample HTML page illustrating more JavaScript functions.

Externalizing Functions

Let's talk about where to store your JavaScript code. You may have noticed JavaScript functions defined at the beginning of HTML documents, and this is perfectly acceptable. In my opinion, however, you lose modularity when you do this; it's better to define functions in an external *.js file. I understand browser compatibility may have kept you from externalizing functions, but give the external *.js file a try before you resort to defining scripts internally.

In my example page, I've stored the JavaScript functions in an external file called commonscripts.js, which is nothing more than a text file with the .js extension. The downloadable code has this file; you can use it as a reference or adopt it as your own and add to it. To include or /COPY the commonscripts.js file into your document, use HTML's SCRIPT tag and place it between theandtags:

Another Way to Do the Same Thing

Server Side Includes (SSIs) are another way to externalize sections of HTML. Unlike in my example, you don't need JavaScript to use SSI. I'm oversimplifying this a bit, but to use SSI, you put the HTML you want to externalize into a separate document (usually with an .shtml suffix) and add an include in the main document, as shown in Figure 3.




... contents ...




 

 

 

 

Figure 3: You can use SSI to externalize HTML code.


SSI has predefined variables you can use to get the current date and time and variables to give information about a document (name, last modified). There is also a set of IF/ELSE commands.   To use SSI, you need to consult with your system administrator to see if it's available. You should also review your Web server's documentation.  SSI or JavaScript: the decision is yours. Choose what works best for your situation.

Footnotes

Building on what you've learned so far, let's look at a unique way to add footnotes (such as copyright information) and/or definitions to an HTML page. This technique uses a JavaScript function similar to the previous one, but you'll add an input variable and an array to hold footnotes, and then you'll call the function from an anchor link.

In the downloadable code, there is an example page called javascript_tip1.htm. Open the document and view the code to get a better understanding of what you're trying to accomplish.

First let me point out that, to format my example page, I'm using an external style sheet. Though it's beyond the scope of this article to explain style sheets, think of them as a way to put all of your HTML formatting options, (e.g., fonts, font color, point size, paragraph spacing, link attributes, etc.) into one place and "copy" or "include" them in.

When you open the example document ( javascript_tip1.htm ), notice that at the end of the first sentence there is a superscript 1 to denote the footnote. Clicking the footnote calls the JavaScript "footnote" function, passing in the parameter 1, which causes a new browser window to open and the footnote to display. See Figure 4.

<A Href="javascript:footnote( 1 );">1

 

Figure 4: Call a JavaScript function from an anchor link.

Behind the Scenes

Looking at the example document (javascript_tip1.htm, available in the downloadable code), you'll notice I took a few lines from "Old Mother Hubbard" and added my commentary in the footnotes.

The "footnote" function is listed in Figure 5 and has two parts. The first part of the function defines an array to hold the footnote text and, as in the first example, also includes any HTML tags needed to mark the text. The statement "foot = new Array( 5 );" creates a new JavaScript array with five elements.

Note that JavaScript array indexes start with zero, so the first footnote would be index zero. To make this easier to manage, I don't use the first index (that is, index zero). By starting with index 1, I am able to associate footnote 1 with array index 1.

// Footnotes
function footnote( nbr )
{
foot = new Array( 5 );
foot[0] = "";
foot[1] = "

Article - Footnote 1

This is a classic
 example of poor planning. As we will soon see, this turns into a
 defining moment for both the old woman and the dog.

";


foot[2] = "

Article - Footnote 2

What dog would choose
 bread over a bone? This inept attempt by the old woman to provide
 sustenance for the dog could be construed as blatant abuse. 

";

foot[3] = "

Article - Footnote 3

PETA would have a
 field day with this woman. Let's look at a list of abuses so
 far:

  • Starvation
  • Abandonment
  • Cruel and unusual
     treatment

 

";

foot[4] = "

Article - Footnote 4

 

";

foot[5] = "

Article - Footnote 5

 

";

var newWin = window.open("", "_new", "height=350, width=400, 
left=75, top=50, menubar=no, resizable=no, scrollbars=yes, status=no, 
toolbar=no");

newWin.document.open();
newWin.document.write(" Article <br /> Footnotes ");

newWin.document.write(foot[nbr]);

newWin.document.write("

 

<Input type='button' 
name='button01' value='Close' 
onClick='javascript:top.close();';>

 

");

newWin.document.close();
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 5: The footnote functions creates a new browser window and displays text based on an input variable.


The second part of the function defines a new browser window using the window.open object. I'm sure you've seen or used this before, so I won't go into detail. The parameters for window.open allow us to stipulate the size of the new window and to define it without a menu or scroll bar. (A good JavaScript reference would give you more information on all the properties of the window object.)

After the new window has been defined, you use the document.write object to set up the new document with HEAD, TITLE, and BODY tags. Then, you write the footnote, using the statement newWin.document.write(foot[nbr]); The function's input variable is used to extract the array element to be written.

This technique is a good way to externalize information into one area so it can be called from multiple documents. Maintaining one JavaScript array is easier than maintaining multiple documents.

Wrapping It Up

I hope these examples encourage you to find more ways to use JavaScript (or SSI). I'd love to hear your ideas on streamlining HTML and lessening Web site maintenance.

Author's Note: A special thank you to Ted Holt and Joe Pluta for their help with this article.

Jeff Kinzer is the Senior Programmer/Analyst for ACH Food Companies, Inc. in Memphis, Tennessee. Jeff has nearly 15 years experience with midrange systems and personal computers. You can contact Jeff at This email address is being protected from spambots. You need JavaScript enabled to view it.

 

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: