Is onClick Universal for Mouse buttons?

733 Views Asked by At

I notice Google use onMouseDown in their search results - for web tracking, seeing keyword and ranking etc.

I want to know which is better, onClick or onMouseDown - or do they both support all of the following: middle button, left click, right click (other buttons like Gamer mouse). Are they supported in all browsers including those on mobile phones, tablets and all other operating systems? It is paramount that the function loads first. HREF is left for SEO and other UI/UX benefits in case of failure of javascript.

<a href="http://www.site.com" onclick="doMyFunctionFirst();">
JavaScript loaded before the href URL
</a>

Or

<a href="http://www.site.com" onMousedown="doMyFunctionFirst();">
JavaScript loaded before the href URL
</a>

Or the seemingly obvious (I do not do this as every character for space matters for my client)

<a href="http://www.site.com" onclick="doMyFunctionFirst();" onMouseDown="doMyFunctionFirst();">
JavaScript loaded before the href URL
</a>
3

There are 3 best solutions below

1
On BEST ANSWER

The main difference is that while onmousedown triggers regardless of which mouse-button was pressed, onclick triggers only for the left mouse button - which will be most likely what you want.

1
On

Notably, the click event will fire if you tab to a link and press Enter, but the mousedown/mouseup will not.

0
On

The W3C spec doesn't seem to specify whether the events should fire for all buttons, only that the button pressed should be indicated on the "button" property of the event object. Under Chrome at least it doesn't appear that "click" fires for anything except the main (in my case, left) mouse button. Quirksmode has a useful test harness to check this.

The onclick, onmousedown and onmouseup represent different behaviours, none of which is intrinsicly "better": a "click" is a press and then release of the button, mousedown is the "down" and mouseup is the "release". Normally this would be relevant if you were doing some drag/drop operations.

The MDN documentation indicates that onclick fires after mousedown and mouseup.

Also, ideally you should be attaching event handlers using Unobtrusive Javascript techniques, rather than in the markup.

HREF is left for SEO and other UI/UX benefits in case of failure of javascript.

If the event handler is doing a redirect/AJAX request or similar, you should use the preventDefault method if you don't want the browser to follow the link after firing your event.