-1

I want to make right and left click do different things on my custom element.

In this original code. in the element file I defined some event listeners for mouse clicks:

container.addEventListener("mousedown", startDrag);
container.addEventListener("contextmenu", onRightClick);

document.addEventListener("mouseup", endDrag);

And some methods that's supposed to be called which will alter an array in the data section:

function startDrag(e) {
    // some code here
}

function endDrag(e) {
    // some code here
}

function onRightClick(e) {
    // some code here
}

The two arrays to be altered (named here intersected and rightClicked are watched, and custom events are emitted when they're altered

watch: {
    intersected(i) {
      this.$emit("change", i);
      console.log("emitting change");
    },
    rightClicked(i) {
      this.$emit("rightclicked", i);
      console.log("emitting rightclicked");
    }
},

So they work perfectly fine. However as I said, I want left and right click to do different things, and as of now right clicking triggers both contextmenu and mousedown. If I change the event listeners to

container.addEventListener("mousedown.left", startDrag);
container.addEventListener("contextmenu", onRightClick);

document.addEventListener("mouseup.left", endDrag);

left clicking would do nothing. The event change was never emitted. Right clicking still emits rightclicked as expected.

What am I doing wrong here?

Dan
  • 195
  • 3
  • 12

1 Answers1

0

The event.button property to determine which mouse button was clicked.

Try this:

container.addEventListener("mousedown", function(event) {
  if (event.button === 0) {
    startDrag(event);
  }
});

container.addEventListener("contextmenu", function(event) {
  event.preventDefault(); // prevent the context menu from showing up
  onRightClick(event);
});

document.addEventListener("mouseup", function(event) {
  if (event.button === 0) {
    endDrag(event);
  }
});
Greg
  • 1,401
  • 11
  • 11