Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger ":target" CSS style with javascript?

Tags:

javascript

css

When you follow an anchor link like <a href="#div">, it will go to the element #div and display the CSS style for ":target", example: #div:target { color: red }. I would like to know how to reproduce this functionality which occurs only when clicking an anchor link (hash).

The whole idea is that I want to custom handle an anchor link so it doesn't trigger the event (on)popstate each time it's clicked. It's very problematic for me that it triggers it.

So if I recode it manually with "scrollIntoView" or the equivalent in Jquery, add its entry to the history (which won't trigger "popstate") then the last thing to code is to trigger the ":target" pseudo-class style.

How to do so?

thank you

like image 267
Barbz_YHOOL Avatar asked Aug 29 '26 05:08

Barbz_YHOOL


1 Answers

Well there's no way to use the :target psuedo-class and change the location without affecting the history,

So something like this should work for you. Basically setting data- attributes on the link pointing to where should be targeted and adding a class for the styling

[...document.querySelectorAll('a')].forEach(a => a.addEventListener('click', _ => {
  const targeted = document.querySelector(`[data-targetted="${a.dataset.target}"]`);

  if (!targeted) return;
  [...document.querySelectorAll('[data-targetted]')].forEach(elem => elem.classList.remove('target'))
  targeted.classList.add('target');
  targeted.scrollIntoView({ behavior: 'smooth' })
}));
div {
  height: 30vh;
}

div.target {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
  font-family: sans-serif;
  color: white;
  background-color: green;
}
<a data-target="link1">Link 1</a>
<a data-target="link2">Link 2</a>
<a data-target="link3">Link 3</a>
<a data-target="link4">Link 4</a>
<a data-target="link5">Link 5</a>

<br/><br/>

<div data-targetted="link1">Link 1 Target</div>
<div data-targetted="link2">Link 2 Target</div>
<div data-targetted="link3">Link 3 Target</div>
<div data-targetted="link4">Link 4 Target</div>
<div data-targetted="link5">Link 5 Target</div>
like image 135
a.mola Avatar answered Aug 31 '26 20:08

a.mola