Smooth scrolling isn't functional when trying to navigate from certain links

I am experiencing an issue with on-page links on my page. There are three links that should smoothly scroll to the anchor link, but only the first one does so. The other two links, which are positioned above the anchored link, first scroll to the top of the page before jumping to the anchor. How can I make all links scroll smoothly without going to the top first?

Below is the code snippet I currently have:

const links = document.querySelectorAll(".cta-btn a");

for (const link of links) {
  link.addEventListener("click", clickHandler);
}

function clickHandler(e) {
  e.preventDefault();
  const href = this.getAttribute("href");
  const offsetTop = document.querySelector(href).offsetTop;
  $("input[id$='input']").focus();
  $(".guitar-service-address>span.placeholder-location").hide();
  scroll({
    top: offsetTop,
    behavior: "smooth"
  });
}

$('#input').on("focus", function() {
  $(".guitar-service-address>span.placeholder-location").hide();
});

$(function() {
  $("span.placeholder-location + input").keyup(function() {
    if ($(this).val().length) {
      $(this).prev('span.placeholder-location').hide();
    } else {
      $(this).prev('span.placeholder-location').show();
    }
  });
  $("span.placeholder-location").click(function() {
    $(this).next().focus();
  });
});

if ($(window).width() < 768) {
  $(".placeholder-above").append($(".placeholder-float").text());
}
.container {
  max-width: 990px;
}

.tab-placeholder {
  display: none;
}

input[id="input"] {
  width: 500px;
}

.guitar-service-address>span.placeholder-location {
  position: absolute;
  margin: 6px 8px;
  color: #686e74;
  cursor: auto;
  font: Helvetica 15px/20px bold;
  font-weight: bold;
  z-index: 1;
}

.guitar-service-address>.placeholder-location>.font-alt {
  color: #686e74;
  font-weight: normal;
}

input {
  padding: 5px;
  font-size: 11pt;
  color: black;
  border: 1px solid #979797;
  border-bottom: 4px solid #000;
}

.help-block {
  font-size: 90%;
}

.test {
  padding: 20px;
}

.section {
  padding: 150px 20px;
}

#head {
  background-color: #ddd;
  padding: 10px 20px;
}

#ckav {
  background-color: #d4d4d4;
}

#cta {
  background-color: #fdfd4d;
}

