Navigate through the sections by scrolling

Looking for some assistance with implementing a 'scroll to section navigation' on my single page website. I tried using this jsfiddle as a starting point, which worked perfectly. However, when I transferred the code to my website, it doesn't seem to function properly. Here are the key code snippets from my implementation:

<!-- SECTION DEFINITION -->

<section id="about" data-anchor="about">
  <div id="about-wrap">
    <h1>I'm a really cool title about<br>Small Space Living</h1>
    <p>Lorem ipsum dolor sit amet, consectetur ...esse.</p>
    <a class="link" href=""><span>Learn More</span></a>
  </div>
</section>


<!-- NAVIGATION MENU -->

<div class="navbar pull-right">
  <ul class="navi">
    <li><a href="#" data-scroll="about">About Us<hr></a></li>
    <li><a href="#" data-scroll="solutions">Solutions<hr></a></li>
    <li><a href="#" data-scroll="contact">Contact Us<hr></a></li>
  </ul>
</div>


<!-- JQUERY FUNCTIONALITY -->

<script>
$(document).ready(function(){
$(function(){
$('navi a').on('click', function() {

    var scrollAnchor = $(this).attr('data-scroll'),
        scrollPoint  = $('section[data-anchor="'+scrollAnchor+'"]').offset().top -10;

   $('body,html').animate({
       scrollTop: scrollPoint
   }, 500);

   return false;

})

$(window).scroll(function() {

});

$(window).scroll(function() {

    if ($(window).scrollTop() >= 100) {

        $('nav').addClass('fixed');

    } else {

        $('navi').removeClass('fixed');

    }

});
});//]]>  
});
</script>

I have checked the CSS and don't see any style-related issues, especially since the jsfiddle version works without any styling. Any suggestions or help would be greatly appreciated. Thank you!

Answer №1

I recently put together a file containing the following code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>

<script>
window.onload = function() {

$('nav a').on('click', function() {

    var scrollAnchor = $(this).attr('data-scroll'),
        scrollPoint  = $('section[data-anchor="'+scrollAnchor+'"]').offset().top -10;

   $('body,html').animate({
       scrollTop: scrollPoint
   }, 500);

   return false;

})

$(window).scroll(function() {

    if ($(window).scrollTop() >= 100) {

        $('nav').addClass('fixed');

    } else {

        $('navi').removeClass('fixed');

    }
});

}
</script>
<header></header>

<nav>

    <a href="#" data-scroll="top">TOP</a>

    <a href="#" data-scroll="news">NEWS</a>

    <a href="#" data-scroll="products">PRODUCTS</a>

    <a href="#" data-scroll="contact">CONTACT</a>

</nav>



    <section id="top" data-anchor="top">

        <h4>TOP</h4>

            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque feugiat eleifend orci, eget aliquam dolor elementum vel. Aliquam eu nulla eros, et tincidunt felis. Pellentesque congue sodales eleifend. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla suscipit nulla vel nisi fermentum ultricies. Integer ligula elit, gravida ac pretium nec, eleifend ultrices purus. Duis cursus orci et urna accumsan tempor. Nunc mattis tincidunt nulla, id porta velit sollicitudin blandit.</p>

            <p>Duis vel augue quis elit ultrices fermentum ut eu risus. Mauris dictum nisl eget lorem pulvinar sit amet bibendum nunc scelerisque. Suspendisse ac libero magna, at imperdiet leo. Pellentesque vulputate venenatis vestibulum. Aenean varius turpis quis sem adipiscing volutpat. Fusce scelerisque iaculis augue, eget fringilla velit mattis nec. Maecenas sagittis dolor eget felis cursus imperdiet. Morbi ut dui libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet mi ac diam semper hendrerit a...

After saving it as index.html and opening it in a browser, everything worked perfectly.

The main issue you encountered revolved around $('navi a'), which I corrected to '$('nav a')`. It appears to have been a minor typo that caused the problem.

Edit I want to provide further clarification. Avoid using .navi since it refers to the class of an object: . Similarly, refrain from using #navi as it pertains to the id of an object: . To target a tag specifically, utilize $('nav'). This adjustment should resolve any confusion regarding element selection in jQuery.

Answer №2

http://jsfiddle.net/gUWdJ/609/

It seems to be functioning correctly on that site. Could it be possible that there is another JavaScript error causing this script to be blocked?

@UPDATE: I recommend trying out this revised code: make sure you include a period in the class definition!! $('.navi a').

$(document).ready(function(){
$('.navi a').on('click', function() {

var scrollAnchor = $(this).attr('data-scroll'),
    scrollPoint  = $('section[data-anchor="'+scrollAnchor+'"]').offset().top -10;

$('body,html').animate({
   scrollTop: scrollPoint
}, 500);

return false;

});
});

If you prefer not to have any animation effects, you can utilize these simple anchor links:

<nav>

<a href="#top">TOP</a>

<a href="#news">NEWS</a>

<a href="#products">PRODUCTS</a>

<a href="#contact">CONTACT</a>

</nav>

http://jsfiddle.net/gUWdJ/608/

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

Insert PDF to completely fill the screen

Seeking advice on embedding a PDF in an HTML document with a consistent height of 100%. The challenge lies in the varying height of the PDF, and the need for the layout to adapt accordingly. ...

