JQuery click event on blank space

I am trying to catch an event when a user presses spacebar on a page using jQuery. For example, let's say you have the following:

<html>
<head>
    <title>Test</title>
</head>
    <body>
        <p>Here some text!</p>
    <body>
</html>

      

I want to catch an event when the user clicks on nothing but the p tag.

Is there a way to catch something like this?

+2


source to share


6 answers


This works in chrome. Haven't tried other browsers. Works from the idea that stickmangumby:



$('body').click( function (e) { 
    if ( e.target == this ) 
        alert('works'); 
});

      

+3


source


It works:

$(function() {
    $('body').click(function() {
        alert('clicked the page');
        return false;
    });
    $('*:not(body)').click(function() {
        alert('clicked an item!');
        return false;
    });
});

      



One "problem" you'll get is that paragraphs are block elements by default, so clicking on the sentence side will cause the element to click, even if it looks like you haven't clicked on the element.

+4


source


You can view the doc for onclick and then check event.currentTarget in your event handling function.

+2


source


I was looking for a solution to a similar problem - hide the custom tooltip when clicking on the document, but not when clicking inside the nib. I did it like this (changed the selector as per the question):

$(document).bind('click', function(e) {
    if($(e.target).closest('p').length == 0) {
        //p is not clicked. do your stuff here
    }
});

      

+2


source


I am creating a small web application that is similar to Taskpaper (for Mac) and I want it to simulate the application's behavior. More proof of concept than anything else

In light of your comments, I wouldn't worry about the body at that time. Connect a div instead so you can restrict the area you want to respond to events. In the case when there are no other elements on the page, they are one and the same.

For what it's worth, on any web page, your users will hate you if they click any blank space somewhere - it will be a bad user interface experience.

+1


source


You can do something like this (I think)

$('body').not('p').click(function(){});

      

Not sure how well this will work.

0


source







All Articles