Skip to main content

Detect Mouse Button

When adding JavaScript functionality to a page, it can be useful to know which mouse button was clicked when a user clicked a mouse button. The following script can tell you which mouse button was clicked.

Example

Click this text with different mouse buttons

The Script

<script type="text/javascript">
function detect_button(e)
{
    e = e || window.event;

    if (e.which == null)
    {
        button = (e.button < 2) ? 'left' :
            ((e.button == 4) ? 'middle' : 'right');
    }
    else
    {
        button = (e.which < 2) ? 'left' :
            ((e.which == 2) ? 'middle' : 'right');
    }

    alert(button);
}

document.getElementById('clicker').onmousedown = detect_button;
if (document.captureEvents) document.captureEvents(Event.MOUSEDOWN);
</script>
Get help with games!