Current Events- a Client Side Tipsheet

by Kenneth Tibbetts

There are nearly always events on webpages, even the simplest pages, and these events always have to be handled, somehow, by the client software. Hyperlinks and anchors have been around since the beginnings of the web.  Forms, with their input text boxes, options lists and buttons are still a common way to facilitate a user's interaction with a site.

Handle with care

Hyperlinks and forms do most of their stuff on the server, but it is important to not lose sight of the fact that nothing happens before the browser deals with the user input- mouseing over a link lights up the link, say, and writes the url to the status bar. Clicking submit calls a function on the browser before sending anything to be processed. Even on clients that don't do scripting you have a fairly hefty amount of event handling going on.

There may be a basic functionality you want to give your pages for users with older browsers, and for these clients, links and forms are it. By keeping your html simple, and adding functionality through scripts, you ensure that every visitor will get the most out of the page.

And even in the most modern browser, bulging with muscular methods and more properties than Masterpiece Theater, using links and forms is often the best way to get users to interact with the page. They are familiar elements, the visitor knows immediately what to do.

A nice thing thing about the new browsers is they support events on just about any html element you can think of. Event handling, however, is not much different than it was yesterday. It is still a browser specific, not quite standardized porridge of incompatable methods and properties. I use the DOM recommendations as much as I can, but in the area of event handling, we are still pretty much on our own. I'll give you a few examples.

Some of the DOM event interfaces are available for Mozilla and Netscape6, but there are enough holes in them that you will often be calling on methods and properties that have been around since Navigator. And while IE has had pretty decent event handling since version 4, it hasn't yet adopted the recommendations. In fact, it's added some new proprietary stuff.

Common Events in HTML

Most of the time,today, the best way to set up an event handler is the simplest, and the oldest- set a property of an html element. This code will work in most browsers:


For Example:

document.links[0].onmouseover=writeStatus;

//where writeStatus is a function that handles a mouseover event:

function writeStatus(e){

var thisStatus=Run.whoEver(e).href.pathName;

var ax=thisStatus.lastIndexOf('\/')+1;

if(ax!=-1) thisStatus=thisStatus.substring(ax);

window.status= thisStatus;

return true;

}

/* Note that you don't define the argument (e). 

The argument is the sniffer- Netscape Navigator and N6/ Mozilla automatically pass an argument for each event. This is basically the DOM scheme as well.

 

IE doesn't pass an argument, but every event instantiates a global window.event object.

 

You could handle your events in the first lines of every function you write, but save typing. Putting a few generic event handlers in your code makes it easy to keep up with the vendors- change once, read many. 

 

Call on an event examiner for the detailsyou need about the event. Most often I want to know what element has triggered the event, which is Eve's specialty.

*/

 


Who is it?

function Run.whoEver(e){

var trigger='';

if(!e && event.srcElement) trigger= event.srcElement;

else if(e.target) trigger= e.target;

if (trigger.nodeType && trigger.nodeType== 3) 
         trigger= trigger.parentNode;

return trigger;

}

/*

If there is an argument (e) you know you have an event argument to work with. Otherwise see if you are working with IE. The DOM is gonna use target and currentTarget (see below) , Netscape 4 and Opera use target, and IE has the lovely srcElement.

 

Whichever, the browser examines the event and returns a reference to the element that triggered it. 

*/

 

 

If you need to use the DOM event phase, which captures events on the way up or down through the document, precede the e.target branch with 
" else if(e.currentTarget) trigger=e.currentTarget". 

I rarely use it, but probably will when IE gets onboard. 

I have used this little function for years, it works in everything from Netscape's version 3 on. I have added a line for DOM aware browsers, to bump up a text node to its parent, because most of the time I work on the element level. But I like to keep it as simple as possible, it gets called a lot.

Page Geography

Another common task is finding where the user is in a document.. The DOM returns clientX and clientY from the event object to tell you where on the display the click or other event came from- but it doesn't take scrolling into account. You may find that a display  triggered by a user's click is out of sight up there somewhere. Again, I have a central branching code:

Where Was the Click?

/*

You can call Run.whereAt from anyplace you need to know the exact location of an event on the displayed page.

 

The returned value is a two element array - [x,y].

*/

function Run.whereAt(e){

var positionX=0;

var  positionY=0;

if(!e && window.event){ // IE code

positionX= event.clientX+ document.body.scrollTop;

positionY= event.clientY+document.body.scrollTop;

if(document.createDocumentFragment) {

    positionY+= document.documentElement.scrollTop;

    positionX+= document.documentElement.scrollTop;

}

/*

I have to test IE browsers to see if they use the document.body or the document.documentElement to control the scrollbars.  I test for IE6+ with the createDocumentFragment test, which isn't supported in previous versions. Older IEs scroll the body, new ones scroll the html element

*/

}

else if(window.pageXOffset){ // N6 and Mozilla

positionX= e.clientX+ window.pageXOffset;

positionY= e.clientY+ window.pageYOffset;

}

var posArray=[positionX, positionY];

return posArray;

}

/*

Netscape6 and Mozilla look at some special properties they gave the window object. There is no DOM equivilent for the page being scrolled. Navigator has its own methods, which I have out back in the quonset hut full of layers, activeX and java code.

 

I usually don't call this unless the visitor has got IE or N6/Mozilla. In an older browser, you can set up anchor elements and hyperlink inside the page to scroll around. But this is sometimes very useful, and makes navigating a long page easier on your visitors.

 

Here's a page that uses this:

 

*/

 

Adding Events and Listeners

HTMLElement.Run.eventListener has been around a while now, but it can't completely replace the specific methods that each vendor has had since version 4. You use it like a method of an element, with three arguments- the type of event,the handler function, and a boolean switch that turns on capturing.

element.addEventListener('click',function,false);

/*

Note- you use the event type without the "on" prefix. And don't quote the false, or you may make it evaluate to true.

*/

If it is a transitory event you need to follow up with a removeEventListener, passed the same arguments, to turn it off.

The best use for it today is when you are truly adding an event- when an element has an onclick or onmouseover event already, and you want to augment the event without replacing it. When you mouseover a heading you may want to pop up a description, and sometimes, but not always, insert a link into the description. Or you could call an extra event if the visitor has selected some combination of elements to view. In IE4 or Netscape Navigator you would have to replace the original event handler, and add the new actions to the old.

In N6/Mozilla and the DOM recommendation you add an event handler to the element. Whatever else is set up for the element is still in place. But test it- there is no guarantee that the order of events will be what you intend. IE 5+ goes its own way again- you "attach" an event to the element. And when you are through with it,  you call detachEvent.

Add an Event Handler

function Run.addEvent(who,wot,evnt){

/*

who is an object reference to an element in the document. 

wot is an event type- click, mouseover,blur . Note that IE has to have the 'on' added to the event type.

 

evnt is a function reference.

If I used capturing I would send a fourth parameter

*/

if(document.Run.eventListener){

who.addEventListener(wot,evnt,false);

}

else if(window.attachEvent){

    wot='on'+wot;

who.attachEvent(wot,evnt);

}

else who[wot]=evnt;

}

This is a useful function, but limited. The DOM doesn't say anything about keyboard events, and when you use add event listener you can't examine the element properties to see what is attached to what, but have to look for specific eventListener registrations. 

There's more, there is always more, but these examples should throw a little light on what you can do, and why, sometimes,you have to bend the standards a bit, if you want to write code that works.

Happy returns...

The End...

More :

Wriggling Mozilla

When you can't trust a browser...

Waiting for the DOM...

 More Articles