Search code examples
javascripthtmlhyperlinkpreventdefaultdom-manipulation

How to stop default behaviour of all the links in the entire webpage?


I am creating project which allows users to remove elements from any webpage. The way this work in my project is that it first creates an overlay which allow user to select the elements they want to remove. Once they have selected all the elements they click on the remove button to delete those elements from webpage. Overlay has style pointer-events: none so that user can select the elements on the web page. Here is jsFiddle preview of code.

This work perfectly fine unless a user clicks on a link which create any issues as now the user redirected to a new site. I want all the link to stop working for some time as long as there is overlay to select items for deletion.

I have tried using following code but this doesn't stop the redirection

 document.querySelectorAll('a').forEach(Element => {
     (Element as HTMLElement).removeEventListener('click', removeDefaultBehaviour)
   })

 const removeDefaultBehaviour= (e:MouseEvent) => {
   e.preventDefault();
 }

I am looking for any workaround to make it work.


Solution

  • you can add

    a {
      pointer-events: none
    }
    

    to your CSS file.