What methods can I use to identify my current page location and update it on my navigation bar accordingly?

My latest project involves a fixed sidebar navigation with 3 divs designed to resemble dots, each corresponding to a different section of my webpage. These sections are set to occupy the full height of the viewport. Now, I'm facing the challenge of determining the scroll position on the page and identifying which section is currently in view.

Leveraging Vue.js for this task will certainly simplify the process once I crack the code.

To achieve this, it seems that I might need to utilize window.scrollY, OffsetTop, as well as the height property of each section to ascertain whether the current window.scrollY falls within the range of a section's OffsetTop (its starting position) and OffsetTop + height (its ending point). Is my approach correct so far?

This is where I stand at the moment:

*, *:after, *:before {
        margin: 0;
        padding: 0;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        text-decoration: none;
        list-style-type: none;
        color: rgba(0, 0, 0, 0.8);
    }
    body {
        background-color: #f1f1f1;
        font-family: 'Roboto', 'Helvetica', 'Helvetica Neue', 'Arial', sans-serif;
        background-image: url("./assets/svg/topography.svg");
        background-attachment: fixed;
    }
    section {
        min-height: 100vh;
    }
    .navigation {
        display: flex;
        flex-direction: column;
        position: fixed;
        right: 5%;
        top: 50%;
        transform: translateY(-50%);
        text-align: right;
    }
    .navigation div {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        margin-bottom: 30px;
        transition: all .1s linear;
        border: 5px solid rgba(0, 0, 0, 0.5);
        cursor: pointer;
    }
    .navigation div:hover {
        transform: scale(1.2)
    }
    .one {
    background-color: red;
    }
    .two {
    background-color: blue;
    }
    .three {
    background-color: green;
    }
<nav class='navigation'>
    <div></div>
    <div></div>
    <div></div>
</nav>
<section class='one'></section>
<section class='two'></section>
<section class='three'></section>

Answer №1

We attempted to use Emacs to navigate between sections on the page.

*, *:after, *:before {
        margin: 0;
        padding: 0;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        text-decoration: none;
        list-style-type: none;
        color: rgba(0, 0, 0, 0.8);
    }
    body {
        background-color: #f1f1f1;
        font-family: 'Roboto', 'Helvetica', 'Helvetica Neue', 'Arial', sans-serif;
        background-image: url("./assets/svg/topography.svg");
        background-attachment: fixed;
    }
    section {
        min-height: 100vh;
    }
    .navigation {
        display: flex;
        flex-direction: column;
        position: fixed;
        right: 5%;
        top: 50%;
        transform: translateY(-50%);
        text-align: right;
    }
    .navigation div {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        margin-bottom: 30px;
        transition: all .1s linear;
        border: 5px solid rgba(0, 0, 0, 0.5);
        cursor: pointer;
    }
    .navigation div:hover {
        transform: scale(1.2)
    }
    .one {
    background-color: red;
    }
    .two {
    background-color: blue;
    }
    .three {
    background-color: green;
    }
<nav class='navigation'>
    <div></div>
    <div></div>
    <div></div>
</nav>
<section class='one'></section>
<a name='one'></a>
<section class='two'></section>
<section class='three'></section>
<a href='#one'> go to section one </a>

Answer №2

The solution you're searching for can be found in the pageYOffset property. You can check it out here and also here

var horizontalScroll = window.pageYOffset;

Answer №3

Instead of the traditional method of calculating element position and height, this code offers a more efficient approach.

let totalSections = document.querySelectorAll("section").length;
let sectionHeight = document.querySelector("section").clientHeight;
let totalHeight = totalSections * sectionHeight;

// Set threshold value or change to 0
let threshold = sectionHeight / 2;

window.addEventListener('scroll', function(e) {

  let scrollPosition = window.scrollY + threshold;

  // Calculate position based on total height and scroll position
  let position = (totalHeight - scrollPosition) / sectionHeight;

  // Reverse the position for accurate section number
  let final = totalSections - position;

  // Get only the section number
  let sectionNumber = Math.trunc(final);

  // Calculate percentage from the final position
  let positionPercentage = final - sectionNumber;
  console.log("section", sectionNumber, "percentage", Math.trunc(positionPercentage * 100));
});
*,
*:after,
*:before {
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  text-decoration: none;
  list-style-type: none;
  color: rgba(0, 0, 0, 0.8);
}

body {
  background-color: #f1f1f1;
  font-family: 'Roboto', 'Helvetica', 'Helvetica Neue', 'Arial', sans-serif;
  background-image: url("./assets/svg/topography.svg");
  background-attachment: fixed;
}

section {
  min-height: 100vh;
}

.navigation {
  display: flex;
  flex-direction: column;
  position: fixed;
  right: 5%;
  top: 50%;
  transform: translateY(-50%);
  text-align: right;
}

.navigation div {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-bottom: 30px;
  transition: all .1s linear;
  border: 5px solid rgba(0, 0, 0, 0.5);
  cursor: pointer;
}

.navigation div:hover {
  transform: scale(1.2)
}

.one {
  background-color: #2ecc71;
}

.two {
  background-color: #9b59b6;
}

.three {
  background-color: #34495e;
}
<nav class='navigation'>
  <div></div>
  <div></div>
  <div></div>
