JavaScript Includes
Loved the PHP Includes tutorial but sadly found out that your host doesn't support PHP? Don't fret because all is not lost. JavaScript is here to help you! Let's not waste a second more and get the ball rolling...
This is based on the PHP Includes tutorial so you may recognize some coding and explanations from there.
Step 1: Your HTML Page
We'll start with something simple:
1: <html> 2: <head> 3: <title>JavaScript Includes</title> 4: </head> 5: 6: <body> 7: 8: <p>Hello, world!</p> 9: 10: </body> 11: </html>
Above is a simple HTML page. The numbers on the side represent the number of lines it has. We leave out those numbers when we actually make the HTML page. They're just there for presentation.
Next is we divide that page into 3 parts. Line 8 will be the content, lines 1-6 will be the header and lines 10-11 will be the footer.
Step 2: Enter JavaScript
This is the good part. Let me introduce you to this simple code:
document.write('LINE OF CODE HERE');
That code up there is going to do the "magic". Just replace the underlined text with the line of HTML code we have. Huh? Don't quite get it? Here's how it should look like:
document.write('<html>');
See how it goes? We placed line 1 of our HTML code in there. But of course, we have several lines to work with so we'll do the same with them. Let's work with the header lines first. It should look like this:
document.write('<html>');
document.write('<head>');
document.write('<title>JavaScript Includes</title>');
document.write('</head>');
document.write('<body>');
Now that's done, we'll save it as header.js using Notepad or any text editor you have. We'll do the same with the footer lines:
document.write('</body>');
document.write('</html>');
And we'll save it as footer.js. Got it? Yes? Good. Let's continue...
Step 3: The Code
We're putting it all together and this is how the code should look:
<script src="header.js" type="text/javascript"></script> <p>Hello, world!</p> <script src="footer.js" type="text/javascript"></script>
Let's save this as index.html and that's it!
Conclusion
There you have it: An alternative to the PHP Includes. So, if you want to change your layout, you just have to edit header.js and footer.js instead of editing each of your HTML pages one by one.
Here's something to remember: Be careful when using apostrophes ('). JavaScript will think that's the end of the line and it won't read the rest of the code. If you need to use an apostrophe, you can add a slash (\) before your apostrophe like we did on this example:
document.write('Miko Reznor\'s JavaScript Tutorial');
You may download the files for this tutorial here.
If you have any questions or if you want to discuss this tutorial, you may post at Blinding Light MB.