Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.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");
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading