Perform function by clicking except on specific item with jQuery

Asked

Viewed 646 times

1

I have the following code:

$(".teste").click(function() {
    return false;
});

Inside that div .teste I have links with the class .link and I want, when clicking on the div, the return false, but that the return false if I click on the links (.link) that are inside the div. I’ve tried:

$(".teste").not("a.link").click(function() {
    return false;
});

tried as well:

$(".teste:not(a)").click(function() {
    return false;
});

But they both didn’t work.

HTML (example):

<div class="teste">
    <div class="outradiv"></div>

    <div class="maisumadiv">
        <a href="/teste" class="link">Link...</a>
    </div>
</div>
  • Could you put your HTML code too to better understand the situation?

  • I added an example

  • In addition to HTML also put CSS, or else a fiddle with your code

4 answers

3

Well, you already have several answers, but I’m going to propose another method:

$('.teste').click(function(e) {
   return !(e.target == this);
});
.teste {
    background: yellow;
    padding: 20px;
}
<div class="teste">
    <a href="http://jsfiddle.net">teste</a>
</div>

This works because the handling of click on the links is delegated to a higher level in the hierarchy, the div. The target of the event is the clicked element, but the this is always the element where you "tied" the event (in this case, the div). Therefore, if you click on something other than the div itself, that is, anything within the div, the event is not canceled (return true), otherwise it is canceled (return false).

2


You can capture the event target, if it is a link vc returns true;

$('.teste').on('click', function(e) {
  if($(e.target).is('a')) return true;
  alert('Click');
  return false;
});
.teste {
  height: 200px;
  background-color: gray;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='teste'>
  <div><a href='http://www.google.com'>Link 1</a></div>
  <div><a href='/'>Link 2</a></div>
</div>

  • 1

    Thank you very much!

0

Maybe that’s what you want:

$(".teste, .link").on('click', function() {
     if ($(this).attr('class')=='link') {
        return true;
     } 
  return false;
});

0

$(".teste").find(".link").click(function() {
    return true;
});
  • Add some explanatory content to your response so it can be useful for members with less knowledge in the future.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.