views:

44

answers:

2

For example, for accessibility reasons I want my onfocus and onmouseover to have identical values. For the sake of maintainability I want to declare this once only.

What I'd like to be able to do is this:

<a onmouseover,onfocus="assist('hello');">linktext</a>

But, of course, that would be too easy, and doesn't work. What's the best way I can achieve this DRYing out of my tags?

+4  A: 

Best I can think of is to use a function, set both events to call the function and put the common code in there.

Cobusve
+7  A: 

The better way is to move all your event handlers out of the HTML and into javascript.

<a id="some_id">link text</a>  

(You don't need to use an ID, it's just for ease of demonstration.)

var link = document.getElementById('some_id');
link.onmouseover = link.onfocus = function() {
    assist('hello');
};

If you wanted to take it to the next level, you could generalise it across many links. This example uses jQuery.

<a href="#hello" class="assist">link text</a>
<a href="#something" class="assist">another link</a>

Then you apply the event handler to all the links in one go (very dry!)

$('a.assist').bind('mouseover focus', function() {
    assist(this.href);   // you'd need to clean up the href here, but you get the picture
});
nickf
This looks very promising indeed. Thanks Nick.
graphicdivine
In practice I'm using the `rel` attribute to pass my text along, rather than the `href`, but this is great, just what I needed. Thanks a lot.
graphicdivine