trigger body click with jQuery

120,793

Solution 1

You should have something like this:

$('body').click(function() {
   // do something here
});

The callback function will be called when the user clicks somewhere on the web page. You can trigger the callback programmatically with:

$('body').trigger('click');

Solution 2

Interestingly, when I replaced this:

$("body").trigger("click")

With this:

jQuery("body").trigger("click")

It works!

Solution 3

I've used the following code a few times and it works sweet:

$("body").click(function(e){ 
    // Check what has been clicked:
    var target = $(e.target); 
    if(target.is("#target")){
    // The target was clicked
    // Do something...
  }
});

Solution 4

if all things were said didn't work, go back to basics and test if this is working:

<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
  </head>
  <body>
    <script type="text/javascript">
      $('body').click(function() {
        // do something here like:
        alert('hey! The body click is working!!!')
      });
    </script>
  </body>
</html>

then tell me if its working or not.

Share:
120,793
ruturaj
Author by

ruturaj

Updated on May 30, 2020

Comments

  • ruturaj
    ruturaj almost 4 years

    I'm unable to trigger a click on the body tag using jQuery using this:

    $('body').click();
    

    Even this fails:

    $('body').trigger('click');
    
  • ruturaj
    ruturaj almost 15 years
    I've already done what u've mentioned.. When I personally click anywhere on the page, the click Handler works perfectly
  • Pradeep Kumar
    Pradeep Kumar almost 15 years
    do you mean you're trying to fire the event? instead of firing the event, why not call the function your click handler would?
  • ruturaj
    ruturaj almost 15 years
    yes I'm trying to fire the event, I want to simulate a click on the body.
  • ruturaj
    ruturaj almost 15 years
    I'm writing a unit test using QUnit (docs.jquery.com/QUnit) and hence I've got to fire the event and then check if the handler worked as it was supposed to work.
  • Russ Cam
    Russ Cam over 14 years
    that indicates to me then that you're using other JavaScript frameworks on the page that also have a $() shorthand defined function.
  • Seeker
    Seeker over 13 years
    hmmm... just note u answer your own question X). anyway u can do alert($.toString()); to give you a clue of what is the other "plugin" that is interfering with jQuery.
  • KevinDeus
    KevinDeus almost 12 years
    or another version of JQuery in a related script.. I got it when using JQGrid when referencing .each()