Reputation: 23
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!
Upvotes: 2
Views: 115
Reputation: 896
$('div').on('click', "a", function(e) {
e.preventDefault();
});
Upvotes: 0
Reputation: 38345
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();
}
});
Upvotes: 1
Reputation: 94459
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();
}
});
});
Upvotes: 2