Automatically selecting and fetching checkbox values using JavaScript

I was struggling with coding a function that involved generating checkboxes using JavaScript. My goal is to automatically select the elements "March" and "September" from the array target[] and display them as checked in the text area. So, "March" and "Se ...

Creating a JavaScript function for a custom timed traffic light sequence

Currently, I am facing a challenge with my high school project of creating a timed traffic light sequence using JavaScript for my upcoming exams. Unfortunately, I feel quite lost and unsure about how to proceed. My initial plan involves formatting the valu ...

What is the best way to adjust the vertical distance between a Material UI FormLabel and Slider element?

I am currently developing a map that includes an image overlay with adjustable opacity. Below is the code for this component: import React from 'react' import PropTypes from 'prop-types' import { MapWithGroundOverlay } from './Map ...

IFrame issue: Page is constantly refreshing when on iframe source

Recently, I started working with asp.net and I'm attempting to call an Iframe src within a table row using a JavaScript click event. (i.e onclick="return loadPhaseWiseChart("DGSET00025");") Here is my code snippet: <tr height="25" id="row3" oncli ...

Unable to select checkbox within a table using Selenium WebDriver with Java

Having trouble checking a checkbox inside a table using Selenium Webdriver in Java? Even with version 2.52.0 of Selenium, the element not found error persists across different web browsers. The iFrame seems to be correct as I can interact with other compon ...

Filtering HTML with HtmlAgilityPack using custom queries

I am faced with a block of two HTML elements in this format: <div class="a-row"> <a class="a-size-small a-link-normal a-text-normal" href="/Chemical-Guys-CWS-107-Extreme-Synthetic/dp/B003U4P3U0/ref=sr_1_1_sns?s=automotive&amp;ie=UTF8& ...

Top method for establishing multiple aliases for disabled elements in CSS

Is there a way to have two different disabled states for checkboxes, one with a gray background and the other with a blue background, while maintaining the same functionality? Code within file.css .overall-example input[type=checkbox]:checked + label { ...

Is it possible to target elements based on a specific CSS3 property they use?

Is there a method to target all elements in the DOM with a border-radius other than 0? If anyone has suggestions, it would be greatly appreciated! ...

Accessing a Variable in one JavaScript File from Another JavaScript File

In the process of creating a basic game using only JavaScript and jQuery, I have split it into two separate pages. The first page contains all the rules and necessary information, while the second page is where the actual game takes place. My goal is to in ...

Modifying the innerHTML of SimpleModal and passing a parameter to a function causes an error to occur

I am currently working on a project where I have a collection of photos displayed on the index page. Each photo should trigger a modal that displays a larger version when clicked. However, I encountered an issue while attempting to use jQuery to modify the ...

Phonegap (cordova 1.6.0) integration with Facebook login is experiencing issues on Android

When using Cordova 1.6.0, I am encountering issues with alerts. The Cordova Facebook Connect plugin is failing on login! The Cordova Facebook Connect plugin is also failing on auth.status! Please assist me with resolving these problems. I have been fol ...

The functionality of Small Caps is not supported by Twitter Bootstrap when using Chrome browser

I am working with a very basic markup <h1> <a href="#"> My Title </a> </h1> and I have this CSS applied h1 { font-variant: small-caps; } You can see the result on this jsfiddle link. The problem arises when u ...

How can I dynamically adjust the size of an image in a directory based on its filename with php?

Is it possible to resize a specific image in a folder by its name using PHP? ..................................................................................................................................................................... I have trie ...

How can I use jQuery to internally modify the styling of an IFrame element?

I am facing a situation where I need to dynamically insert an iframe into a parent page (The domain is out of my control) using the following script... var _hf_iFrame = document.createElement("iframe"); _hf_iFrame.setAttribute("id", "_hf_iFrame"); _hf_iFr ...

My custom Material UI table is being hindered by unnecessary div tags that are interfering with my CSS styling

View the generated code The rendered table demonstrates that when scrolling past the maximum width, the data does not appear <div> <table (not going to display all the markup for this. this table contains the headers of each column and appear ...

The jQuery AJAX post request is displaying an error message stating that the website xxx is not permitted by

I encountered a roadblock while attempting to use AJAX to call the eBay FindProducts API with a POST request. The error message that I got stuck on is as follows: XMLHttpRequest cannot load . Origin is not allowed by Access-Control-Allow-Origin. This ...

Inspecting the source page through a red font lens

I noticed that in the view source page, the following lines appear in red: <img alt="4054775 1991 Chevrolet Camaro" class="image" onerror="this.onerror=null;this.src='/images/nophoto_250.gif'"; src="http://carphotos3.cardomain.com/images/00 ...

Connect a word in one QMD file to a word in another QMD file with a hyperlink

As I work on creating a Quarto book, I am looking to link key terms in the book to corresponding definitions in a glossary. The challenge is to ensure that these links function properly in both HTML and PDF formats. Below are some methods I have explored s ...

Executing an event when a hyperlink is clicked using Javascript

I'm in need of some assistance with a specific problem. I have an anchor on a separate HTML page, and all of these pages are connected through one external JS file. Here is the setup: <!-- language: none --> page1.html page2.html js.js In pa ...