Having trouble with Javascript in getting one-page scroll navigation to work?

Hey there, I am working on creating a one-page scroll navigation with some basic javascript to add a smooth animation effect that takes 1 second as it scrolls to the desired section. However, I seem to be experiencing an issue where it's not functioning correctly. Any suggestions or ideas from anyone?

Html


            <ul class="header-nav">
            <li><a id="home" href="#home-View">Home</a></li>
            <li><a id="about" href="#about-View">About</a></li>
            <li><a href="#">Blog</a></li>
            <li><a id="contact" href="#contact-View">Contact</a></li>
        </ul>

Javascript


    $(document).ready(function() {

    // adding click listeners to each anchor tag
    setBindings();

});

function setBindings() {
    $(".header-nav a").click(function(e) {
        // prevent default behavior for anchor tags
        e.preventDefault();
        var sectionID = e.currentTarget.id + "Section";

        $("html body").animate({
            scrollTop: $("#" + sectionID).offset().top
        }, 1000)

        alert("sdf");
    })
}

Answer №1

id that was being targeted in your jQuery script could not be found in the markup, causing it to fail with an error in the console. Try the following revised code:

  $(document).ready(function() {

    // Add a click listener to each <a> tag
    setBindings();

  });

  function setBindings() {
    $(".header-nav a").click(function(e) {
      // Prevent anchor tags from functioning (?)
      e.preventDefault();
      var sectionID = e.currentTarget.id + "-View";
      console.log(sectionID);
      $("html,body").animate({
        scrollTop: $("#" + sectionID).offset().top
      },1000);
      alert("sdf");
    })
  }
body {
  height: 1200px;
}

#home-View {
  margin-top: 50px;
  background: red;
  height: 200px;
}

#about-View {
  margin-top: 50px;
  background: red;
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="header-nav">
  <li><a id="home" href="#home-View">Home</a></li>
  <li><a id="about" href="#about-View">About</a></li>
  <li><a href="#">Blog</a></li>
  <li><a id="contact" href="#contact-View">Contact</a></li>
</ul>
<div id="home-View"></div>
<div id="about-View"></div>

Answer №2

Test out this functional example for navigating to a specific element on the page.

$(document).ready(function() {

    // Add a click listener to each <a> tag
    setBindings();

});

function setBindings() {
    $(".header-nav a").click(function(e) {
       
        // Prevent anchor tags from default behavior (?)
        e.preventDefault();
        var sectionID = e.currentTarget.id + "Section";
        console.log(sectionID);
        $("html body").animate({
            scrollTop: $("#" + sectionID).offset().top
        }, 1000)

        alert("sdf");
    })
}
#homeSection
{
  height:200px;
  background-color:red;
  border:1px solid #DDD;
}

#aboutSection
{
  height:200px;
  background-color:white;
  border:1px solid #DDD;
}

#blogSection
{
  height:200px;
  background-color:blue;
  border:1px solid #DDD;
}

