Question

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!

Was it helpful?

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();
    }
  });
});

OTHER TIPS

Simply check that the original target of the event isn't an <a> tag:

$('#parent').click(function(event) {
    if(event.target.tagName !== 'A') {
        event.preventDefault();
    }
});
$('div').on('click', "a", function(e) {
    e.preventDefault();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top