Home > OS >  jQuery - addClasss to div depending on URL hash on page load
jQuery - addClasss to div depending on URL hash on page load

Time:02-03

I have a page with team members and I need to add class to section based on the current hash in URL. The reason is to enable linking to specific team member as they don't have separate pages.

So when somebody enters URL https://www.mypage/members#anchorX the open class will be added to the element right after div with anchorX ID.

$(window).on('hashchange', function(e) {
  e.preventDefault();
  let hash = window.location.hash.substr(1);
  $('div[id^="'   hash   '"]').next().addClass('open');
});
.open {
  color: red;
  opacity: 1
}
<a href="#anchorX">Bla</a>
<a href="#anchorY">Bli</a>
<a href="#anchorZ">Blu</a>

<div id="anchorX">Anchor 1</div>
<div>this should be red 1</div>
<div id="anchorY">Anchor 2</div>
<div>this should be red 2</div>
<div id="anchorZ">Anchor 3</div>
<div>this should be red 3</div>

The JS code above works fine but ONLY when the hash changes - so when somebody already is on the page https://www.mypage/members and then will go to the https://www.mypage/members#anchorX it works.

But I need that to be working mainly when somebody gets an URL with hash and going directly to https://www.mypage/members#anchorX. But in this situation nothing happens. As I understand it is because there is no 'hash change' in the second situation, but how can I make it work? Different window event? Or trigger some kind of reload?

https://jsfiddle.net/beatajak/de18hwxf/9/ - the code above

CodePudding user response:

Just call it on load, and no need for preventDEfault

const changeColor = (e) => {
  let hash = window.location.hash;
  if (hash.length > 1) $(hash).next().addClass('open');
};
$(function() {
  $(window).on('hashchange', changeColor);
  changeColor()
})
  • Related