Sunday, December 09, 2007

Automatically updating multiple items on your website:

Here's an oldie but goodie. You could do this PHP or in other ways as well, but here's a simple way that will work for everyone (and works in ALL browsers!). Tip in advance: use your mouse to select any text that you have a hard time viewing on this blog---it will highlight it, and make it easy to read.

Say you display a phone number on dozens of pages across your website:
Call us at: <span class="phoneNumber">(612) 222-0000</span>

(The exact HTML or CSS you use doesn't matter---just pretend it looks like the line above.) Now say you want to change that phone number in one place, and then have it update everywhere else on the website automatically ! How would you do it?

First, realize that these two things are actually IDENTICAL:

Call us at: <span class="phoneNumber">(612) 222-0000</span>
document.writeln('Call us at: <span class="phoneNumber">(612) 222-0000<\/span>');

In the first case, you've just typed on the page the code you want. In the second case, you asked JavaScript to type it onto the page. The result is IDENTICAL HTML/CSS on the actual web page for visitors.

So, knowing this, here's the trick:

Take that line of JavaScript code, put it in a file (lets call it phone.js), then link to the file! So the phone.js file will have one line of code:
<!-- document.writeln('Call us at: <span class="phoneNumber">(612) 222-0000<\/span>'); //-->
... same as before. But now, on the page itself, you LINK to the phone code with:
  <script type="text/javascript" src="phone.js"></script>
Instead of putting the "Call us ..." etc. code on the page, you put it in a file, link to that file (phone.js), and then any changes you make to the file show up everywhere you list the phone number on your website!

There are few tips and tricks to this, so here's a couple of links for further research---check these out:
Creates javascript for you automatically: felgall.com/htmlt48.htm
Explains the process: web-source.net/dynamically_update.htm

No comments:

Post a Comment