How to Create Image Rollovers in JavaScript?
Image rollovers (sometimes also called Image MouseOvers or mouse-overs) are a fairly common sight in websites today (although I don't use them at this time on Affiliated-Business.com). You've probably seen them around too: when you move your mouse cursor over a button on a particular site, the button appears to be depressed. Move your mouse cursor away, and the button pops out again.
Image rollovers are implemented by creating two images for the same button. The first image is that which you want displayed when the mouse is not hovering over it, typically the "undepressed" or "up" state of a button. The second image is the graphic you want displayed when the mouse pointer is over the graphic, usually showing the button in a depressed or "down" state.
The actual mouse-over effect is created by some JavaScript code that is added to the affected links. Your link would typically look like this:
<a href="index.html"
onmouseover="buttondown('homebutton')"
onmouseout="buttonup('homebutton')">
<img src="homebutton.gif" name="homebutton" border="0" />
</a> |
When your mouse moves over the link above, the JavaScript snippet above will attempt to execute the function buttondown(). When your mouse moves away, the function buttonup() will be executed.
Now you need to add the called JavaScript functions to your web page. Add the following code to the <head> section of your HTML document.
<script language="JavaScript" type="text/javascript">
<!--
if (document.images) {
homebuttonup = new Image();
homebuttonup.src = "homebutton.gif" ;
homebuttondown = new Image() ;
homebuttondown.src = "homebuttondown.gif" ;
}
function buttondown( buttonname )
{
if (document.images) {
document[ buttonname ].src = eval( buttonname + "down.src" );
}
}
function buttonup ( buttonname )
{
if (document.images) {
document[ buttonname ].src = eval( buttonname + "up.src" );
}
}
// -->
</script> |
The initial code pre-loads the "home" button images needed for the page, so that the actual roll-over switch of images will proceed faster on your visitor's browser.
The function buttondown() and buttonup() modifies the name of the button that is passed to them. If you will recall, the name attribute on the <img> tag was originally set to "homebutton". When this is passed to the buttondown() function, it changes the reference to "homebuttondown.src" which was defined earlier to point to the file "homebuttondown.gif". Likewise, the buttonup() function, when called changes the name passed to it to "homebutton.src", which was defined to refer to "homebutton.gif".
The end result of the foregoing is that when the mouse moves over the "Home" button, the JavaScript function causes the "homebuttondown.gif" file to be displayed. When it moves away, the "homebutton.gif" file is used.
Modifying the Code
You can modify the code above to add support for other buttons (such as an "About" button, a "Feedback" button, etc).
To add support for, say, an "About" button, you would simply have to add an additional link to the main web document like the following:
<a href="about.html"
onmouseover="buttondown('aboutbutton')"
onmouseout="buttonup('aboutbutton')">
<img src="aboutbutton.gif" name="aboutbutton" border="0" />
</a> |
Remember that the parameter given to the buttondown() and buttonup() functions must match the "name" attribute of the IMG tag.
To the initial portion of the JavaScript code in the <head> section, just add the following lines to the first "if (document.images) {" section, following the code for the "home" buttons:
aboutbuttonup = new Image();
aboutbuttonup.src = "aboutbutton.gif" ;
aboutbuttondown = new Image() ;
aboutbuttondown.src = "aboutbuttondown.gif" ; |
The final code snippet for the <head> section will thus look like this:
<script language="JavaScript" type="text/javascript">
<!--
if (document.images) {
homebuttonup = new Image();
homebuttonup.src = "homebutton.gif" ;
homebuttondown = new Image() ;
homebuttondown.src = "homebuttondown.gif" ;
aboutbuttonup = new Image();
aboutbuttonup.src = "aboutbutton.gif" ;
aboutbuttondown = new Image() ;
aboutbuttondown.src = "aboutbuttondown.gif" ;
}
function buttondown( buttonname )
{
if (document.images) {
document[ buttonname ].src = eval( buttonname + "down.src" );
}
}
function buttonup ( buttonname )
{
if (document.images) {
document[ buttonname ].src = eval( buttonname + "up.src" );
}
}
// -->
</script> |
That's it. No other code modifications are needed. Notice that the functions buttondown() and buttonup() have not been modified. They will work with your other buttons as long as you follow the pattern given above in naming your up and down buttons.
You're not limited to "about" and "home" buttons of course. You can add as many buttons as you need by following the procedure outlined above.
Limitations
The code above requires JavaScript 1.1 and above to execute. This means that if your visitor is using a browser prior to Netscape 3.0 or Internet Explorer 4.0, they will not be able to view your rollovers.
The links, however, will still work correctly when clicked (even on browsers with JavaScript disabled or with no JavaScript support at all). This is important since mouseover effects are purely cosmetic, and you don't want them to detract from the overall functionality of your site.
Note that you should probably also make sure that the files you use for the buttons are small. If your files are too big, the image rollovers (or mouse-overs) will not have the smooth effect of buttons popping up and down that you intend.
Finally, like all web page graphics, use your discretion in implementing mouse-over images on your site. Excessive use of rollover images will add to the overall load time of your web pages, and, if you are on a commercial web host, increase your bandwidth costs.
How to Make a Text Link Submit A Form
Every now and then, I get a question from one of my visitors at Affiliated-Business.com asking how a text link can be made to work like a submit button in submitting the contents of a form. This is easily done, with the help of a bit of JavaScript.
For the uninitiated, the usual way that the contents of a form is submitted is when someone clicks on a button created with HTML (or XHTML) code like the following:
Alternatively, some people prefer to replace the ugly button with a graphical image. If the image is called, say, "buttonimage.gif", the code to do this might take the following form:
| <input type="image" src="buttonimage.gif" /> |
Search as you might, you will probably not be able to find any documentation in your HTML manual on how you can make a text link function as though a submit button has been clicked. And no wonder. HTML does not directly support such a feature.
The JavaScript Code
If you want the contents of a form submitted when a text link is clicked, you will need a little help from JavaScript. Needless to say, if this is the only way your form can be submitted, your form will never be used by visitors who do not have JavaScript enabled in their browsers.
Let's say you have a form that begins in the following way:
| <form name="supportform" method="post" action="yourscriptname.cgi"> |
Now, suppose you want to have two text links, one of which is for "Paid Support" and the other for "Free Support". Clicking either of these text links is supposed to cause the form to be submitted, with some device to indicate which link was clicked.
The code to implement this is simple. First, place the following JavaScript code somewhere on your page, such as in the HEAD section of your document.
<script language="JavaScript" type="text/javascript">
<!--
function getsupport ( selectedtype )
{
document.supportform.supporttype.value = selectedtype ;
document.supportform.submit() ;
}
-->
</script> |
Now add the following to your form prior to the closing FORM tag.
<input type="hidden" name="supporttype" />
<a href="javascript:getsupport('Paid')">Paid Support</a> or
<a href="javascript:getsupport('Free')">Free Support</a> |
As you can see from the FORM snippet, when the text link "Paid Support" is clicked, getsupport will be called with the string "Paid". Likewise, when the text link "Free Support" is clicked, getsupport will be called with the string "Free" in its argument.
The function getsupport sets the form variable "supporttype", which you defined as a hidden field in the form, to the string given in its argument. This is "Free" or "Paid" depending on which link was clicked. It then submits to form to the CGI script you defined in the "action" attribute of the FORM tag.
Modifying the Form
You will probably want to modify or extend the form to suit your purposes. For example, you might want to change the name of the variable "supporttype" in the code or add more possible values that can be assigned to it. Whatever you do, remember to synchronize your JavaScript code with your form code. For example, if you change "supporttype" to something else in the JavaScript code, remember to change the hidden INPUT tag to contain your new name as well.
Conclusion
There you have it. A text link that can be used to submit a form. Trivial, isn't it?
Do remember, though, before you rush out to implement this in your forms, that not everyone has JavaScript enabled in their browsers. Those without JavaScript will see your form, click it, and find that nothing happens. You will have to weigh the advantage of having this kind of facilities on your site against the cost of excluding non-JavaScript users.
Breaking Out of Frames JavaScript
Fed up of being trapped in some other site's frame even when you've left their site? You can provide your visitors with a simple way to break out of the frame. The traditional method is to put a link on your page that allows your visitors to click and open the existing URL in the window without the frame. Code for such a link might look like the following:
Trapped in a frame?
| <a href="SamePageURL.html" target="_top">Click here</a> to break out of it. |
The target="_top" attribute causes the web browser to open the document in the topmost window. This method has the disadvantage of requiring your visitors to actually read your instructions and click the link.
You can also provide a way for them to break out of frames without having to take any action themselves. One way to do this is through a JavaScript function which you can put in your <head> section, like the following:
<head>
<script language="JavaScript" type="text/javascript">
<!--
function breakout_of_frame()
{
// see http://www.thesitewizard.com/archive/framebreak.shtml
// for an explanation of this script and how to use it on your
// own website
if (top.location != location) {
top.location.href = document.location.href ;
}
}
-->
</script>
</head> |
Alternatively, you can put the following in a file called (say) "scripts.js" and load it from every page. I do this at Affiliated-Business.com since it allows me to maintain one copy of the script even though it is loaded by every page on the site.
function breakout_of_frame()
{
// see http://www.thesitewizard.com/archive/framebreak.shtml
// for an explanation of this script and how to use it on your
// own website
if (top.location != location) {
top.location.href = document.location.href ;
}
}
|
The code to include the script in your web page is:
<script src="scripts.js" language="JavaScript" type="text/javascript">
</script> |
It should be placed in the <head> section of your web page.
The function breakout_of_frame() checks to see if the URL of the topmost window is the same as the URL of the current window. If it is not the same, it sets it to be that of the current window, effectively loading the URL into the top window and removing the frames.
To use the above function automatically, you will have to call the script in the "body" tag:
<body onload="breakout_of_frame()">
... (the rest of the document) ...
</body> |
and voila! If your visitors have JavaScript enabled, when they enter your site, they'd be automatically rid of the irritating frame.
If you prefer to give your visitors the choice of whether to continue in a frame or to break out of it, you can put a button on your page that users can click to break out of the frame instead of using the "onload" attribute in your <body> tag. The code for the button is as follows:
<form action="dummyvalue">
<input type="button" value="Breakout of Frame"
name="button" onclick="breakout_of_frame()" />
</form> |
Such code may be useful if the frames are actually your own, and you want to allow your visitors to have a "No Frames" version of your pages without having to bother with specifically coding for it.
Adding a What's New Section to Your Website
If you look at Affiliated-Business.com, you'd probably noticed that it has a What's New section on its main page. What is probably more striking is that you can find a What's New section on almost every single sub-site on Affiliated-Business.com, which is saying a lot, since it means that that one site alone has five "What's New" sections in addition to a "What's New on This Site" page!
The story is that when I first experimented with such a section, I found that the traffic to the pages highlighted in that section increased by quite a large number. Apparently, even though I already had links to those sub-pages from my main page, highlighting them in this way actually increased their visibility, thus attracting more visits.
This does not mean that the number of unique visitors to your site increases - of course not. That depends on your advertising *outside* your site. This tactic only helps your existing visitors find interesting stuff on your site. It is essentially a facility that improves your intra-site navigation.
Who Should Include One?
A "What's New" section is particularly useful if your site has the following characteristics (like Affiliated-Business.com):
- Content is constantly being added or changing.
- Your site has a large number of pages.
If your site only has a main page with a "Feedback Form" and a "Reciprocal Links" for your sub-pages (or pages like that), a "What's New" section is probably meaningless for you.
What If My Content Doesn't Change Often?
Even if your site's content does not change frequently, you still can have a section that highlights certain sub-pages on your site. You should not however, call it a "What's New" section. If you do, your visitors will quickly notice that nothing new ever graces that section and think that your site is abandoned.
Instead, you can always call it a "Featured Pages" section, where you highlight certain pages on your site. You should of course link to those pages (and not merely mention them).
Is It Okay To Simply Have A What's New Page?
In the early days of thefreecountry.com, I only had a "What's New on This Site" page, which was linked from the main page. Although the content of this page changed frequently (since the site is constantly being updated), I noticed that there was one constant throughout the history of that page: the small number of visitors (relative to the overall site).
The basic rule of web design holds here as well: if visitors have to click to get anywhere or do anything, many will not bother to do it.
If you want something to be noticed by them, put it under their noses. Put it on your front page. You needn't put everything on the front page - maybe just the latest news. You can always link to your more comprehensive "What's New" page at the bottom for those who are really interested.
What Should I Write?
It's really up to you. The important thing here is to be sure that even as you mention changes (or features), you link to your sub-pages that hold those changes. Don't expect your visitors to have to search through your entire site to find the page you mentioned. I have encountered (many) sites with that kind of "What's New" section. They're really not using it to its full potential. It doesn't merely have to be informational - it can serve as a means to draw your visitors to certain pages.
Conclusion
Sure, if you want to maintain both a "What's New" section on your main page and a "What's New" page, it's a big hassle to have to keep both in sync. In my opinion, however, the results make it worth the effort. Your visitors appreciate that section because it helps them keep abreast of changes, and you benefit because those pages get highlighted and visited more often than it normally would.
Drop Down Navigation Menu JavaScript
Improving Your Site Navigation
We all know the value of making it easy for visitors to navigate a website. In general, your visitors are unlikely to search every single page of your site just to get the information they want. If they cannot easily get to the information they are looking for, they'll just leave the site.
There are many ways to improve the navigation on your site. One common method is to put a drop-down navigation menu on your website, which is the subject of this article.
(For the curious, some of the other ways of improving your navigation include Putting a Site Search Engine on your site and Adding a What's New Section to your website.
Using a JavaScript Drop Down Menu
A drop-down menu typically contains a list of pages on your site that your visitors can select from a drop down list. When he selects the page, he is automatically transported to the appropriate page.
The simplest way to get such a menu for your website is to use the Navigation Menu Wizard to create a customized menu for your site according to your specifications. Alternatively, you can read this article which describes how such a menu is constructed.
Constructing Your Drop-Down Menu
The first thing you need for the drop down navigation menu is to put the following JavaScript function somewhere in your web page, before the actual menu itself. For example, you can put it in the <head> section of your document, or if you prefer, immediately before the drop down menu itself (see later).
<script language="javascript" type="text/javascript">
<!--
function menu_goto( menuform )
{
// see http://www.thesitewizard.com/archive/navigation.shtml
// for an explanation of this script and how to use it on your
// own site
var baseurl = "http://www.put-your-domain-name-here.com" ;
selecteditem = menuform.newurl.selectedIndex ;
newurl = menuform.newurl.options[ selecteditem ].value ;
if (newurl.length != 0) {
location.href = baseurl + newurl ;
}
}
//-->
</script> |
The function takes a single argument - the form object. It then proceeds to extract the selected value from the object and load the page from that URL.
Please change the "baseurl" given above to the domain name of your site. I did not terminate the URL with a slash because all my filenames in the menu below start with the slash. If you terminate your URL here with a slash, do not start your filenames below with a slash.
If your site is designed with frames, you will need to use "top.location.href" instead of "location.href" if you want the new document to replace your all your frames. You can leave it as it is if you want the document to appear in the current frame. Alternatively, if you want it to be in another frame (sibling of the one in which the menu appears), just replace "location.href" with "parent.your_frame.location.href" where "your_frame" is the frame named "your_frame".
Now for the menu itself. Since the exact URLs for your menu and the names of the pages will differ for your site, you should modify the code given below for your situation.
<form action="dummyvalue">
<select name="newurl" onchange="menu_goto(this.form)">
<option value="" selected="selected">----- Select A Page -----</option>
<option value="/index.html">Home</option>
<option value="/feedback.html">Feedback</option>
<option value="" disabled="disabled"> ---- Miscellaneous ----</option>
<option value="/links.html">Related Links</option>
</select>
</form> |
Please note the following about the menu code above:
- This menu code goes into the portion of your web page where you want your menu to appear.
- The action attribute for the <form> tag is required under HTML. Since our form never uses it, you can place some dummy value there, as I have done above.
- It is helpful to put something like "Select a Page" as the first item in the menu so that visitors looking at the drop down box will know that it is a menu. I have set the "selected" attribute as well for that item to ensure that it is shown as the default selection when the page loads.
- The "Miscellaneous" menu item illustrates the use of subtitles or separators in the menu. They serve as organising tools to help visitors see the various sections in the menu. Many modern browsers will recognise the "disabled" attribute and not allow visitors to select that item. However, if you want to be sure, you can set the value of such item to your main page or your site index.
- You will, of course, have to change the filenames in each of the option "value" tags as well as the description of those files.
Changing Your Pages
Trivial isn't it? However, changing your pages is not so trivial if your site has numerous pages. Worse, if you have the intention of including every page on your website in that menu, each time you add a new page, you have to go through all your pages to modify the menu. Sooner or later, the menu will cease to be a novelty.
I faced this problem when I decided to convert all of Affiliated-Business.com's approximately 150 pages to include a drop down menu. For those of you familiar with this site, you will probably know that I add new pages (with new articles or with other categories of free stuff) rather regularly. Not only would the conversion be a pain, the maintenance would be a nightmare.
To minimize your maintenance nightmare, you might want to consider one of the following options.
- Use the JavaScript menu code generated by Navigation Menu Wizard . Be sure to select the "Pure JavaScript version" when generating the code. The Wizard generates code where all the menu items are contained in an external JavaScript file. Everytime you need to add a page, simply change that external JavaScript file, and the menu on all your pages will automatically be updated, instantaneously. Using this code has an additional advantage - if your visitor does not have JavaScript, your menu will not appear on the page at all. This is good since the menu will not function without JavaScript anyway, and having it appear on your page but not working tends to make visitors lose confidence in your website.
- Put your site in frames, and place the menu in one of the frames that is loaded for every page. That way, you only have to modify one page. The disadvantages of this method include: visitors who do not arrive at your site through your frameset page would not get to see the menu (happens more often than you think!); many people strongly dislike frames; some older browsers cannot handle frames; and unless you take special action, search engines do not index a site with frames particularly well.
- Put your menu in a separate file, and include it on every page using server side includes (SSI). Once again, each time you add to the menu, you only need to modify one file. Disadvantage: Some web hosts require files using SSI to have a ".shtml" extension for all your pages, so if your pages do not already have this extension, it means that you have to rename all your pages. This is however a short-term problem. Once you complete that renaming, you have solved it. You should of course set up some sort of redirection so that people going to your old .html pages will be redirected to the renamed versions.
- Put your menu in a separate file, but prior to uploading, run a script on your own machine that inserts it into every page. Then upload the modified pages to your site. The disadvantage of this method is that everytime you modify your menu, you have to re-upload every single page that uses that menu.
Conclusion
Having a drop down navigation menu improves your site navigation, and hopefully allows your visitors to locate the information they need on your site. The JavaScript menu described here is one way in which such a menu can be implemented.
Form Input Validation JavaScript
Many websites, like Affiliated-Business.com, have a feedback form of some sort so that visitors can make comments to the webmasters. If you have such a form on your site, I'm sure that from time to time, you would have received the results of your form with some essential field (like the email address or the visitor's name, or even the feedback itself) omitted.
Don't worry - this is a common problem. One way around it is to validate the essential fields with a simple JavaScript.
To do this, you will need to add a call to your validation function when the form is submitted. You do this by adding a "onsubmit" attribute to your FORM tag, like the following (keep it on one line if possible):
<form action="mailto:yourname@yourdomain.com" method="post" onsubmit="return checkform(this);"> |
If the field you want to validate is something like:
| <input type="text" name="email" /> |
then your validation routine will look like the following (put it, say, in the HEAD of your document):
<script language="JavaScript" type="text/javascript">
<!--
function checkform ( form )
{
// see http://www.thesitewizard.com/archive/validation.shtml
// for an explanation of this script and how to use it on your
// own website
// ** START **
if (form.email.value == "") {
alert( "Please enter your email address." );
form.email.focus();
return false ;
}
// ** END **
return true ;
}
//-->
</script>
|
You will need to replace the "email" in both the "name" attribute of the INPUT tag as well as the function checkform to the actual name of the field you want to check. For example, if you want to check a field called "fullname", replace all instances of "email" in the function with "fullname".
The function begins by checking that the field named "email" is not an empty string. If it is, it will call the alert() function to display a dialog box with the message "Please enter your email address." It then calls form.email.focus() to place the text cursor in the email field for the convenience of the visitor and returns "false" to prevent the form from being submitted. On the other hand, if the field was not empty, nothing is executed and the form is submitted as usual.
What if you want to check more than one field? Simply copy everything from the
// ** START **
line to the
// ** END **
line and place it immediately below the existing
// ** END **
line, before the " return true; " statement. Then change all occurences of "email" in the new block to the name of the field you wish to check. You can duplicate that procedure as many times as you have fields to check.
|