开发者

Detecting mouse click on div with Javascript without side-effects

I wa开发者_如何学Pythonnt 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 ?


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();
};


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.


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


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

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

then on your component:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