Search code examples
javascripthyperlinkpreventdefault

I cannot figure out how to exculde links from preventdefault


I want to exclude links inside a child-div from preventDefault

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("#parent").click(function(event){
    event.preventDefault();
  });
});
</script>
</head>
<body>
<div id="parent">
<div id="child"><a href="mylink.html" alt="link">click me!</a></div>
</div>
</body>

Is it possible to get the link in the child div working? I have spent about 3 hours looking for the answer right now, and I can't seem to figure it out!


Solution

  • Check that the target that triggered the event is not the anchor. If it is not do not propagate the event.

    $(document).ready(function(){
      $("#parent").click(function(event){
        if(!$(event.target).is("a")){
            event.preventDefault();
        }
      });
    });