Animation resetting when clicking anchor point using jquery & js


I have a background animation (some bubbles), and everytime I click a link in the navbar that jumps to an anchor point on the same page, the animation resets. I’m using ruby on rails and jquery, here’s the code:

/* _navbar.html.erb*/

<div class="navbar">

  <div class="logo"></div>
  <div class="navbar-items">
  
    <div class="item">
    
      <a href="#section-one">Home</a>

    </div>

    <div class="item">
    
      <a href="#section-two">About me</a>

    </div>

    <div class="item">
    
      <a href="#section-three">Skills</a>

    </div>

    <div class="item">
    
      <a href="" >Projects</a>

    </div>
  
  </div>

</div>

/* script.js imported into application.js to compile , I copied the code from a post specifying that it prevented the reset but did not work*/

document.addEventListener('DOMContentLoaded', () => {
  $(function() {
    $('a[href=#]').on('click', function() {
      if (location.pathname.replace(/^//,'') == this.pathname.replace(/^//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 1000);
          return false;
        }
      }
    });
  });
})

/* application.html.erb */

<!DOCTYPE html>
<html>
  <head>
    <title>Portfolio</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" integrity="sha512-YWzhKL2whUzgiheMoBFwW8CKV4qpHQAEuvilg9FAn5VJUDwKZZxkJNuGM4XkWuk94WCrrwslk8yWNGmY1EduTA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" integrity="sha512-NhSC1YmyruXifcj/KFRWoC561YpHpc5Jtzgvbuzx5VozKpWvQ+4nXhPdFgmx8xqexRcpAglTj9sIBWINXa8x5w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  </head>

  <body>
    <%=render 'background'%>
    <%=render 'layouts/navbar'%>
    <%= yield %>
  </body>
</html>

Source: CSS – Stack Overflow

November 8, 2021
Category : News
Tags: css | html | javascript | jquery | ruby-on-rails

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.