|
Back to the Index Page |
Javascript & HTML ScriptsWhere practical, each code comes complete with a working sample of the code. Many of these codes were sourced from www.bravenet.com, some being more modified than others. My advice, for what it's worth, is never use Javascript where an HTML equivalent exists. Although Javascript has a very close relationship with browsers and HTML, large bits of it don't work in every situation. The same is true of HTML, of course! Also, test your code as widely as possible on as many different browsers, platforms, screens and systems as you can before you introduce it to your site.
Clicking on this image wherever you see it will bring you back to the Contents section. |
Contents
Mouse Rollover (HTML Method, No Pre-load) Adding Date on a Webpage Time-Sensitive Greeting No Right Click Pop-Up Window Pop-Under Window Determining a New Window Size Auto Bookmark Back/Forward/Reload (can be varied to link text or images Print Jump Menu (Example 1) Jump Menu (Example 2) Jump Menu (Example 3) Frameset Page Loading Pre-formatting Email Headers, Subjects and Messages (HTML method) Safely Promoting Your Email Address (Javascript method) Form Command Buttons as Links |
Mouse Rollover (HTML Method, No Pre-Load)Here is an easy HTML way to change an image when the user hovers over it. The following code does not require you to use header insertions. It will require you to have two images, one that appears on page load, and one that appears when users hover or roll over the first image with their mouse. Finally, we also specify a return to our original image when the user mouses back out.
Step 1. Make a Link: <A HREF="TestPage.htm" onMouseOver="ChangingImage.src='Image2.jpg'" onMouseOut="ChangingImage.src='Image1.jpg'">
This tells the browser to do three things. Firstly, when the mouse rolls over the image, it changes the image to Image2.jpg. Secondly, when the mouse leaves the image, it changes the image to Image1.jpg. This code does NOT specify what the ORIGINAL image is: it only deals with changes of image state. Thirdly, if the mouse clicks on the image, the hyperlink loads the file "TestPage.htm" into your browser.
Step 2. Add the Image:This is the code which specifies the image you start with. It does not need to be one of the two images above, although there is rarely a practical use for a 3-image set in a simple rollover situation. You will see that it is a 'named' image, called "ChangingImage". The code works by varying the source filename of the object called "Changing Image".
<IMG SRC="Image1.jpg" NAME="ChangingImage" BORDER=0>
Step 3. Close the Link Tag: </A>
Step 4. Test it:Test it. You have now completed your image rollover.
Sample (try it)

<A HREF="TestPage.htm" onMouseOver="ChangingImage.src='Image2.jpg'" onMouseOut="ChangingImage.src='Image1.jpg'"><IMG SRC="Image1.jpg" NAME="ChangingImage" BORDER="0"></A>
So there it is. We start with an image called Image1.jpg. When the mouse rolls over it, it changes to Image2.jpg. When the mouse leaves, it changes it to Image1.jpg (which is also our starting image).
This technique is simple, works in most browsers, and it works on those pages where you have no access to the <HEAD> area (such as a 3rd Party Forum). It suffers from a slight delay in showing the alternate image when you first mouseover it. This can be overcome by another script which pre-loads the alternate image(s) into your cache, but that requires access to the page <HEAD> area. I hope to add this script element later.
Note: if you want the image only to change with no hyperlink attached, replace "TestPage.htm" with "#" |
Adding a Date on a WebpageWant to add a date in your webpage? Take this script and put it in the <body></body> tags where you want the date to show.
<SCRIPT LANGUAGE="JavaScript"> <!-- Begin Hiding myvar = new Date(); Month = (myvar.getMonth() + 1) Year = (myvar.getFullYear()) if (Month == 1) {WordMonth = "Jan";} if (Month == 2) {WordMonth = "Feb";} if (Month == 3) {WordMonth = "Mar";} if (Month == 4) {WordMonth = "Apr";} if (Month == 5) {WordMonth = "May";} if (Month == 6) {WordMonth = "Jun";} if (Month == 7) {WordMonth = "Jul";} if (Month == 8) {WordMonth = "Aug";} if (Month == 9) {WordMonth = "Sep";} if (Month == 10) {WordMonth = "Oct";} if (Month == 11) {WordMonth = "Nov";} if (Month == 12) {WordMonth = "Dec";} document.write(WordMonth+". "+myvar.getDate()+", "+Year); // End Hiding --> </SCRIPT>
If you want the full month to show, just change the contents of the WordMonth variable to long-format months ("January").
This piece of code shows something interestingabout the use of the "=" sign in Javascript. When it is used to compare two values, it must be used twice, as "==". When it is used to assign a value, it is used only once, as "=". This is a common source of coding errors because the error is not obvious when looking at a statement like "if(Month=12".
Left to its own devices, the line Year=myvar.getYear() ) would return a 'year value' of the Christian calendar less 1900. That's the way the date system works! So a further line Year=Year+1900 provides us with a regular Christian year value. If you wish to use another calendar, such as the Gregorian, you would need to adjust that offset value.
If you wished to assemble your date in a different order, such as "Year, Month, Day" or "Day, Month, Year", that is done by shifting around the three date elements assembled in the document.write() function. |
Time-Sensitive GreetingWouldn't it be nice to have a greeting on your page that responds to the time of day? This script does just that. You can paste this into your html document in the location you would like the greeting to appear. That's all there is to it. Now, when someone visits your site the greeting will be:
Good Morning. Welcome to my site! Good Afternoon. Welcome to my site! Good Evening. Welcome to my site! (depending on what time it is on their computer.)
Paste this anywhere in the body of your document.
<SCRIPT LANGUAGE="JavaScript"> <!-- Begin hiding todaydate = new Date(); timeis=todaydate.getTime(); todaydate.setTime(timeis); houris = todaydate.getHours(); if (houris > 17) display = "Evening"; else if (houris >12) display = "Afternoon"; else display = "Morning"; var WelcomeMsg = ("Good " + display + ". Welcome to my site!"); document.write(WelcomeMsg); // End hiding --> </script>
|
No Right ClickInsert this code somewhere between the <BODY></BODY> codes of your page.
<script LANGUAGE="JavaScript"> <!-- function click() { if (event.button==2) { alert('I will not let you do that'); } } document.onmousedown=click // --> </script>
I have attached this code to another page so that you can see it in effect. Please click on the button below to open that page.