#contactSection
{
  height:200px;
  background-color:#DDD;
  border:1px solid #DDD;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="header-nav">
            <li><a id="home" href="#home-View">Home</a></li>
            <li><a id="about" href="#about-View">About</a></li>
            <li><a id="blog" href="#">Blog</a></li>
            <li><a id="contact" href="#contact-View">Contact</a></li>
        </ul>
        
  
 <div id="homeSection"></div>
 <div id="aboutSection"></div>
 <div id="blogSection"></div>
 <div id="contactSection"></div>

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

Is there a way to move the cards to the next line within a wrapper when the screen size is reached?

My goal is to showcase multiple elements in cards, obtained from my routing system, much like how I'm setting up my sidebar (which is functioning correctly). I have all the titles and icons ready, and the linking works seamlessly. This is where I&apo ...

Ajax fails to transmit data to PHP script

Having encountered an issue with my script that prevents sending data from AJAX to a PHP file, I decided to debug it by logging the form data before running it through the AJAX function. The data obtained was as follows: Form: name=jim&email=info%40te ...

Switching between rows in a table once information has been added to an array | Vue

I'm currently working on creating a table with rows that toggle when a 'View' button is clicked. The table is generated using a for loop for an array. I've successfully implemented the toggling functionality for preloaded data, but enco ...

Compile a list of URLs found within a particular HTML A tag and save them to a text file

In an attempt to extract specific URLs from a webpage, I aim to target only those within a particular HTML A tag. For instance, the targeted URLs are in HTML A tags that contain "Info science": a bunch of HTML before <a rel="external nofollow&quo ...

How come despite installing node 10.1.0, the system is showing the installed version as 5.6.0?

After I downloaded the NPM Windows installer from this link: https://nodejs.org/it/, I made sure to download and install the 10.1.0 version. However, when I checked my console using the command node -v, I was surprised by the following output: C:\U ...

Unable to connect to server using React-Native fetch. Localhost is not being used

I recently encountered an issue with my app where the fetch function used for user authentication stopped working. Despite not making any changes, the transition from React 0.27 to 0.28 seemed to have caused this problem. After scouring through numerous S ...

JavaScript TweenJS is a powerful library that simplifies

Hey there, it's my first time posting on Stackoverflow. I'm facing an issue with a tween in my code. It seems like the brute function is being called at the end, indicating that the tween should be running. However, I'm not seeing any actual ...

Surprising Vercel Production Problem: Functions in Development Environment but Fails in Production Even After Reverting to a Functional Commit

In the development environment, everything runs smoothly without any issues. However, when the application is deployed to production, errors start cropping up. What's puzzling is that even after reverting to a previous commit where the production was ...

Having difficulty launching the sapper app in production mode

Having trouble starting my sapper project in production mode. When running npm run start, the following output appears on the console: niklas@Niklass-iMac project-name % npm run start > [email protected] start /Users/niklas/path/to/project > node _ ...

Top method for handling chained ajax requests with jQuery

I'm facing a scenario where I have to make 5 ajax calls. The second call should only be made once the first call returns a response, the third call after the second completes, and so on for the fourth and fifth calls. There are two approaches that I ...

Understanding the concept of inertia within the OrbitControls feature of ThreeJS

I have implemented THREE.OrbitControls to rotate my objects in a project. Yet, I am interested in incorporating some inertia for the camera rotation so that it gradually comes to a stop after the user stops moving the mouse. What would be the best approa ...

Tips for assigning custom values using CSS and jQuery for a standalone look

I am facing a challenge with my HTML markup: <div> <figure></figure> <figure></figure> <figure></figure> </div> Alongside some CSS styling: div { position: relative; } figure { position: absolu ...

Contrast 2 GET objects retrieved from separate controllers

I have 2 collections of data from different controllers. Data Collection 1 (Controller Name): [{id:1,"name":"jakov"},...] Data Collection 2 (Controller Nickname): [{id:1, "nickname" : "jandric", "nameId" :1, "title" : "master"},...] I send data from C ...

The fixed left div and scrollable right div are experiencing issues with their alignment

I am having an issue with a section where the left div is fixed and the right div is scrollable. However, the content of the right div scrolls even before the scroll top reaches the section. My goal is for the right div to scroll only when it reaches the t ...

Trigger a JavaScript function when a key is pressed down

Hey everyone, I'm trying to figure out how to trigger a JavaScript function when a particular key is pressed. For example, I want the function down() to be executed when the down key is pressed and function left() when the left key is pressed. Is ther ...

Cloning a table row through editing functionality in ReactJS

Hey there, I'm currently working on implementing an edit feature in react.js. The current functionality is such that when the edit button is clicked, it displays the row data in the name and email address fields. If submitted without any changes, it c ...

Having issues with the basic KnockoutJS binding not functioning as expected

There appears to be an issue with my KnockoutJS script that I'm struggling to pinpoint. Below is the snippet of HTML code: <h2>SendMessage</h2> <div class="form-group" id="messageSender"> <label>Select User Type</l ...

What steps should I take to modify this recursive function so that it can verify the property name of an object?

I stumbled upon the code snippet below online, which effectively and recursively eliminates properties from an object if their values are null, undefined, or 0 const removeEmpty = (obj) => { Object.keys(obj).forEach(key => (obj[key] & ...

The resolution of deferred actions is not as successful as foreseen

In my code, I have a method that queries documentdb for a specific document and returns the results to the caller. fetch: function(query) { var fetchDeferred = q.defer(); client.queryDocuments(collectionLink, query).toArray(function(err, docs) { ...

Injecting live data into an input field within a table using Angular 4

Trying to create a dynamic row table with input fields in all cells. The loaded data is static, and I'm facing issues adding more data in the view. However, the functionality to add and delete rows is working fine. I have experimented with ngModel and ...