Navigate to a specific section of the page by scrolling when linked to an id

Just getting started with web development and using Bootstrap to build this site.

I'm working on a single-page site where the top navbar directs users to specific IDs. The issue I'm facing is that I want the page to scroll to the ID when clicked (similar to this example). Additionally, I'd like to apply an 'active' class when the user scrolls past a certain ID.

Not sure where to begin, but here's my HTML code:

<nav class="navbar navbar-default" data-spy="affix" data-offset-top="34">
<div class="container">
<div class="navbar-collapse collapse navbar-responsive-collapse" id="main-menu">
<ul class="nav navbar-nav">
<li class="active"><a href="#whatissm">What We Are</a></li>
<li class=""><a href="#whyusesm">Why Us</a></li>
<li class=""><a href="#whatdoessmeoffer">What We Offer</a></li>
<li class=""><a href="#contactus">Contact Us</a></li>
</ul>
<ul class="nav navbar-nav pull-right">
<li><a href="#">Right Link</a></li>
</ul>
</div>
</div>
</nav>

Answer №1

To create a smooth scroll animation, you can use the function provided below. If you want to add the 'active' class to the previous ID, refer to @ahb's answer. In this function, I have included a variable reduce that deducts 50px from the actual offset.

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
  var reduce = 50;
    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 - reduce
        }, 1000);
        return false;
      }
    }
  });
});

SOURCE

DEMO

Answer №2

When utilizing JQuery:

If you want to scroll and animate to a specific ID, refer to the link here.

To include a class after passing a certain ID while scrolling, this code can be used:

// Storing the window and all content as variables 
// instead of repeatedly fetching them from the DOM during each scroll

var $window = $(window),
    $content = $('.content');

$window.scroll(function () {
    $content.each(function () {
        // For every element with the class 'content'
        // checking its position and adding 'SomeClass' accordingly
        if ($window.scrollTop() >= $(this).position().top) {
            $(this).addClass('SomeClass');
        } else if ($window.scrollTop() <= $(this).position().top) {
            // Removing the class if window position is less than the element's position
            $(this).removeClass('SomeClass');
        }
    });
});

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

Node JS promise predicaments

I'm stuck trying to figure out why this function is returning before my message array gets updated with the necessary values. var calculateDistance = function (message, cLongitude, cLatitude, cSessionID) { return new Promise(function (resolve, re ...

React SlideMenu will not close when a link is clicked

I am facing an issue with my off-canvas menu, which slides in when the variable isOpen is set to true. However, the problem arises when trying to slide it back out upon clicking a Link to navigate to another page. Instead of sliding out, the mobile menu oc ...

Import a new JavaScript file and access a variable

I'm currently working on a school project where I am creating an online platform for purchasing games. The platform is designed using HTML, CSS, and JS, with each game having its own corresponding JS file containing the information. Here is a sample o ...

JQuery's .ajax function often triggers the success callback before the page it is calling

Below is the code I am currently working with: <script type="text/javascript"> $(function(){ $("#AddMaps").submit(function(){ var $form = $('#AddMaps'); $.ajax({ type: 'POST&a ...

Leveraging the power of THREE.js TransformControls

I am currently working on a project in JSBin and attempting to incorporate the THREE TransformControls class. Due to constraints, I am unable to share my full code, but my JavaScript is contained within <script type="text/javascript"></s ...

The copyFileSync function is failing to copy the file without generating any error messages

I have developed a JavaScript function running in a nodejs/Electron client to copy a file from the user's flash drive to c:/Windows/System32. The file is copied to enable manual execution from Command Prompt without changing directories. The issue I ...

Animating HTML elements based on the user's scrolling position

My goal is to add a CSS3 animation to specific HTML elements when the scrollbar reaches a certain position. While exploring various jQuery plugins, I came across interesting options like parallax and harmonic scrolls. The closest match to what I'm lo ...

Searching for related values in a nested array of objects using JavaScript: A guide

My goal for this project is to thoroughly examine the path along with all nested elements within the Items and assign them to the details variable. However, due to the limitations of the function inside the useEffect, I am unable to check nested items eff ...

What is the best way to adjust the position of the left-aligned button on an HTML table so that it

https://i.sstatic.net/DIIsv.png I'm working with HTML code that has tables wrapped around with Divs using Bootstrap. The issue I'm facing is that the "Sold By" Table is not aligned with the rest of the content and I want to move it more towards ...

Calculate the dimensions of each list item and dynamically increase the size of the unordered list with jQuery

Trying to extract the 'width' style attribute from li and assign it to ul. The HTML code looks like this: <div id="carousel_team" class="glide"> <ul class="slides" style="opacity: 1; width: 1464px;"> <li class="slide first active ...

How can you transfer a function to another function within the render return statement?

I am encountering an issue when attempting to pass a function to another function. The initial function successfully downloads JSON data and returns it. However, the subsequent function, which is meant to convert the JSON data to HTML code, is not functio ...

Equal Sized <li> elements within Bootstrap Cards

I've been working with the following "template", and there are multiple cards like this on the settings page I'm currently developing. <!-- Card template --> <div class="card mt-3 shadow-sm"> <div class="card-hea ...

Use an if statement in Angular to conditionally add a title attribute with an empty value to HTML

How can I conditionally add the title attribute to a div without creating another div and using ngIf? If the permission is true, I want to include a title in my div. Here's what my current div looks like: <div (click)="goToChangelog()&quo ...

Is there a directive in AngularJS that allows for binding HTML templates using ng-bind-html

I'm working on a directive that has the ability to use dynamic templates with expressions inside them. The challenge I face is if I use ng-bind-html, the expression won't be evaluated properly. On the other hand, using ng-bin-template results in ...

Ways to adjust your selection to the space or new line before or after

$('button').on('click', function(){ const selection = window.getSelection(); selection?.modify('move', 'backward', 'word'); selection?.modify('extend', 'forward', 'to the next space ...

Using Javascript to prevent css from changing the display

I want to make some CSS adjustments to a single element using a single script, but I want all the changes to be displayed at once. For example: $("#someelement").css({width:"100%"}); //this change should not be displayed $("#someelement").width($("#someel ...

Can you provide an update on the progress of the JavaScript target development in antlr3?

What is the current status of Antlr3's Javascript target? I attempted to generate a parser for a simple grammar, but encountered numerous compiler errors in the generated code. After investigating the website, I downloaded the latest antlr3.5-snapshot ...

The Handsontable popup autocomplete editor is unfortunately truncated by the horizontal scrollbar

I have implemented an autocomplete feature on all columns in my project. However, I am facing an issue where the autocomplete editor gets cut off by the horizontal scrollbar. You can see the problem demonstrated in this jsfiddle link. Here is some code re ...

Viewing information from the database without the need to refresh the page

HTML <textarea>Enter your question here</textarea><button class="askButton">SUBMIT</button> Upon clicking the button, the question is stored in the database using Ajax, jQuery, and Laravel. However, the question only appears after ...

Combine multiple key values from an array of objects into a single array

I have a set of key and value pairs that I need to filter based on whether the values are in an array or not, and then combine them into a single array. const holiday_expenses = { food: [{name: "abc", place: "xyz"}], travel: [{name: ...