-1

Left Click

$(document).ready(function(){
    $( "div" ).click(function() {
      $( this ).toggleClass( "class-one" );
     //alert('left click');
    });
});

Right Click

$(document).ready(function(){
    $( "div" ).click(function() {
      $( this ).toggleClass( "class-two" );
     //alert('Right Click');
    });
});

it's my requirement Jquery Mouse left click add one class and mouse right click add another class, so my task left click add class is done and right click add class is Not working,

If you possible on right click on Jquery ?

  • 2
    http://stackoverflow.com/questions/4235426/how-can-i-capture-the-right-click-event-in-javascript – Morpheus Oct 09 '14 at 12:44
  • duplicate of so many questions..just do a google search..or a SO search.. – Bradley Oct 09 '14 at 12:45
  • try this http://jsfiddle.net/Kn9s7/5/ or http://stackoverflow.com/questions/1206203/how-to-distinguish-between-left-and-right-mouse-click-with-jquery/2725963#2725963 – Aru Oct 09 '14 at 12:48

3 Answers3

2

The event name for right-click is contextmenu:

$("div").on("contextmenu", function() {
    $(this).toggleClass("class-two");
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You can try this:

$(document).ready(function () {
    $("div").mousedown(function (e) {
        $(this).toggleClass("class-two");
        if (e.button == 2) {
            alert('Right mouse!');
            //here goes the code you want to add in mouse right click
        }
    });
});
div {
    height:100px;
    width: 100px;
    background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
Alex Char
  • 32,879
  • 9
  • 49
  • 70
0

Do this way:

HTML --

<div id="test">
    test test
</div>

CSS --

div {
    width: 300px;
    height: 200px;
    background-color: #99EAEA;
}

.class-one {
    background-color: #EAEAEA;
}

.class-two {
    background-color: #EA3355;
}

JQUERY --

$(document).ready(function(){ 
    document.oncontextmenu = function() { return false; };

    $("#test").click(function() {
      $( this ).removeClass("class-two").addClass("class-one");
    });

    $(document).mousedown(function(e){ 
        if( e.button == 2 ) { 
            $("#test").removeClass("class-one").addClass("class-two");
            return false; 
        } 
        return true; 
    });  
});

that's it! Demo: http://jsfiddle.net/ag62dyry/1/

Zanoldor
  • 378
  • 6
  • 13