TheGr8_Nik
TheGr8_Nik

Reputation: 3200

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

Upvotes: 12

Views: 11765

Answers (2)

Iglesias Leonardo
Iglesias Leonardo

Reputation: 544

There you go! Just run the snippet.

const element = document.getElementById('test');
setupElement(element);

function setupElement(element){
    let clickedByMouse = false;

    element.onclick = (e) => {
        console.log(clickedByMouse);
        if(clickedByMouse){
          e.preventDefault();
        }else{
          doSomething();
          clickedByMouse = false;//reset clickByMouse if needed
        }
        console.log(clickedByMouse);
    }
    
    element.onmousedown = (e) => {
        clickedByMouse = true;
    }

}
#test {
  height: 200px;
  background-color: #000;
}
<div id="test"></div>

Upvotes: 1

Shreyas
Shreyas

Reputation: 1462

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

Upvotes: 1

Related Questions