How to use jQuery to detect mouse clicks

Right after I found out how to get mouse cursor coordinates when mouse moves, I went ahead with exploring how to detect mouse clicks.

This post discuss how I had used jQuery to detect mouse clicks.

Registering a JavaScript callback function to listen to mouse clicks

Getting my codes notified of mouse clicks is simple via jQuery:

$(document).mousedown(function(e) {
    switch(e.which) {
        case 1:
	    $('#mouseButtonStatus')
                .html("You had just clicked on the left button of your mouse");
            break;
        case 2:
	    $('#mouseButtonStatus')
                .html("You had just clicked on the scroll button of your mouse");
	break;
        case 3:
	    $('#mouseButtonStatus')
                .html("You had just clicked on the right button of your mouse");
            break;
    }			
});

I wrap the document object with jQuery and supplied a function to the mousedown function. In the function, I will receive a event object e from jQuery when mouse clicks are detected. I then use e.which to switch between numbers that identify which mouse button was being clicked. A 1 will mean that the left button of my mouse was clicked, a 2 will mean that the scroll button of my mouse was clicked and a 3 will mean that the right button of my mouse was clicked.

In each of the three cases, I then use jQuery to look up the HTML element labeled with mouseButtonStatus as its id and inject the appropriate messages as its HTML content.

The entire HTML document

To fully realize this proof of concept, I head over to my list of HTML code segments and construct a HTML document. In the head section, I add the jQuery codes; In the body, a HTML div element with mouseButtonStatus as its id to contain the message.

<html>
<head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
	$(document).ready(function(){	   
	    $(document).mousedown(function(e) {
	        switch(e.which) {
		    case 1:
		        $('#mouseButtonStatus')
                            .html("You had just clicked on the left button of your mouse");
		    break;
		    case 2:
			$('#mouseButtonStatus')
                            .html("You had just clicked on the scroll button of your mouse");
		    break;
		    case 3:
			$('#mouseButtonStatus')
                            .html("You had just clicked on the right button of your mouse");
		    break;
		}			
	    });
	});
    </script>
</head>
<body>
<div id="mouseButtonStatus">
No mouse clicks detected yet.
</div>
</body>
</html>
Advertisements

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people.

Advertisements
Advertisements