Heisenberg
Heisenberg

Reputation: 5299

How to detect event by right clicking

I would like to unregister some event with a right click.

For example, when I register an event clicking some cells, it's color will change. like below:

$(function() {  
$("#our_calendar td").click(function(){
    $(this).css('background', 'yellow');

  });
});

I would like to unregister with right click. I found some answers:

Is right click a Javascript event?

I wonder if it is possible to unregister (initialize it's color) by right clicking ,and is it possible not to display window with right click.

If someone has experienced such issues, please let me know.

thanks

Upvotes: 0

Views: 112

Answers (3)

User863
User863

Reputation: 20039

You are searching for contextmenu event and off()

$("a")
  .on('click', function() {
    $(this).css('background', 'yellow');
  })
  .on('contextmenu', function(e) {
    e.preventDefault();
    $(this).off('click').css('background', 'unset');
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a href="javascript:;">Button</a>

Upvotes: 2

Tui T&#237;nh Tếu
Tui T&#237;nh Tếu

Reputation: 1

YOu can using:

$('#our_calendar td').mousedown(function(event) 
{

    switch (event.which) {
        case 1:
            alert('Left mouse button is pressed');
            break;
        case 2:
            alert('Middle mouse button is pressed');
            break;
        case 3:
            alert('Right mouse button is pressed');
            break;
        default:
            alert('Nothing');
    }
});

Upvotes: 0

Jerdine Sabio
Jerdine Sabio

Reputation: 6140

Assuming by unregister, you mean removing the color you set initially by clicking, yes you could. You could also prevent the dropdown (contextmenu) being displayed by passing an argument e or event argument in your event handler and using by e.preventDefault();

Try the demo below, click to set color and right click to unset;

$("#our_calendar td").on("contextmenu", function(e) {
  e.preventDefault();
  $(this).css('background', 'unset');
}).on("click",function(){
  $(this).css('background', 'yellow');
});
td {
  padding: 15px;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="our_calendar">
  <tr>
    <td>1</td>
    <td>1</td>
    <td>1</td>
    <td>1</td>
    <td>1</td>
  </tr>
  <tr>
    <td>1</td>
    <td>1</td>
    <td>1</td>
    <td>1</td>
    <td>1</td>
  </tr>
  <tr>
    <td>1</td>
    <td>1</td>
    <td>1</td>
    <td>1</td>
    <td>1</td>
  </tr>
</table>

Upvotes: 4

Related Questions