views:

7527

answers:

4

I'm unable trigger a click on the body tag using jQuery, I'm using this...

$('body').click();

even this fails

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

Any ideas?!

+1  A: 

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');
kgiannakakis
I've already done what u've mentioned..When I personally click anywhere on the page, the click Handler works perfectly
ruturaj
do you mean you're trying to _fire_ the event? instead of firing the event, why not call the function your click handler would?
Jonathan Fingland
yes I'm trying to fire the event, I want to simulate a click on the body.
ruturaj
I'm writing a unit test using QUnit (http://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.
ruturaj
trigger('click') works for me both in Firefox and IE
kgiannakakis
A: 

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

$("body").click(function(e){
  //you can then check what has been clicked
  var target = $(e.target);  
  if (target.is("#popup")) {
  }
}
Fermin
+1  A: 

interestingly.. when I replaced

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

with

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

IT WORKED!!!

ruturaj
that indicates to me then that you're using other JavaScript frameworks on the page that also have a $() shorthand defined function.
Russ Cam
A: 

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"&gt;&lt;/script&gt;
  </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.

Seeker
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.
Seeker