Navigate through pages using scrollspy without losing your position when returning

Hey all you web geeks out there, I could really use your help solving a little issue.

I've been working with Bootstrap to build a website that utilizes scrollspy for navigating different sections of the page using the navbar. The only way I could stop the URL from showing "#section-2" when scrolling was by calling my JavaScript in the <head>.

Here's the problem...

I tried adding an FAQ section as its own separate page, and wanted it to link back to specific parts of the original page.

It seems like the FAQ <a> tag doesn't work unless the browser is resized...

Two bugs already with scrollspy! Is it common for Bootstrap to have this many issues?

Check out the code below:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>
        Day &amp; Night | Responsive Web Design
    </title>
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
    <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">


    <meta name="viewport" content="initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">

    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js">
    </script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js">
    </script>
</head>

 ...

</body>

</html>

Answer №1

If you have a jQuery function in place that automatically scrolls to each menu link section, but you want to exclude the FAQ link and redirect when it is clicked, you can modify the script like this:

//trim the spaces and check if the text of the menu link is not equal to 'FAQ'
if ($.trim($(this).html()) != 'FAQ') {
    $($(this).attr('href'))[0].scrollIntoView();
    scrollBy(0, -offset);
} else {
    //if it is, redirect to the page
    window.location.href = $(this).attr('href');
}

View Full Screen (jsfiddle)

Edit:

Regarding a comment about linking back causing an issue with scrollspy, you can make adjustments by following these steps:

when trying to link back I am using ""; which is throwing off the scrollspy by adding #section-2 to the url.

To address this challenge, you need to remove the existing function

