Home > Software design >  How TO - Add data-attribute to Current Element
How TO - Add data-attribute to Current Element

Time:11-10

How to add an attribute aria-current="page" only to the currently selected element, i.e. to the active class clicked, and remove it from the non-current page?

EX.

$('.nav__link').attr('aria-current', 'page');

$('.nav__link').removeAttr('aria-current');

document.addEventListener('DOMContentLoaded', function() {
const selector = '.nav__link';
const elems = Array.from( document.querySelectorAll( selector ) );
const navigation = document.querySelector( 'nav' );

function makeActive( evt ) {
  const target = evt.target;
  
  if ( !target || !target.matches( selector ) ) {
    return;
  }
  
  elems.forEach( elem => elem.classList.remove( 'active' ) );
    evt.target.classList.add( 'active' );
};

navigation.addEventListener( 'mousedown', makeActive );

} );
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

*::before, *::after {
    box-sizing: border-box;
}

.container {
  width: 100%;
  max-width: 1024px;
  display: block;
  margin: 30px auto;
}

ul {
  list-style: none;
}

a {
  text-decoration: none;
}

.nav {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
}


.nav__item {
  padding: 1rem;
}

.nav__link {
  display: block;
  padding: .3125rem 1.5rem;
  text-transform: uppercase;
}

.nav__link.active  {
  border: 1px solid #ff4b4c;
  color: #ff4b4c;
}
<div >
  <nav>
    <ul >
      <li ><a  href="#" aria-current="page">Current Page</a></li>
      <li ><a  href="#">Page 1</a></li>
      <li ><a  href="#">Page 2</a></li>
      <li ><a  href="#">Page 3</a></li>
    </ul>
  </nav>
</div>

Source: Highlight current page active menu item

CodePudding user response:

These two lines of code:

elems.forEach( elem => elem.classList.remove( 'active' ) );
evt.target.classList.add( 'active' );

Should be changes like this:

elems.forEach( elem => {
  elem.classList.remove('active');
  elem.removeAttribute('aria-current')
});
evt.target.classList.add('active');
evt.target.setAttribute('aria-current', 'page');
  • Related