-1
 const preventReloadLinks = container.querySelectorAll('.leftnav-link');
  preventReloadLinks.forEach(link => {
   addEventListener('click', function (e) {
     e.preventDefault()
    });
   })

Hi Everyone I'm using this piece of code to stop links in the nav causing page reload, it works but unfortunately it stoped (prevented) from click other links on my page to external pages which I want them to work.I tried more specific selector but it the same. How can I stop this behavior or reverse it for the other links. thanks

3 Answers3

0

Your code adds an eventListener to the window for each link in nav.

addEventListener('click', function (e) { // same as window.addEventListener
   e.preventDefault()
});

So you missed link. and the code should be

link.addEventListener('click', function (e) {
   e.preventDefault()
});

But I suggest instead to delegate, then you do not have to loop

container.addEventListener('click', function (e) {
  const tgt = e.target.closest("a"); // or just e.target if there are no child elements in the link 
  if (tgt && tgt.classList.contains("leftnav-link")) { 
     e.preventDefault()
  }   
})
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • thank you very much the missed link. sorted everything preventReloadLinks.forEach(link => { link.addEventListener('click', function (e) { e.preventDefault() }); – Norbert Perka Apr 30 '21 at 16:24
0

const preventReloadLinks = document.querySelectorAll('.leftnav-link');
for (let i = 0; i < preventReloadLinks.length; i++) {
    preventReloadLinks[i].onclick = () => false;
}
Arnab Ghosh
  • 333
  • 1
  • 2
  • 10
  • 1
    No need to change the forEach to a for loop. The mistake was to keep adding eventlistener to window as [I have detailed](https://stackoverflow.com/a/67333534/295783) – mplungjan Apr 30 '21 at 12:15
-1

Add another custom class to the links which are created by you which must be absent in foreign links.

Then modify the querySelector() for custom class

Sudarshan
  • 702
  • 6
  • 24