I have included this code here because it shows something very important about Javascript. It's not just that this 'no right click' function is easy to workaround, it's that it only works in Internet Explorer. It does not work in Netscape 7, which has a full Java implementation, and it will not work in any other browsers that either do not support Java or which have had their Java features switched out. So beware of Javascript — never assume that it will always work for you or your user.
I may later add a better code example of this feature. I am not too worried about it because, as I have suggested, using Javascript for any front-end security feature is really asking too much of its limitations. |
Pop-Up Window<SCRIPT language="JavaScript"> <!-- window.open('PopUpTestPage.htm'); // --> </SCRIPT>
The above is the base code to create a pop-up window effect. If you put that anywhere in the page, when the page loads (or refreshes) it will cause a pop-up window to come into existence quite automatically.
I have attached this code to another page, or else it would already have appeared here. Click the button below to open that other page. When it opens, it will spawn a pop-up window.

|
Pop-Under Window<script language="JavaScript"> <!-- Hide script from older browsers if(navigator.appName.indexOf("WebTV")==-1) {
myWin = open('', 'winin','toolbar=0,menubar=0,scrollbars=1,status=0,resizable=1,width=620, height=430'); myWin.blur(); myWin.location = 'PopUnderTestPage.htm'; var shut=true; } // end hiding contents --> </script>
The use of blue colouring indicates a single line of code, not to be split across different lines when entered on the page.
Although very similar to the Pop-Up Window, this code includes a definition of the new window's size, as well as a few other definitions concerning its window type. You need to be careful when specifying these kinds of parameters because what works on your monitor may cause serious problems for someone using an old, 640x480 monitor. If your pop window causes a big problem to a user, that user will not want to stay around your site!
As with the pop-up sample above, I have attached the pop-up sample code to another page. Simply click the button below to go to a further page which will automatically spawn a pop-under page.

