Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

Javascript, onMouseover etc.

Events in js code rather than html tags?



10:54 pm on Jun 27, 2003 (gmt 0)

10+ Year Member

Instead of having a whole bunch of <a href="#" onMouseover="...> in your html is there a way to declare your onMouseover, or other events, in your js file?

It would save a lot of clutter if this is possible.



2:27 am on Jun 28, 2003 (gmt 0)

WebmasterWorld Senior Member korkus2000 is a WebmasterWorld Top Contributor of All Time 10+ Year Member

Not that I know of. There are methods for event handlers but they are not supported really well.


11:33 am on Jun 28, 2003 (gmt 0)

10+ Year Member

If you're not too fussed about supporting older browsers you could do something like

<body onload=init() ...

<a href="#" id=a0>

function domouseout () {
//do stuff

function domouseover () {
//do stuff

function init(){
for (i=0;i<13;i++)

don't ask me why but the id has to start with a letter.


1:27 pm on Jun 28, 2003 (gmt 0)

10+ Year Member

The id has to start with a letter because that is how id's are defined by the W3C - 'ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").'


3:27 pm on Jun 28, 2003 (gmt 0)

10+ Year Member

As korkus2000 said this is poorly supported. IE6 doesn't recognize the standard.

Anyway, here's an example I put together to give you an idea. If you want to use this you'd need to improve the sniffing and drop older browsers. The ie5 sniff needs to be on 1 line.

An interesting point, Opera 7 works with both methods. You gotta feel for those Opera programers :)


ie5 = document.all && document.getElementById && navigator.userAgent.toLowerCase().indexOf('opera')==-1?1:0

onload = function() {
links = document.getElementsByTagName('a')
links_length = links.length
for (var i=0; i<links_length; i++) {
if (ie5) {
links[i].attachEvent('onmouseover', href_on_mouse_over)
links[i].attachEvent('onmouseout', href_on_mouse_out)
} else {
links[i].addEventListener('mouseover', href_on_mouse_over, false)
links[i].addEventListener('mouseout', href_on_mouse_out, false)
output = document.getElementById('output-div')

function href_on_mouse_over() {
output.value = 'over'

function href_on_mouse_out() {
output.value = 'out'



<a href="some_page.htm">link 1</a>


<a href="other_page.htm">link 2</a>


<input type="text" id="output-div">



6:40 pm on Jun 28, 2003 (gmt 0)

10+ Year Member

I just stumbled on a "links" colection. The array name in my example should be changed.



Featured Threads

Hot Threads This Week

Hot Threads This Month