Search code examples
javascripteventssettimeoutpreventdefault

Remove preventDefault() On A Click Event After 2 Seconds


I have a preventDefault() method on some links that I would like to remove after 2 seconds.

I'm trying to both work out how to remove the preventDefault() - which stops the links from working, but also how to do it so it happens after 2 seconds.

I thought I could do it by removing the 'link' class the initial forEach loop happens on, but alas this doesn't work.

Does anyone know how to solve this problem?

CodePen: https://codepen.io/emilychews/pen/VwPJNGE

var link = document.querySelectorAll(".link");

// prevent default on all specific links
link.forEach(function (item) {
  item.addEventListener("click", function (e) {
    e.preventDefault();
  });
});

// remove prevent Default
function allowLinks() {
  link.forEach(function (item) {
    item.classList.remove("link");
  });
}

setTimeout(function() {
  allowLinks();
}, 2000);
body {
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100vh;
}
<a target="_blank" href="https://google.com" class="link">Make me work after 2 seconds</a>


Solution

  • Removing the link class won't accomplish your goal because the event listener is associated with the DOM element, not the class. In other words, the class name is the means by which you accessed the DOM elements but the class itself holds no association with the event listener.

    One option is to remove the event listener itself after two seconds. You can do this by defining the event listener function in a higher scope and the using the removeEventListener method.

    var link = document.querySelectorAll(".link");
    
    const listener = function (e) {
      e.preventDefault();
    };
    
    // prevent default on all specific links
    link.forEach(function (item) {
     item.addEventListener("click", listener);
    });
    
    // remove prevent Default
    function allowLinks() {
      link.forEach(function (item) {
        item.removeEventListener("click", listener);
      });
    }
    
    setTimeout(() => {
      console.log("links allowed!");
      allowLinks();
    }, 2000);
    body {
      margin: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100vh;
    }
    <a href="https://google.com" class="link">Make me work after 2 seconds</a>