pipo92
pipo92

Reputation: 159

hash for auto generated ids not working on page load

in a current project i have different articles containing different headings (<h3>). Because the articles are composed in a CMS we cannot set the id of the <h3> element from the beginning on. Thats why I'm setting them on page load:

$(document).ready(function(){
  
  let articleContent = $(".article-body")
  let headings = articleContent.find("h3")

  headings.each(function() {
    $(this).attr("id", $(this).first().text().replace(/\s/g, "-"))
  }
}

The problem is, when I try top open the URL with the given id of the heading as its hash to navigate the user to the right heading (eg. https://test.com/article-122321#heading2), this is not working. I guess this is the case because on page load the headings do not have any ids set and the browser doesn't know where to navigate to.

Can you help out with a solution for that? Do I have to set the ids at another point of time or do I need some custom Javascript code to tell the browser to navigate to the heading?

Thanks!

Upvotes: 0

Views: 300

Answers (1)

mplungjan
mplungjan

Reputation: 178094

Have a try of this

$(document).ready(function() {
  $(".article-body h3").each(function() {
    $(this).attr("id", $(this).first().text().replace(/\s/g, "-"))
  })
  const hash = location.hash;
  const $element = hash ? $(hash) || null; // assuming a valid selector in the hash
  if ($element) $element[0].scrollIntoView({ // use the DOM method
    behavior: "smooth", // or "auto" or "instant"
    block: "start" // or "end"
  });
});

Upvotes: 1

Related Questions