Removing the :target psuedo-class

I was working on a page with a link to a document fragment and put an animation on it using the :target pseudo-class. Scrolling back to the anchor and pressing it again skips to the fragment, but the animation does not run again. That’s because it still has the pseudo-class, it doesn’t disappear when scrolling.

To get round this I cloned the node then replaced it with the clone, like so:

const element = document.querySelector(':target');
const elementClone = element.cloneNode(true);
element.replaceWith(elementClone);

I put it inside a function, and called the function from inside the setTimeout global function so the pseudo-class didn’t get removed before the animation could run.

const anchor = document.querySelector('.anchor');

function removePseudoClass(pseudoClass) {
  const element = document.querySelector(pseudoClass);
  const elementClone = element.cloneNode(true);
  element.replaceWith(elementClone);
}

anchor.addEventListener('click', () => {
  setTimeout(removePseudoClass(':target'), 1450); // The animation runs for 1250 but adding a wee buffer for jank
});

Tags