Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Friday, 19 February 2010

Build a menu bar on-the-fly with JavaScript

Its not necessary to use either PHP or SHTML to include a dynamic menubar in a set of web pages - you can do it with JavaScript.

First define arrays containing all the links and the link text you want for the links - make certain the two arrays have the same number of elements!

Then have a loop that goes through these arrays, displaying them on the screen in order. You can do a bit of string testing to work out what page you're on and have that link displayed differently - perhaps in bold or just not underlined. Output all the HTML using document.write

Here's an example:

var textArray=new Array('home','news','people','places','views', 'faq');
var linksArray=new Array('index.html','news.html','people.html','places.html','views.html','faq.html');

for (i=0;i < textArray.length; i++) {
var str = window.location.toString();
var urlbits = str.split('/');
if (urlbits[urlbits.length-1]!=linksArray[i]) {
document.write(''+textArray[i]+'');
} else {
document.write(''+textArray[i]+'');
}
if (i!=textArray.length-1) document.write(' | ');
}

Note how the last line in the loop misses off the delimiter for the last item.

Save this JavaScript in a separate file - something like menubar.js - and include it in the same place in all of your HTML pages using a conventional link to an external JavaScript file:

<script type="text/javascript" src="menubar.js"></script>

My links here are just straightforward links, but they could equally be styled bullet list items, buttons, images, whatever.

Wednesday, 10 December 2008

Dynamic HTML select objects

Want to use JavaScript to remove all elements of a select object? Don't do this:

for (i=0; i < form.yourSelector.length; i++) {
  form.yourSelector.remove(i);
}


...and don't do this either:

l = form.yourSelector.length;
for (i=0; i < l; i++) {
  form.yourSelector.remove(i);
}


Instead, do this:

l = form.yourSelector.length;
for (i=0; i < l; i++) {
  form.yourSelector.remove(form.yourSelector.length - 1);
}