Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript, Stop preventDefault() to pass to child element

I have a div container, where for some reason I have to add e.preventDefault(), but surprisingly it stops the anchor elements to do their job as well

jQuery('#anything').on("click", function(e) {
  e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="anything">
  <a href="https://google.com"> Link should work </a>
</div>

I didn't expect that anchor won't work, I never had to deal with this before. I tried StopPropagation() as suggested somewhere, But that didn't work

How can I make the anchor working again?

like image 924
nikhil123 Avatar asked Dec 18 '22 21:12

nikhil123


1 Answers

One option would be to use event delegation and exclude all as from triggering the listener:

jQuery('#anything').on("click", '*:not(a)', function(e) {
  e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="anything">
  <a href="https://google.com"> Link should work </a>
</div>

Or if you want to make sure that no clicks inside children of #anything trigger the listener, put #anything as the delegation selector instead. In native Javascript this time:

document.querySelector('#anything').addEventListener('click', (e) => {
  console.log('listener running');
  if (!e.target.matches('#anything')) return;
  console.log('prevented default');
  e.preventDefault();
});
  
<a href="www.google.com" id="anything">Parent A<span>Child Span</span></a>

(though, preventDefault() on just a div doesn't much sense..?)

like image 112
CertainPerformance Avatar answered Dec 28 '22 09:12

CertainPerformance