Rion Williams
Rion Williams

Reputation: 76577

Selection of Div that contains no class - jQuery

I have been attempting to capture the event when a user clicks on a section of my menu that doesn't contain any other type of contents / class.

The menu itself is separated into two portions, both of which are floated (one on the right and another on the left) and I am just trying to grab when the click occurs inside the parent div (the menu) and outside of the floated divs.

Markup:

<div id='test'>
    <div class='t1'>
    </div> 
    <div class='t2'>
    </div>
</div>

CSS

#test
{
     background-color: red;
     height: 30px;
     width: 50%;
     position: relative;

}
.t1
{
     float: left;
     width: 45%;
     height: 30px;
     background-color: blue; 
     margin: 0;
     padding: 0;
}

.t2
{
     float: right;
     width: 10%;
     height: 30px;
     background-color: blue; 
     margin: 0;
     padding: 0;
}

Example:

jsFiddle Example!

I was mainly wondering if this was possible just using selectors through jQuery, as opposed to another method of examining what was clicked and determining if the correct area was clicked. (Both of these methods are acceptable though.)

Upvotes: 2

Views: 228

Answers (2)

lonesomeday
lonesomeday

Reputation: 237995

Compare this to e.target. If they are the same, the element where the event is handled will be the same as the one where it originated.

$('#test').click(function(e)
{
    if (this === e.target) {
        alert('#test itself clicked');
    } else {
        alert('some child element was clicked');
    }
});

jsFiddle.

Upvotes: 3

Pointy
Pointy

Reputation: 413895

You can add a handler for the contained elements:

$('#test *').click(function(e) {
  e.stopPropagation();
});

That'll keep those events from bubbling up to the top.

Alternatively, you could check to see if the event target is the right element:

$("#test").click(function(e) {
  if (this === e.target) alert("success!");
});

Updated fiddle.

Upvotes: 3

Related Questions