Search code examples
javascriptjquery

Prevent click event for wrapper when inner link is click


Here is the example for UI element construct,

HTML

  <div class='wrap'>
          <a class='inner-link' href="#">Link</a>
    </div>

CSS

.wrap
{
  background:#CDD4E0;
  width:300px;
  height:100px;
  padding:20px;
}

.wrap:hover
{
  background:#868B93;
}

jQuery

   $('.wrap').click(function () {
             alert("Handler for wrap container click.");
         });
         
   $('.inner-link').click(function () {
             alert("Handler for inner link click");
         });

What I want to do is to prevent the container with the class .wrap click event when I click the link inside.
You can reference this fiddle example.
Current code fire $('.wrap').click when I do for $('.inner-link').click.


Solution

  • Add if to check if the target does not contain class inner-link.

    UPDATE: Oh, the comment has a better way to solve it.

    $(".wrap").click(function (e) {
      if (e.target.className !== "inner-link") { // add this
        alert("Handler for wrap container click.");
      }
    });
    
    $(".inner-link").click(function (e) {
      e.stopPropagation(); // or add this
      alert("Handler for inner link click");
    });