</nav>
<section class='one'></section>
<section class='two'></section>
<section class='three'></section>

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

How to centrally align Vuetify's dropdown menu with the button

Below is a drop-down menu with two rows of v-list items: <v-menu class="dropdown" open-on-hover offset-y > <template v-slot:activator="{ on, attrs }"> <v-btn class="rounded-xl green darken-3 text-ca ...

Updating a behavior object array in Angular 5 by appending data to the end

After creating a service to share data across my entire application, I'm wondering if it's possible to append new data to an array within the userDataSource. Here is how the service looks: user.service userDataSource = BehaviorSubject<Array& ...

Issues with ng-repeat causing the Angular Editable table to malfunction

<table class="table table-bordered"> <tbody> <tr ng-repeat="playerOrTeam in template.editableTable track by $index"> <td style="text-align: center;" ng-repeat="playerOrTeamCat in playerOrTeam track by $index"> ...

Invoking PHP code from within Javascript will output the function as a direct string

I seem to be going in circles and missing something silly... My setup involves using CodeIgniter on the server-side and Bootstrap on the client, but that's not really the issue here... I am attempting to access a PHP value within a JavaScript functi ...

Removing the switcher outline in Bootstrap Switch: a step-by-step guide

I have implemented the bootstrap-switch - v3.3.1, however, I want to remove the default blue outline that appears around the switcher when toggling it on or off. Despite setting style="outline: 0 none; for the input, the outline remains visible. Below is ...

Axios consistently produces results in the form of strings but always seem to omit the final

I'm encountering an issue with my axios post method. public function viewAuthCheck(Request$request){ return [ 'test' => 'hello!' ]; } Here is my axios function: axios.post('/timetracking/settings/auth/check ...

Error: Type Error when using custom App and getInitialProps in Next.js

I have a simple app built using the Next JS starter kit, and I am attempting to integrate custom functionality as outlined in the documentation: class MyApp extends App { static async getInitialProps({ Component, router, ctx }) { let pageProps = {}; ...

CSS/HTML: Resolving Internet Explorer's Div Positioning Challenges

I've been struggling to find a resolution for this issue but I haven't been able to come up with anything effective. Here's the basic concept of what I'm trying to achieve. My goal is to have my layout divided into 3 divs. The first se ...

Incorrect Reactjs installation technique

When I try to run create-react-app on my Windows PC, only dependencies are being installed with no folders other than node_modules. Even when using Yarn, I haven't been able to progress further. Please assist and thank you in advance for any help. Thi ...

Encountered an issue while trying to access the length property of an undefined value within an aside

I am currently utilizing ng-strap's modal, alert, and aside features. Each of them is functioning properly on their own, but when I attempt to place an alert or modal inside an aside, it throws the following error: Uncaught TypeError: Cannot read p ...

When using v-for to render components and <selection>, is there a way to customize it for just one specific instance of the component?

How can I modify the selection in each instance separately when rendering elements of an array obtained from the backend using v-for? Currently, changing one selection affects all instances due to the v-model. Is there a way to target only one selection ...

How does the onclick event trigger even without physically clicking the button?

I am struggling with creating a simple button using mui. My intention is to activate a function only when the button is clicked, but for some reason, as soon as I enter the webpage, it triggers an alert automatically. This behavior is puzzling to me and ...

Issues with aligning text in TextBoxes

I'm struggling to center align my text boxes and write labels on either side. I want it to look like this: https://i.stack.imgur.com/6QsNv.png Despite trying different solutions, I can't seem to get the boxes to align in the center. Is there a ...

Parallax scrolling in all directions

Is there a resource available for learning how to program a website similar to the one at ? I am familiar with parallax but can't seem to find any examples that resemble what they have done on that site. ...

Adjust the width of a div in Angular 6 based on a specified condition

I need to adjust the width of a div based on certain conditions. <div [ngStyle]="'width': selectedTab =='Home' ? '50%' : '100%'"> </div> The currently selected tab is stored in "selectedTab". There ...

encountering an issue during the installation of a npm module

When trying to install any module from npm or yarn, I keep getting this error. I'm unsure of where the problem lies. https://i.stack.imgur.com/bYO5K.png ...

Choose the number that is nearest to the options given in the list

I am faced with a challenge involving a list of numbers and an input form where users can enter any number, which I want to automatically convert to the closest number from my list. My list includes random numbers such as 1, 5, 10, 12, 19, 23, 100, 400, 9 ...

Guide on getting "Laravel Localization To Vue/JSON" up and running efficiently

I am currently implementing the "Laravel Localization To Vue/JSON" feature in my Laravel 5.8 project. However, I am facing an issue where when I try to translate a text using: {{ trans.get('Header') }} it only displays "Header". The localizatio ...

How can you create a jQuery fade in effect for a single <li> element

I'm in the process of developing a task management app that generates a new li element every time a user adds an item. However, I am facing an issue where fadeIn() is activating for every li on the page whenever a new item is added. Does anyone have s ...

Whenever I press a button, my desire is for each picture to seamlessly reposition itself in the exact same spot on the screen

Having some issues with my code. When I click a button, the plan is for the pictures to change one by one to simulate a traffic light sequence. However, when I run the code, all the pictures appear at once without any effect from the button. Any help in ac ...