graphicdivine
graphicdivine

Reputation: 11211

Can I declare the same value for two attributes at once

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?

Upvotes: 0

Views: 163

Answers (2)

nickf
nickf

Reputation: 546273

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
});

Upvotes: 7

Cobusve
Cobusve

Reputation: 1570

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

Upvotes: 4

Related Questions