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.
Author by
ruturaj
Updated on May 30, 2020Comments
-
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 almost 15 yearsI've already done what u've mentioned.. When I personally click anywhere on the page, the click Handler works perfectly
-
Pradeep Kumar almost 15 yearsdo you mean you're trying to fire the event? instead of firing the event, why not call the function your click handler would?
-
ruturaj almost 15 yearsyes I'm trying to fire the event, I want to simulate a click on the body.
-
ruturaj almost 15 yearsI'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 over 14 yearsthat indicates to me then that you're using other JavaScript frameworks on the page that also have a $() shorthand defined function.
-
Seeker over 13 yearshmmm... 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 almost 12 yearsor another version of JQuery in a related script.. I got it when using JQGrid when referencing .each()