Search code examples
javascriptjqueryresponsivesmooth-scrolling

Smooth scrolling nor working when element is dynamically wrapped with anchor


For the mobile devices I want to convert all the h1 headings to anchors that can scroll smoothly to their target. To achieve that, when a certain device resize occurs, i just wrap the content of the h1 tag with an a tag and then unwrap the content of the a tag when the device comes back to desktop width.

$(document).ready(function() {
  // Add smooth scrolling to all links
  $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function() {

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});


//the function to convert the heading to an anchor for devices smaller than 780px
function makeResponsive() {
  if ($(window).width() < 780) {
    if ($('a').length) {
      return true;
    } else {
      $('h1').each(function() {
        $(this).contents().eq(0).wrap('<a href="#section2"></a>');
      });
    }


  } else {
    $('a').contents().unwrap();
  }
}

//run on document load and on window resize
$(document).ready(function() {

  //on load
  makeResponsive()

  //on resize
  $(window).resize(function() {
    makeResponsive();
  });

});
body,
html,
.main {
  height: 100%;
}

section {
  min-height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
  The Heading
</h1>

<div class="main">
  <section></section>
</div>

<div class="main" id="section2">
  <section style="background-color:blue"></section>
</div>

The problem is that when the h1 content is converted to an anchor, the smooth scrolling is not happening at all and the anchor just jumps to the target.


Solution

  • Your a-Tag doesn´t get the click event, because you add the listener when it doesn´t exist.

    Try this

    $(document).on('click', 'a', function(event) {...