0

I asked here (How to detect right click + left click) how to detect when user right click hold it and click on the left button of the mouse

I did like the first answer but its not working as expected,

First in my code I create table and td's, and then I add events to every td like that:

td.setAttribute('onmousedown', "handleMouseDown(event)");
td.setAttribute('onmouseup', "handleMouseUp(event)");
td.setAttribute('onclick', "checkCell(this)");

I dont use addEventListener` because IE < 9.

The two functions to handle the events is:

function handleMouseDown (e) {
     if (e.button == 2) rightClicked = true;

}
function handleMouseUp (e) {
    if (e.button == 2) rightClicked = false; 
}

First its dosent work good, the handleMouseUp dosen't always set rightClicked to false
when I was clicked on left button its dosent set rightClicked to false when I release the right button so I add to checkCell if rightClicked is true so set it to false.

 if (rightClicked) {
      rightClicked = false;

Now In the first time I click right click and left its work, but after that its not work anymore unless continue to press left click and after that sometimes it work
Sometimes its dosent work even the first time

My all code in jsfiddle: https://jsfiddle.net/e4pf78zu/ Its dosent work fine there the functions shown in the console as undefined I dont know why can someone fix that for me thanks

Community
  • 1
  • 1
Harman met
  • 241
  • 2
  • 3
  • 10

1 Answers1

0

This doesn't work for a couple of reasons.

First of all you are setting the event listeners for each cell in a very weird way, not to mention you are doing it wrong.

td.setAttribute('onmousedown', "handleMouseDown(event)");

Why didn't you simply do

td.onmousedown = handleMouseDown;

Also, you are doing handleMouseDown(event), which I am pretty sure is wrong.

In general, please don't add your event handlers like this.

I dont use addEventListener` because IE < 9.

IE9 and below don't support addEventListener but they do support attachEvent which is probably better than doing .on<EventName> = function(){}, or what you are doing there currently.

Moreover you can even simulate addEventListener in these browsers as well. Simply use this polyfill here, and in general read about addEventListener

the handleMouseUp dosen't always set rightClicked to false when I was clicked on left button

rightClicked is supposed to become false only when you release the right button, so that works as expected.

its dosent set rightClicked to false when I release the right button

Well, based on the code you provided, that's impossible. The code pretty clearly says

if (e.button == 2) rightClicked = false; 

so I add to checkCell if rightClicked is true so set it to false.

This was probably not needed. Resolve your other issues first and then see if you really need to do this.

Dimitris Karagiannis
  • 8,942
  • 8
  • 38
  • 63