D
D
Denis_81062021-06-06 19:51:20
JavaScript
Denis_8106, 2021-06-06 19:51:20

How to check URL hash?

There is a multilingual site with two buttons (en/fr)

<div class="lang">
          <a href="#en" id="lang-en">EN</a>
          <a href="#fr" id="lang-fr">FR</a>
        </div>


I want to have a hash in the URL, add styles to the buttons by adding a class. There is this sketch, but it doesn't work:
const langEn = document.querySelector('#lang-en');
const langFr = document.querySelector('#lang-fr');

if (window.location.hash === '#en') {
  langEn.classList.add('active');
  langFr.classList.remove('active');
} else {
  langFr.classList.add('active');
  langEn.classList.remove('active');
}


Help solve the problem. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2021-06-06
@Denis_8106

If such a booze has already gone, isn’t it easier to do something like this?

window.addEventListener("hashchange", (e) => {

  document.querySelectorAll('.lang > a').forEach(el = el.classList.remove('active'));
  
  switch(location.hash) {
    case '#en': document.getElementById('lang-en').classList.add('active'); break;
    case '#fr': document.getElementById('lang-fr').classList.add('active'); break;
    default: break;
  };
  
}, false);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question