Search code examples
jquerysmooth-scrolling

Smooth Scrolling -


I implemented the following code to enable smooth scrolling. The problem is it doesn't seem to allow bookmark links to work when they aren't on the page of the bookmark.

For example, on the following page, the "Post a Job" link/button in the right sidebar doesn't work - clicking the link does nothing - doesn't even open the page.

https://indianashrm.staging.wpengine.com/job-board/graphic-designer/

If the bookmark link is on the page with the bookmark, it works - see "Post a Job link/button in sidebar.

https://indianashrm.staging.wpengine.com/job-board/

Any ideas?

<script>
jQuery(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
  });
});
</script>

Solution

  • The scrolling behavior is set to work only on this location: https://indianashrm.staging.wpengine.com/job-board/#createjobposting

    and #createjobposting form is not in the loaded page (https://indianashrm.staging.wpengine.com/job-board/graphic-designer/), but when you are in /job-board/ it is.

    Don't use this.hash if you plan to use the button scrolling behavior outside of job-board as well, if you are somewhere else it will throw undefined.

    enter image description here

    Considering there is no working fiddle example, the solution could be diverse, but one could be:

    • to place #createjobposting form on /graphic-designer/ and every other job item you have that shows the post a job button (this is recommended if you wish to preserve the scrolling behavior).

    • or to use a full URL link to: https://indianashrm.staging.wpengine.com/job-board/#createjobposting (this would reload to that location if you are somewhere else)