|
Determining a New Window SizeYou can determine the size of window that a new page will have when it opens. The following code is used between the <HEAD></HEAD> codes of the 'No Right Click' sample page.
<script language="JavaScript"> self.moveTo(0,0); self.resizeTo(630,280); </script>
The following button takes you to a sample page which uses this code.

The self-move means that, as the window is created, so it will move of its own accord to align its top left corner with the screen grid reference of 0, 0 (in order words, the top left of the screen). The size of the window (outside the borders, and less any window bars) is 630 pixels wide, by 280 pixels tall.
You can modify these parameters to other fixed values (make sure you do not make life too difficult for people with 640x480 monitors!) and you can use mathematics. In the sample below, the code would set the window height to the available height of the screen less 140 pixels. But beware! Netscape and Internet Explorer do not produce exactly the same size windows using these methods, I think because they differ over whether or not to include the window's border and menu area in the definition of the new window. Also, these different browsers each have different spaces taken up by the menu areas at the top, and can have different border widths determined by Windows itself, so defining the outside size of a new window is not guaranteeing you a specific amount of space inside the window, which is what you really want to define. But you can't, not without a lot of work which I won't go into here. Yes, it is a very silly situation, but such is life on the Internet.
<script language="JavaScript"> self.moveTo(0,0); self.resizeTo(630,(screen.availHeight-140)); </script> |
Auto BookmarkInsert this code somewhere in the body of your document. Take care that this only works with later versions of Internet Explorer.
<a href="javascript:window.external.AddFavorite('http://www.network54.com/', 'The Home of Network54');">Bookmark Network54's address!</a>
Bookmark Network54's address!
This code bookmarks the address you specify, not necessarily the address of the page. I have used this code to bookmark Network54's home address. It would be very highly unethical to use this feature to get someone to bookmark a page different to the one you indicate. |
Back/Forward/ReloadYou can insert any one or all three of the following code lines anywhere in the body of your document.
<a href="javascript:history.back(1)">Go Back</a> <a href="javascript:history.forward(1)">Go Forward</a> <a href="javascript:location.reload(1)">Refresh</a>
Go Back Go Forward Refresh
Note: these samples will only work if you have a page to go back to, or forward to! |
Print<a href="javascript:window.print()">Print this page</a>
Print this page |
Jump Menu (Example 1)All the examples of Jump Menus use the same addresses to keep things simple. Using them will lose this page, so make sure you know how to get back here using the BACK button in your browser (keyboard shortcut: ALT + left arrow key). One problem with Jump Menus is that you cannot use your right click to select 'Open In New Window' as you can with regular HTML links.
With this first example, two elements are visible: the drop-down box and the 'Go' button. Both these items size automatically according to the data content. So the drop-down box is sizing itself large enough to take "ICQ Instant Messenger" and the command button is sizing itself for the "Go" legend.
The line 'Option Selected' shows a series of hyphens ---------- which is displayed in the box before any selection is made. Once a selection is made the user will not see that line of hyphens again. It is only an unlinked starting value, so no selection has been pre-determined.
To move to a destination the user must first select it (to change its value) and then press the 'Go' button.
<SCRIPT LANGUAGE="JavaScript"> <!--- Hide from old browsers function jumpBox(list) {location.href=list.options[list.selectedIndex].value} // end hiding ---> </SCRIPT>
<FORM> <SELECT> <OPTION selected>------------------- <OPTION VALUE="TestPage.htm">A test page <OPTION VALUE="http://www.network54.com">Network54 <OPTION VALUE="http://www.msn.com">MSN <OPTION VALUE="http://www.yahoo.com">Yahoo <OPTION VALUE="http://www.mirabilis.com">ICQ Instant Messenger </SELECT> <INPUT TYPE="button" VALUE="Go" onClick="jumpBox(this.form.elements[0])"> </FORM>
|
Jump Menu (Example 2)Compared to the first example, this example differs in two ways. Firstly, the rather uninformative line of hyphens has been replaced by "Choose Destination", which should help a user to understand what the box is for. Secondly, and more importantly, as soon as the user makes a selection, the change of value triggers an 'onChange' function to occur which takes the user to the selected page without any other button being pressed. So there is no need of a "Go" button when this function is enabled in the drop-down box. Be warned that instant execution can be too abrupt for many users!
<form name="nav"> <select name="link" onChange="location=document.nav.link.options [document.nav.link.selectedIndex].value;" value="GO"> <option selected>Choose Destination</option> <option value="http://www.network54.com">Network54 <option value="http://www.msn.com">MSN <option value="TestPage.htm">A test page <option value="http://www.yahoo.com">Yahoo <option value="http://www.mirabilis.com">ICQ Instant Messenger </option> </select> </form>
As with most JavaScript, spacing is important. Please ensure that the second line of the code above (shown in blue) is entered continuously, without line breaks. There is no space in that line between '.options' and [document.nav'.
|
Jump Menu (Example 3)Compared to the previous two examples this one has pre-selected "Yahoo" as a destination. It has done this by including the word 'SELECTED' within its 'OPTION' definition. In many cases the topmost label would be the default selection, but this is just an example to show you the possibilities.
It would be inappropriate to use an 'onChange' function here. That is because any address could be selected except Yahoo, because the pre-selected Yahoo destination would not be a change of selection! So a command button is required, which this time is labelled "Go to the site". This is a very clumsy label but shows how a command button will resize to fit its label text.
<Script Language="JavaScript"> <!-- Hide from old browsers function NavJump(list){location.href = list.options[list.selectedIndex].value} // end hiding ---> </script>
<form> <Select> <OPTION VALUE="TestPage.htm">A test page <OPTION VALUE="www.network54.com">Network54 <OPTION VALUE="http://www.msn.com">MSN <OPTION SELECTED VALUE="http://www.yahoo.com">Yahoo <OPTION VALUE="http://www.mirabilis.com">ICQ Instant Messenger </SELECT> <INPUT TYPE="button" VALUE="Go to the site" onClick="NavJump(this.form.elements[0])"> </FORM>
|
Frameset Page LoadingOne of the many problems with using frames in the building of websites is that search engines tend to index the independent pages and link to them this way. Therefore, when someone follows the link in the engine, it will be to the individual page and not to the frameset that you designed for navigation around your site. This is a real problem if the only navigation that you offer your visitors is in one frame and the content is in a different page!
This little piece of code will correct this problem by ensuring that if someone tries to link into one html page, the script will force the opening of the entire frameset. This code needs to be inserted within the <HEAD> section of its host page.
I have enlarged this text so that you can clearly see the use of curly brackets { } and plain brackets ( ).
<script language="JavaScript"> if (parent.location.href == self.location.href) { window.location.href = 'index.html' } </script>
Just be sure to replace 'index.html' with whatever filename (full address, if needed) you use for your frameset declaration file. |
Pre-formatting Email Headers, Subjects and Messages (HTML method)Note: HTML leaves your email address exposed to harvesters. For a safer method which develops on these HML ideas, see also the Javascript procedure below.
You can click a hyperlink to send a message. It's simple and effective and lets the user define his or her mail message without having to fill in any tedious forms. However, did you know that you can pre-assign both the subject and the body text using the mailto tag? It's really easy and can help you quickly identify messages as they come in.
As you might know, the HTML for the mailto anchor tag is used like this: <a href="mailto:name@domain.com">Email me</a>
Email me
This creates a hyperlink that, when clicked, will launch the user's default mail program with the coded address in the "to" line. Now, you can take this a step further by introducing the "Subject" variable. For example, if you want people to submit a job application, you can pre-code the subject. This is important if you get lots of mail as it will quickly let you know the subject of these messages.
So, we would code the mailto like this: <a href="mailto:name@domain.com?Subject=Job_Application">Sample Subject Email Link</A>
Sample Subject Email Link
Note: it is best not to use spaces ... use an underscore (_) instead
Now, what if you wanted to pre-determine the Body Message as well? You may wish to do this if you have an offer that is always the same, such as a request for information. Let's say you're offering a free brochure. You can code the subject as "Free_Brochure" and the Body Message as "Please send me your brochure."
We code the mailto this way: <a href="mailto:name@domain.com?Subject=Brochure&Body=Please send me your brochure.">Sample Subject & Body Email Link</A>
Defining the message body may not work with all mail clients, but it "fails safe" with no text inserted.
So now you can save your visitors some time, and save yourself the anguish of strange email inquires by pre-coding your mailto expressions.
Sample Subject & Body Email Link |
Safely Promoting Your Email Address (Javascript method)These days, disreputable companies use robots to trawl the Internet searching for email addresses to collect and then sell to marketing companies. The process is called 'harvesting' and, one day, I hope it will become illegal. Until then, if you want to put your email address out there but don't want it harvested, you are safest using Javascript, not HTML, to publish that address for you.
Here are two working examples for you. They each defeat a harvester robot by breaking the email address into components. The robot is not clever enough to recompile the whole address and so returns garbage information to its selfish master.
Simple Link
Sample:
<script language=Javascript> <!-- var addy; addy = "mailto:"; addy = addy + "MyAccountName"; addy = addy + "@"; addy = addy + "email.com"; document.write("<a href=" + addy + ">Email me</a>"); // --> </script>
Link With Subject Line
Sample:
[new lines are shown in red]
<script language=Javascript> <!-- var addy; addy = "mailto:"; addy = addy + "MyAccountName"; addy = addy + "@"; addy = addy + "email.com"; addy = addy + "?subject=" addy = addy + "About_The_New_Website" document.write("<a href=" + addy + ">Email me</a>"); // --> </script> As with the HTML methods above, you can also add a message body to your email by ading more lines of code to your Javascript. If you examine the preceding HTML section and the two samples above, you will understand how to do this. |
Form Command Buttons as LinksThis uses stylised Command Buttons as hyperlinks. In Internet Explorer 6 and Netscape 7 it all looks very pretty. Alas in Netscape 4.79 and iE v4 it lacks the chosen colours and does not work. But I leave it here as a code sample which might interest you, and recommend that you don't use it in the exampled role (for navigation-essential links) until probably 2005-2006, when the older browsers will be mostly out of use.
<form method="post" action="TestPage.htm"><input type="submit" value="Click Here to visit the Test Page" style="font-family:Verdana, Arial, Helvetica, sans-serif; color:FFFFFF; font-weight:bold; background-color:green;"> </form>
If you don't like the look of the standard form button when it is modified like this (or to some other style of your choosing) you can instead use styles to modify simple hyperlinks. You will be pleased to hear that this not only looks good in Netscape, the linkage also works, so is much the preferred option compared to the command button approach, above.
<a href="TestPage.htm"> <span style="font-family:Verdana, Arial, Helvetica, sans-serif; font-weight:bold; text-decoration:none; color:FFFFFF; background-color:yellow;"> Got To Test Page </span> </a>
Go To Test Page
With this type of background/foreground colouring going on, make sure that the text is legible in all colour states of the link text (that is: before and after it has been visited). |
Back to the top Back to the Index Page |