A-OK
A-OK

Reputation: 3254

Handle clicks on an element but not clicks on links within that element

How do I handle clicks on an element but not clicks on links within that element? Say I have the following

<div class="section">
    Some text blah blah
    <a href="#">Link</a>
</div>
<script>
    $(".section").click(function() {
        // code to expand/collapse section
    });
</script>

And I want users to be able to click on .section in order to expand/collapse it but I don't want that to happen if they clicked on a link within that section.

Upvotes: 3

Views: 122

Answers (4)

sv_in
sv_in

Reputation: 14049

$(".section").click(function(e) {
    if($(e.target).is('a')) {
      return;
    }

    // code to expand/collapse section
});

e.target points to the element on which the user had clicked. So the function checks whether the target was a a element. if yes, it just returns from the function

Upvotes: 1

Dogbert
Dogbert

Reputation: 222398

var $section = $(".section");
$section.click(function(e) {
    if ($(e.target).get(0) == $section.get(0)) {
        alert("expanding...");
    }
});

http://jsfiddle.net/yLMVy/

Upvotes: 1

korywka
korywka

Reputation: 7653

use return false; in the end of function

Upvotes: 0

James Allardice
James Allardice

Reputation: 166051

You can check the event target, and only do something if it is the div. Here is one example:

$(".section").click(function(e) {
    if(e.target.tagName !== "DIV") {
      //Not the div! 
    }
});

You can test various properties of the target, so if for example you had other child div elements, but didn't want to register clicks on those, you could use the className property:

e.target.className !== "section"

Here is a working example (using the tagName property).

Upvotes: 4

Related Questions