Question

So I guess it's pretty unanimous that using href="javascript:fn_name();" is bad practice. But let's say I have a link: <a href="#" class="exec-fn">Click me</a>.

I can use

$('.exec-fn').click(fn_name);

But this isn't very accessible. Since it's a click event, this doesn't work for tapping or, perhaps, tabbing to the link and pressing Enter to follow it. I kind of want to emulate the browser's ability to focus and follow a link as its default behavior allows it to, but I know the javascript: protocol is not recommended, and I also don't always want to name a globally accessible function either.

Is there a better method?

Was it helpful?

Solution

There is a corresponding recommendation:
http://www.w3.org/TR/DOM-Level-3-Events/#click-synthesis

If the instance of the activation trigger is not an event of event type click (that is, when it does not result from a user's activation of a button or link using a mouse or equivalent pointing device), the implementation MUST synthesize and dispatch an event of event type click as one of the default actions of that activation trigger. The value of the Event.target MUST be set to the event target (normally, the currently focused element), and the event MUST simulate a left click (i.e., the MouseEvent.button attribute value MUST be 0, and the MouseEvent.buttons attribute value MUST be 1). Other context information of such a simulated click event is implementation dependent, but for historical purposes, the interface for the click event MUST be the MouseEvent interface, regardless of the actual device used to activate the element. Preventing the default action of the activation trigger, such as with the Event.preventDefault(), MUST stop the initiation of the activation behavior.

And an example:

When a user activates a hyperlink using a keyboard, such as by focusing the hyperlink element and pressing the 'Enter' or ' ' key, a click event would be dispatched as the default action of the respective keydown event.

Basicly, click event is a way to go.

OTHER TIPS

Projects like Ben Alman's JQuery BBQ provide a nice easy way to listen to hash changes. You could keep your link as <a href="#go-there">Do things</a>. JQ BBQ can pick up and do things and go places.

Frameworks like Backbone have this built in to Router. You could create a router for #/go-there and have some things happen.

If you're more of a vanilla-js kind of dev, then use the window.onhashchange event https://developer.mozilla.org/en-US/docs/Web/API/window.onhashchange

I'm on my phone, just had a few minutes of down time. Otherwise I'd provide links and more verbosity. Sorry.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top