最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Detecting mouse click on div with Javascript without side-effects - Stack Overflow

programmeradmin0浏览0评论

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 ?

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 ?

Share Improve this question asked Jan 8, 2011 at 2:10 ImranImran 611 gold badge1 silver badge2 bronze badges 1
  • Unless you specifically have code that interferes (such as setting event.cancelBubble, calling event.stopPropagation() or returning true (or something truth-y) you code shouldn't be interfering. Can you show a specific example? – RoToRa Commented Jan 8, 2011 at 2:23
Add a comment  | 

4 Answers 4

Reset to default 11

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)

  1. 暂无评论