3

I'm looking for a way to intercept all mouse events (especially clicks) on a web page.

My first instinct was $('body').click(....)

But that's not capturing the event if any other Handler is attached for a particular event.

To put the question in context: I'm writing a "statistics" module for my web app. We want to keep track of all user interactions on the pages to adapt. If we see they don't use a functionality we will add a tooltip for example.

I have following frameworks :

jQuery, Knockout and a little Framework "home made"

What I want is a function which is called on each click with mouse position.

Jurion
  • 1,230
  • 11
  • 18

1 Answers1

6

Try something like this (without jQuery):

    var eventCount = 0;
    var eventProperty = [];

    var TrackMouse = function (mouseEvent) {
        eventProperty[eventCount++] = {
            id: mouseEvent.toElement.id,
            type: 'mouse',
            ts: Date.now(),
            x: mouseEvent.x,
            y: mouseEvent.y
        };

        console.log("Element id: " + eventProperty[eventCount - 1].id + ", X: " + mouseEvent.x + ", Y: " + mouseEvent.y + "\n");
    };

    document.addEventListener('click', TrackMouse);
Nick
  • 4,002
  • 4
  • 30
  • 41
  • 1
    Are you sure this event will fire even if there is a custom event on, let say, textbox ? – Jurion Nov 16 '13 at 03:47
  • Worked perfectlly with little modification. (No array eventProperty and no more counter eventCount++] ) How can I upvote you ? – Jurion Nov 16 '13 at 03:53
  • Sorry, realized I forgot to declare eventProperty. Check out this fiddle: http://jsfiddle.net/theoutlander/UP7yY/ – Nick Nov 16 '13 at 03:56
  • No worries, worked prefectlly for me ! Thatnk youa lot :) c# i'm your guy, but JS and css..... Not me – Jurion Nov 16 '13 at 04:00
  • document.addEventListener('click', TrackMouse, **true**); Use the boolean third parameter for event capturing instead of bubbling: http://stackoverflow.com/questions/4616694/what-is-event-bubbling-and-capturing – Vial Jul 13 '16 at 21:53