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">
    <br><br>
    <h2>Are you a magician?<br>Can you make the cat appear and disappear?</h2>
    <br>
    <button type="button" style="font-size:x-large">Show me cat!</button>
    <br>
    <img src="insert_cat_pic_here">
</div>

<script>

$( "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:
            break;
        case 2:
            break;
        case 3:
            // show cat
            $( "img" ).toggle();
            // change text of button
            if ($(this).text() == "Show me cat!") 
            { 
                $(this).text("Make cat disappear!"); 
            } 
            else 
            { 
                $(this).text("Show me cat!"); 
            }; 
            break;
        default:
            alert('You have a strange Mouse!');
    }
});

</script>

No comments:

Post a Comment