Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 713
Imran Avatar asked Jan 08 '11 02:01

Imran


2 Answers

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();
};
like image 166
David Tang Avatar answered Oct 04 '22 13:10

David Tang


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.

like image 22
Marcus Whybrow Avatar answered Oct 04 '22 13:10

Marcus Whybrow