$('.navbar li a').click(function(event) {
entirely and replace it with the provided code snippet:

$("document").ready(function() {
      $(document).on('click','.navbar li a',function(event) {
          alert($(this).html());
        event.preventDefault();
        if($.trim($(this).html())!='FAQ'){
            $($(this).attr('href'))[0].scrollIntoView();
            scrollBy(0, -offset);
          }
          else
          {
              window.location.href = $(this).attr('href');
          }

      });

   // Additional logic here to handle redirection from FAQs page
  
});

In order for this solution to work properly, ensure that each <a> tag has a unique id attribute assigned, like so:

<a href="#section-1" id="a-section-1">
<a href="#section-2" id="a-section-2">

Finally, you can see a demonstration of how the trigger functionality functions here: demo

Answer №2

Assign an identifier to the initial div such as dynaDiv and update

<a href="/faq"> FAQ </a>
to
<a href="/faq" onclick='addFAQ();'> FAQ </a>
. Create a function as follows:

function addFAQ(){
  $("#dynaDiv").load("./faq.html");
}

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

Fix the Bootstrap navbar that is obstructing the link to content on the page

Currently, I am implementing Bootstrap 4, with a fixed-top navbar at the top of the screen. Everything works perfectly fine, except for one issue when linking to elements on the same page. When I target an element further down the page from one of the nav ...

Float: A threshold reached when adding 1 no longer has any effect

In the realm of programming, float serves as an estimation of a numeric value. For example, 12345678901234567890 === 12345678901234567891 evaluates to true However, 1234567890 === 1234567891 yields false Where does the equation num === num+1 reach a br ...

Enhancing performance by implementing cache mechanism for storing search results in a table with multiple filtering options using Vue

In my current project, I am utilizing VueJS. However, the issue I am facing is not necessarily exclusive to this framework - but if there is a vue-specific solution available, that would be my preference. The task at hand involves constructing a table wit ...

Leveraging the power of jQuery's $.when and $.then methods for efficiently managing multiple AJAX requests that do not

My goal is to utilize jQuery to retrieve data from both an XML and JSON feed, and then only log the data when both requests are successful. When I comment out getRoomFeed() within the $.when, it returns the correct responseText object for the XML. However ...

Using ReactJS to return a component from a function

Working with React, useState, and React-Icons. I am trying to implement a dropdown menu without using Bootstrap. My goal is to change the icon upon clicking to trigger a function, but currently, it only displays the raw SVG details. Any suggestions on how ...

Have you ever wondered why MEAN.js applications use the #! symbol at the start of their URLs

Embarking on my first MEAN application build using MEAN.JS, I was intrigued by the structure of how mean.js organizes the application, particularly why URLs begin with /#!/. For instance, for the login page, I envisioned: http://example.com/login instea ...

Activate dropdown to trigger a function that fetches dates and disables them in the datetimepicker

I have a dropdown menu containing staff names and StaffId. These are linked to an appointment business logic. I am attempting to activate a select change event where dates stored in the database will be marked as unavailable in the connected jQuery datet ...

React Bootstrap encountered rendering issues

Recently, I decided to delve into the world of React Bootstrap and started my learning journey. To get started, I followed some tutorials on <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <meta name="vi ...

Creating real-time chat using Node.js

I am looking to create a live chat feature using node js. Can someone provide guidance on how to achieve this? Here are the use cases I have determined: Users will have the option to click on a link or icon labeled 'Online chat support' on the ...

Transforming .POST into corresponding .AJAX techniques

I'm currently attempting to convert a .post javascript call into an equivalent .ajax call in order to make it asynchronous. However, I'm running into some issues and can't seem to get it to work. The original working .post call looks like th ...

Error encountered when using prisma findUnique with where clause

Trying to set up a Singup API using ExpressJS and Prisma is proving to be a bit challenging. The issue arises when I attempt to verify if a given email already exists in my database. Upon passing the email and password, an error is thrown stating Unknown ...

Issues with Angular functionality

I'm a newcomer to Angular and I am trying to recreate this example from jsfiddle in order to experiment with nodes. However, I am encountering issues with the Angular setup. Firstly, the jsfiddle is causing confusion because the application names do n ...

Show a multipage report of a MySQL database

I have a MySQL database with some information that I would like to make accessible to everyone, with an option to edit. <?php $username = "VKSolutions"; $password = "VKSolutions@1"; $hostname = "VKSolutions.hostedresource.com"; $database = "VKSolut ...

Client-Side Isomorphic JS: A Guide to Using HTTP Requests

Seeking advice on data population for isomorphic flux apps. (Using react, alt, iso, and node but principles are transferable) In my flux 'store' (), I need to fetch data from an api: getState() { return { data : makeHttpRequest(url) ...

There seems to be a problem with completing the Axios post request in the Javascript Front

My front-end, built with React, is having trouble retrieving data from a third-party API through my Node.js backend. Despite using axios.post request, the response remains undefined and I'm stuck at handling the asynchronous request. It appears that t ...

The functionality of the Bootstrap carousel may be compromised when initialized through JavaScript

Why isn't the Bootstrap carousel working in the example below? It starts working when I paste it into .content <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script sr ...

Webpack in Vuejs does not have access to the keys defined in dev.env.js file

The framework utilized here is vuejs-webpack, with build and config files located here. No modifications have been made to these files. According to the information on Environment Variables, the keys specified in dev.env.js should be accessible during the ...

Revealing Transition Element on mouseover

My side-menu consists of icons that display text to the right upon hovering over them. I want the text to show up and the div to expand smoothly with a sliding transition, ideally without the need for additional JavaScript. Is there a way to achieve this? ...

Exploring the functionality of the onblur HTML attribute in conjunction with JavaScript's ability to trigger a

How do the HTML attribute onblur and jQuery event .trigger("blur") interact? Will both events be executed, with JavaScript this.trigger("blur") triggering first before the HTML attribute onblur, or will only one event fire? I am using ...

Obtain details regarding a worker's collision

This code snippet is being used to manage cluster crashes within a node application cluster.on('exit', function (worker, code, signal) { console.log("error in cluster",worker); console.log("cluster code",code); console.l ...