26 March 2016

Detecting different mouse button clicks

The following example demonstrates capturing left, middle, and right mouse clicks with jQuery –along with changing element text, and toggling viability. It was made for my daughter who is into magic, and scored me some dad points.

JSFiddle: https://jsfiddle.net/n2fole00/t3aL5zmq/

<head><script src="https://code.jquery.com/jquery-2.2.0.min.js"></script></head>

<div style="margin-left:auto;margin-right:auto;text-align:center">
    <h2>Are you a magician?<br>Can you make the cat appear and disappear?</h2>
    <button type="button" style="font-size:x-large">Show me cat!</button>
    <img src="insert_cat_pic_here">


$( "img" ).toggle(); // hide on img on init

// disable right click context menu
$('*').contextmenu( function() {
    return false;

$('button').mousedown(function(event) {
    switch (event.which) {
        case 1:
        case 2:
        case 3:
            // show cat
            $( "img" ).toggle();
            // change text of button
            if ($(this).text() == "Show me cat!") 
                $(this).text("Make cat disappear!"); 
                $(this).text("Show me cat!"); 
            alert('You have a strange Mouse!');


No comments:

Post a Comment