Home > other >  Dynamically Loaded Anchors Not Working On Page Load
Dynamically Loaded Anchors Not Working On Page Load

Time:08-16

I am generating anchors dynamically for each <h3> on page load, but when linking to another page the anchor doesn't scroll to the destination. I am pretty sure this is because the anchors don't exist yet. How can I either look at the URL and trigger the scroll after the page is ready or generate the anchors sooner?

jQuery:

//Add anchors with name for each h3 
jQuery(document).ready(function($) {
  $('h3').each(function() {
    let text = $(this).text();
    $(this).before("<a name='"   text   "'></a>");
  });
});

URL structure: https://sample.com/page/#anchor

CodePudding user response:

This is what I did. In case anyone else finds it helpful.

//Add anchors with name for each h3 
jQuery(document).ready(function($) {
  $('h3').each(function() {
    let text = $(this).text();
    $(this).before("<a name='"   text   "'></a>");
  });

  let anchor = window.location.hash.replace("#", "");

  $('html, body').animate({ 
    scrollTop: $(".content [name='"   anchor   "']").offset().top - 32
  }, 1000);  
});
  • Related