Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent click event from mousedown

I tried the following code on Chrome, Firefox and IE:

var test = document.getElementById('test');

test.addEventListener( 'click', function ( e ) {
  alert( 'clicked' );
});

test.addEventListener( 'mousedown', function ( e ) {
  e.stopImmediatePropagation();
  e.stopPropagation();
});

In chrome, the alert will not be fired; in firefox and ie, yes. Which is the correct behaviour? How can I prevent the click event to be fired?

jsBin Example

like image 280
TheGr8_Nik Avatar asked Oct 27 '15 09:10

TheGr8_Nik


1 Answers

If you want to cancel the click event, you can do that in the Capture phase. Attach a click listener to the body to cancel the click event on the required element. The third argument in addEventListener lets you specify if you want to use the capture phase.

http://jsbin.com/kocapuharo/1/edit?html,css,js,output

like image 136
Shreyas Avatar answered Sep 20 '22 17:09

Shreyas