Imran
Imran

Reputation: 61

Detecting mouse click on div with Javascript without side-effects

I want to detect whenever someone clicks in a div (essentially I want to know when a user is interacting with a section of text on my site, be that by selecting some text or clicking on a link), but I don't want to interfere with what the user is doing.

If I put a onmousedown or onclick event on the div it ends up breaking selection, links, etc. Is there any way to catch these events without causing any interference ?

Upvotes: 6

Views: 19587

Answers (4)

CZar
CZar

Reputation: 17

Can't you simply add a click event to the div?

<div id="secretDiv" (click)="secretDivClick()">

then on your component:

secretDivClick() {
console.log('clicked');
}

Upvotes: -2

e11438
e11438

Reputation: 894

you can use do it by adding a event listener as well

var myNode= document.querySelector('.imagegrid'); 
myNode.addEventListener("click",function(e){    
 alert(e.target+" clicked"); 
}); 

A similar example is demonstrated here

Upvotes: 1

David Tang
David Tang

Reputation: 93664

Onmousedown or onclick shouldn't interfere with anything as long as it doesn't return false;.

You can do this:

document.getElementById("spy-on-me").onmousedown = function () {
    console.log("User moused down");
    return true; // Not needed, as long as you don't return false
};

If you have other scripts that are attaching behaviour via this method on the page, then to prevent overriding them you can do:

var spyElement = document.getElementById("spy-on-me");
var oldMousedown = spyElement.onmousedown;
spyElement.onmousedown = function () {
    console.log("User moused down");
    if(oldMousedown) oldMousedown();
};

Upvotes: 11

Marcus Whybrow
Marcus Whybrow

Reputation: 19988

Yes, I suspect you are currently returning false at the end of the event binding, just don't do that or any of the things in this binding:

$('a').click(function(e) {
    e.stopPropagation();
    e.preventDefault();
    return false;
});

If you do not do any of these three things, jQuery will not stop the event from bubbling up to the browser.

Edit: Sorry didn't realise it was a plain JavaScript question.

Upvotes: 3

Related Questions