1

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.

shinzou
  • 5,850
  • 10
  • 60
  • 124
  • you can inject the code of the above question in the page so your problem will be solved. – Emmanouil Chountasis Aug 30 '15 at 08:20
  • 1
    Voting to reopen (..err, magically reopening by dupehammer), as duplicate is incorrect. It deals only with detecting whether a particular click event is a left mouse button (which isn't even asked by the OP!) and does not deal with the core problem of capturing the even anywhere on the page. – Xan Aug 30 '15 at 10:14

2 Answers2

2

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/

Community
  • 1
  • 1
Reed Spool
  • 843
  • 7
  • 15
0

Reed's answer works fine, but it triggers the action multiple times. I found this solution that only works on left mouse triggers and executes once per click.

$("body").unbind().click(function() {
    //Do Stuff
});
desertnaut
  • 57,590
  • 26
  • 140
  • 166