How to exclude links from the .click handle

advertisements

I'm trying to handle .click action but exclude links from it so that you could click on a link in an element without firing .click.

I've got no clue how to do that. I've tried z-indexes, position: absolute, relative but nothing worked.

<style>
div {
background: yellow;
height: 200px;
}
</style>
<script>
$(window).load(function(){
   $(function() {
      $( "div" ).click(function() {
          alert( "Click handler." );
      });
   });
});
</script>
</head>
<body>
    <div>
        <a target="_blank" href="http://stackoverflow.com/">Link</a>
    </div>
</body>
</html>

http://jsfiddle.net/KwAE7/

Any help? Thanks!


You can check the 'currentTarget' vs 'target', the currentTarget is the exactly the object that you putted the bind, and the 'target' is the element that is clicked, that could be any element inside your div. This way you will ensure that the event will only be fired when the click is in the div.

http://jsfiddle.net/hBLF9/

$(function() {
    $('div').bind('click', function(ev) {
        if($(ev.currentTarget).get(0) == $(ev.target).get(0)) {
            alert('clicked');
        };
    });
 });