Search code examples
javascriptjquerywordpressscrollsmooth-scrolling

Smooth Scrolling Stopped Working - What Am I Doing Wrong?


I had implemented the CSS-Tricks Smooth Scrolling snippet on my homepage and it was working wonderfully UNTIL I decided to rebuild my homepage. Now it's not working at all.

Here's a bit of history on what I did. I'm trying to build a single-page scrolling website. Originally, I created a page in Wordpress and inserted 3 divs called 'about,' 'work,' and 'contact.' I implemented the Smooth Scrolling snippet, and everything was working nicely. However, then I decided to do some more research during which discovered the magic of Wordpress custom post types. I decided to rebuild my homepage with a custom template (page-include.php) that uses WP_query to include 3 different pages. Two of the pages ('about' and 'contact') are actual Wordpress pages, but the third ('work') is just a custom loop pulling my custom post type. Long story short, when I went to Settings > Reading and changed the homepage to direct to the new page, the smooth scrolling stopped working. When you click on the links in the nav bar, the page jumps to the appropriate spot, but it doesn't scroll at all. If I change set the homepage back to the old version, the scrolling still works fine. Any ideas on why it stopped working?

If it helps, here's my site. Also, if you're wondering, my theme is based on Roots.


Solution

  • There's an error occuring on JavaScript execution, that's why the script quits, and therefore no smooth-scrolling gets applied.

    I've seen, that your script in plugins.js walks all the links with a hash (#) at the start of href. Unfortunately you have a link in your nav bar, that is like this: <a href="#anchor3">Anchor 3</a>

    Now you don't have a section like <div id="#anchor3"> in your website, that's the reason your script throws an error.

    The problem is this line of code in your plugins.js, circa line 30:

    var targetOffset = $target.offset().top;
    

    $target is empty, try alert($target.length) or console.log($target.length) to get the proof. Now to fix this, change this line:

    if (target) {
    

    to this:

    if (target && $target.length) {
    

    Now before calling .offset() your script will check if there are any elements in your jQuery selection. If $target is empty, it won't fire, scripts will continue to work.