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

Transform an asynchronous callback into an asynchronous generator format

I have the following function from a third-party package that I am unable to modify async function runTransaction(callback) { const client = await createClient(); try { await client.query("BEGIN"); await callback(client); } ...

retrieving data from Redis with the help of Node.js

I'm having trouble with the code snippet below. Despite setting values for the left_label and right_label variables in Redis, they always seem to return as "true". I suspect this is due to the client.get function returning true when successful. How ca ...

Employ a separate function to extract HTML content from a jQuery target in an AJAX response

Initially, the HTML div is empty upon loading the page. However, clicking a button triggers jQuery AJAX to load new HTML content into the div. $("#control-list a#ms").click(function(){ var postData = "actionrequest=ms"; $.ajax({url:"SSSutility.php ...

Adjusting table font dynamically using Angular and CSS

I am currently working on an Angular project and facing a challenge with setting the font size dynamically in a table. I have created a function to address this issue, which includes the following code snippet: $('.td').css({ 'font-size ...

Using Angular's ng-repeat alongside a bootstrap input checkbox, make sure to incorporate a dynamic ng-model and utilize ng-

This particular issue is proving to be a bit challenging for me to articulate, but I'll give it my best shot. I'm currently working on implementing Angular checkboxes with their ng-true-value attribute in conjunction with a dynamic ng-model. < ...

Guide on sending two values from a form using Ajax and the POST method

How can I send two values, A and B, from a form to check.php using Ajax with the POST method? In the code snippet below, I managed to send two input values to check.php and assign them to variables $A and $B. However, I want to accomplish this without ref ...

A error was encountered stating that the formValidation function is not defined when the HTML form element is submitted

Having trouble calling a function and receiving an error message. How can I resolve this issue? The error message reads: index.html?email=&gebruikersnaam=&wachtwoord=&submit=Submit:1 Uncaught ReferenceError: formValidation is not defined at HT ...

Express.js POST Request Not Being Accepted | 404 Error Detected

I am encountering difficulties implementing PayPal on my website. Whenever I attempt a post request, including using Postman, I receive a standard 404 error page instead of the expected response. The console shows no errors, leading me to believe that the ...

Unable to obtain return value in AngularJS controller or view

I have been working on a geolocation and reverse geocoding application. I have a function that is triggered by a button click to call a function in my controller which then calls my service. While the service is able to retrieve values, I am unable to get ...

How to assign a global variable in Angular 2 from within a promise

I have encountered a strange issue while trying to assign a response to a global variable inside an observable. Here's the logic of my program: Fetch the latest playlists IDs from elastic search (using a type definition file for elastic search). T ...

Fixing Function for Internet Explorer versions 6-8

I have been experimenting with a small function that works perfectly in most browsers. However, I am facing an issue in IE6 to 8 where the tags are behaving strangely. For example, if you click on Bold once, it displays <b></b>. But if you clic ...

Accordion-style elements arranged in a grid format, smoothly displacing surrounding content

I am facing an issue with a grid of accordions, as demonstrated in the codesandbox linked below. The problem arises when I open one accordion, causing all the accordions in the row below to shift down. Ideally, only the accordion directly below should be p ...

Javascript tabs with clickable links

I have created a page with a series of thumbnails that reveal content below when clicked. The content is positioned absolutely and set to display:none, with javascript changing this for each thumbnail. (I am not very familiar with javascript and learned t ...

Implementing efficient loading and dynamic updates in web applications with Angular.js and php through

Currently, I am working on a project that requires lazy loading of images. However, a new requirement has come up which involves a server batch process pulling images from a database at regular intervals. These images must then be appended to the photos ...

Creating multiple nested ng-repeats in an AngularJS table

Managing a large amount of data on users' availability by hour for multiple days can be challenging. The data is structured as follows: availData = { "date1":arrayOfUsers, "date2":arrayOfUsers, ... } arrayOfUsers= [ userArray, userArray, ... ] user ...

Convert HTML Form to PDF or Docx with Angular 4

My current setup involves Angular 4 with Node and MySQL. I have a form that, upon submission, needs to trigger a Save As... dialog box for the user to save the entered form contents as either a PDF or Word Doc. I've attempted using htmlDox and saveAs ...

Guide to encapsulating a container within a map function using a condition in JSX and TypeScript

Currently, I am working with an array of objects that are being processed by a .map() function. Within this process, I have a specific condition in mind - if the index of the object is greater than 1, it should be enclosed within a div element with a parti ...

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

Is there a way to customize the color of the HR element in a Material-UI Select Field?

https://i.stack.imgur.com/DYeX7.png https://i.stack.imgur.com/CN0T6.png Hi there, I am currently working on a website and using a Select Field component from Material-UI. I am faced with the challenge of customizing the style to change the default light ...

What is the best way to handle this unconventional JSON structure?

Looking for some insight on retrieving process information from a VPS with PM2. However, the JSON string returned by PM2 is malformed, making it impossible to run JSON.parse(). An example of the output provided by PM2: '{data: 0, informations: " ...