Search code examples
javascriptgoogle-chromegoogle-chrome-extension

Is it possible to detect a mouse click on a page on every element?


I want to trigger a function if a user clicks anywhere on the page, even clicking on no element or link. Is it possible?

The extension runs only on youtube.com so I can't add every element on the page to the trigger and I assume that every page has different element's ids.


Solution

  • Emmanouil Chountasis is correct, you can use the code at "Detect left mouse button press" to detect a left mouse click crossbrowser.

    To the heart of your question, I think what you're looking for is Event Delegation. In jQuery,

    // Select a wrapper for the events
    $('body')
      // Whenever any element in the <body> is clicked
      .on('click', '*', function (evt) {
        // Emmanouil Chountasis's suggestion would be called right here
        if (isLeftClick(evt)) { 
          // ... do stuff
        }
      });
    

    See http://learn.jquery.com/events/event-delegation/