@media (max-width: 768px) {
  input(id="input") {
    width: 300px;
  }
  span>.placeholder-float {
    display: none;
  }
  .tab-placeholder {
    display: block;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<section class="section" id="head">
  <div class="container">
    <h2>CTA</h2>
    <div>
      Leverage agile frameworks to provide a robust synopsis for high level overviews. Iterative approaches to corporate strategy foster collaborative thinking to further the overall value proposition. Organically grow the holistic world view of disruptive
      innovation via workplace diversity and empowerment.
    </div>
    <div class="cta-btn">
      <a href="#ckav">Check your guitar</a>
    </div>
  </div>
</section>

<section class="section" id="ckav">
  <div class="container test">
    <div class="row">
      <div class="col-sm-12">
        <div class="placeholder-above"></div>
        <div class="guitar-service-address">
          <span class="placeholder-location"><span class="placeholder-float">Find guitar repair specialist. </span><span class="font-alt">Enter your guitar make and model...</span></span>
          <input id="input" type="text" />&nbsp;
        </div>
        <p class="help-block">What is this?</p>

      </div>
    </div>
  </div>
</section>

<section class="section" id="stuff">
  <div class="container">
    <h2>Stuff</h2>
    <div>
      Collaboratively administrate empowered markets via plug-and-play networks. Dynamically procrastinate B2C users after installed base benefits. Dramatically visualize customer directed convergence without revolutionary ROI. Efficiently unleash cross-media
      information without cross-media value.
    </div>
    <div class="cta-btn">
      <a href="#ckav">Check your guitar</a>
    </div>
  </div>
</section>

<section class="section" id="cta">
  <div class="container">
    <h2>CTA</h2>
    <div>
      Leverage agile frameworks to provide a robust synopsis for high level overviews. Iterative approaches to corporate strategy foster collaborative thinking to further the overall value proposition. Organically grow the holistic world view of disruptive
      innovation via workplace diversity and empowerment.
    </div>
    <div class="cta-btn">
      <a href="#ckav">Check your guitar</a>
    </div>
  </div>
</section>

Here's a fiddle: http://jsfiddle.net/Codewalker/6or8pwjx/

Answer №1

Simply include the following CSS code and you won't require any Javascript or Jquery.

* {
  scroll-behavior: smooth;
}

👉 View demonstration on Jsfiddle

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Filtering out undefined elements from an array created by mapping over a nested array using map() and filter()

I'm currently in the process of creating multiple variables to be utilized later on, each one representing a specific array within a set of nested arrays (essentially a data array that will be used for various projects). As I attempt to select the pr ...

What is the best way to incorporate Cross-Origin Resource Sharing (CORS

How do I go about implementing CORS in jQuery? I've been attempting to create a basic page scraper, but keep encountering an Access-Control-Allow-Origin error. Below is the code I've been using: $(document).ready(function(){ $('#start' ...

What is the best way to center a text and a rectangle (containing some text) on a page using Bootstrap?

I'm in the process of creating a webpage using HTML and CSS that needs to look exactly like this image: https://i.sstatic.net/wYKZw.png Currently, I have a version of it on JSFiddle. The issue with the JSFiddle version is that the text and rectangle ...

Failure of event watcher on dynamically updated content

Any help would be greatly appreciated! :) I am currently using JavaScript to dynamically add fields to a document, but I have noticed that the event listener only works on predefined fields. For instance, in the code snippet below, the 'lozfield&apo ...

Best practices for implementing dual ngFor directives within a single tr element?

Click here to view the page The image attached shows the view I want to iterate through two ngFor loops inside the tr tag. When using a div tag inside the tr, it's looping the button next to the tag instead of where I want it in the file table header ...

Select a value automatically by utilizing the ID obtained through an ajax request

I need help figuring out how to programmatically select a value using the ID received through an Ajax call. Despite following the select2 guide and using the code below: $ ('#select2_id').val('1'); $ ('#select2_id').trigger(&a ...

Tips to successfully utilize addEventListener on a submit action

Having issues getting this to work on submit, it functions properly when using document.getElementById("gets").addEventListener("click", b_button); but does not work when I try document.getElementById("gets").addEventListener ...

Why is it that filling a DataTable with a variable doesn't work, but when I input the same value into a PHP site and request it using AJAX, it suddenly works?

Contained within the variable named "test" is the following data: {"data":[{"HistChar_ID":"4","Vorname":"Garnier","Nachname":"de Naplouse"},{"HistChar_ID":"2"," ...

Can you provide me with the appropriate CSS styles to align these tables side by side and ensure they are responsive?

Having recently started learning CSS, I'm unsure about which property to use in order to position the table where I desire. My attempt with the float: right property resulted in the table moving to the bottom right instead. https://i.sstatic.net/BI7 ...

Incorporate animated SVG directly into Vue templates without using any additional enclosures

I need to incorporate dynamic SVG code into my <template> without using v-html or any wrapper around it. The desired end result should look like the following, but template does not support v-html to achieve this. If there is a way to accomplish thi ...

Exploring the spinning globe using ThreeJS

Is there a way to rotate an object in three-dimensional space using THREEJs? I've been trying the code below but it doesn't seem to work. Can anyone spot what I might be doing incorrectly? object.matrixAutoUpdate = false; const matrix = object ...

Troubleshooting: Custom JQuery function not functioning as expected

I am currently facing an issue with the jQuery in my website while trying to implement a portfolio element. It seems to be related to the changePortfolio() function, but I am unsure of how to resolve it. $('.projects a[href^="#"]').on('clic ...

Guide on extracting the selected radio button value from one page and showing it on another using HTML and PHP

I am working on a form where members enter their details. When I click submit, all values are stored in the database. However, when I click edit, it retrieves all values except for the radio button value. Is there a way to fetch the radio button value wh ...

What could be causing the data-price values of my alternative select options to not add up correctly when running this function?

ISSUE I am facing a challenge in calculating the total values of select inputs based on the radio button selected initially. Each radio button corresponds to different select inputs with their own data-price values. Once a radio button is chosen, the div ...

Preserve aspect ratio when applying a texture map to a threejs object

I have a project idea to develop a 3D shoe design tool that allows users to create patterns and apply them to the shoes. I am facing an issue with adding an image to a Three.js material. The texture appears blurry after updating it. As a beginner in Three ...

Can you explain the type of the Fat Arrow function or Callback?

Here's a simple question. Coming from a Qt/C++ background, I value explicitness as good practice: protected sanityCheck() : void { ... } // Clear and Type-Safe protected sanityCheck() { ... } // Risky and Insecure Now, how can I achieve the s ...

Why is the React Util js file not functioning properly when using an absolute path?

Help needed! I'm utilizing create-react-app without ejecting. I can't seem to figure out why this code snippet is not functioning correctly. import { capitalizeFirst } from 'util/util.js'; //This line is causing issues import AdminIn ...

Despite successfully connecting to my webservice, the ajax function encounters an error

<script type='text/javascript'> $(document).ready(function () { $("#submit").click(function (e) { e.preventDefault(); var userName = $("#username").val(); var pwd = $("#password").val(); authenticate(use ...

The response from an AJAX request is consistently negative

Currently, I am working on a basic PHP form that involves some AJAX functionality. Despite my efforts to troubleshoot the issue on my own, I have been unable to identify the missing component. The problem persists as all results return false, and no recor ...

The arrow lambda callback function in JavaScript's Array Every method is returning undefined when passing an argument

Utilizing the JavaScript Array Every method for validation, I encountered an issue when passing arguments with a specific condition while using the JavaScript arrow lambda callbackFn. To illustrate the problem, let's consider a simple example. The s ...