Incorporate a minimum height requirement for enabling the scroll to top feature

I am currently dealing with some JavaScript code that scrolls to a specific div when clicked. However, I have encountered an issue where the div is displayed at the very top of the page, causing it to go behind a fixed header that is 90px in height. As a result, the title of the div is hidden.

To solve this problem, I would like to modify the code so that the div does not scroll all the way to the top, but instead leaves a certain height gap, for example, 90px. You can see the issue in the screenshot provided: https://i.sstatic.net/kDIAz.png

Here is the current JavaScript code:

this.scrollTo = function(eID) {

        // The scrolling function
        // was sourced from http://www.itnewb.com/tutorial/Creating-the-Smooth-Scroll-Effect-with-JavaScript

        var startY = currentYPosition();
        var stopY = elmYPosition(eID);
        var distance = stopY > startY ? stopY - startY : startY - stopY;
        if (distance < 100) {
            scrollTo(0, stopY); return;
        }
        var speed = Math.round(distance / 100);
        if (speed >= 20) speed = 20;
        var step = Math.round(distance / 25);
        var leapY = stopY > startY ? startY + step : startY - step;
        var timer = 0;
        if (stopY > startY) {
            for ( var i=startY; i<stopY; i+=step ) {
                setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
                leapY += step; if (leapY > stopY) leapY = stopY; timer++;
            } return;
        }
        for ( var i=startY; i>stopY; i-=step ) {
            setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
            leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
        }

        function currentYPosition() {
            // For Firefox, Chrome, Opera, Safari
            if (self.pageYOffset) return self.pageYOffset;
            // For Internet Explorer 6 in standards mode
            if (document.documentElement && document.documentElement.scrollTop)
                return document.documentElement.scrollTop;
            // For Internet Explorer 6, 7, and 8
            if (document.body.scrollTop) return document.body.scrollTop;
            return 0;
        }

        function elmYPosition(eID) {
            var elm = document.getElementById(eID);
            var y = elm.offsetTop;
            var node = elm;
            while (node.offsetParent && node.offsetParent != document.body) {
                node = node.offsetParent;
                y += node.offsetTop;
            } return y;
        }

    };

Answer №1

To improve your code, consider making a slight adjustment to the following line:

var topY = findElementPosition(elementID);

Instead, you can try this updated version:

var topY = findElementPosition(elementID) - 50;

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

The default export (imported as 'Vue') could not be located within the 'vue' module in Vue 3 and Laravel

I'm currently in the process of building a project that combines Laravel 8 and Vue JS 3. I've set everything up, but whenever I try running `npm run watch`, I encounter an error message similar to the one below. Despite looking through various fo ...

What is the best way to showcase a singular item from response.data?

Below is the controller I have set up to display details of a single book from my collection of json records .controller('BookDetailsController', ['$scope','$http','$stateParams',function($scope,$http,$stateParams){ ...

Learn how to display every ASCII or EBCDIC character once radio buttons have been selected

I'm currently working on a simple website that requires the user to input a minimum of 256 characters, choose between ASCII or EBCDIC for conversion, and then click the submit button (Run) to display the final converted result on the page. However, I& ...

The issue of Angular's ng-repeat view not refreshing after a search query remains unresolved

Having some trouble with updating a results array in AngularJS using a service call. After submitting a form and calling the service, I set up my callbacks with .then() on the promise object. However, the view only updates when I start deleting characters ...

How can I access a property of the model controller when I need to use the ngModel controller?

Implementing ng-repeat and defining a model with it resembles the code snippet below: <div ng-repeat="thing in things" ng-model="thing" my-directive> {{thing.name}} </div> Subsequently, within my directive, the structure typically appear ...

verifying the presence of offspring in knockout js

Utilizing knockout for displaying items on the page, I have a series of groups such as Group 1, Group 2, etc. Each group is contained within its own div. Upon clicking on a group, it expands to showcase the items within that specific group. However, some o ...

Accessing the Parent Variable from a Function in JavaScript: A Guide

How can you properly retrieve the value of x? let x = 5 const f = (n:number) => { let x = "Welcome"; return x * n // Referring to the first x, not the second one } Also, what is the accurate technical term for this action? ...

Using TypeScript to call Node.js functions instead of the standard way

Can someone assist me with the issue I'm facing? I have developed a default node.js app with express using Visual Studio nodejs tools, and now I am attempting to call the setTimeout function that is declared in node.d.ts. The code snippet in question ...

Arrange two arrays by organizing them based on the contents of one in JavaScript

Consider the following two arrays: priceArray= [1, 5, 3, 7] userIdArray=[11, 52, 41, 5] The goal is to sort the priceArray in such a way that the userIdArray also gets sorted accordingly. The desired output should look like this: priceArray= [1, 3, 5, ...

Tips for updating server-side variables from the client-side in Next.js

There is a code snippet in api/scraper.js file that I need help with. const request = require("request-promise"); const cheerio = require("cheerio"); let url = "https://crese.org/distintivo-azul/"; let result; request(url, ...

Revamp the sequence of divs using jQuery

<div class="example first">111</div> <div class="example second">222</div> <div class="example third">333</div> Can the order of these divs be changed using jQuery? I am looking to get: <div class="example second"&g ...

What is causing the discrepancy in outcomes between using ng-show="!emptyArray" and ng-hide="emptyArray"?

I used to believe that ngShow and ngHide were like two sides of the same coin, acting as boolean counterparts to each other. However, my perception was challenged when I encountered unexpected behavior with ngShow in relation to an empty array. Check out ...

Update the labelClass of markers when hovering over them with jQuery on Google Maps

After successfully incorporating the markerwithlabel.js file, I am now able to display markers with labels on my Google map using the following code: markerArray[i] = new MarkerWithLabel({ position: myLatLng, map: map, icon: image, lab ...

"Unlocking the secret to fetching the id of the clicked element within a Highchart context menu

Is it possible to retrieve the id of a clicked button on the highchart context menu? Alternatively, is there a way to execute the click function twice? const contextButtonArray = []; contextButtonArray.push({ { text: 'TEST BUTTON&ap ...

Is it possible to merge createStackNavigator with createBottomTabNavigator for enhanced navigation functionality

Current Situation : My app currently has three tabs for navigation (School, Admin, Family); I am now facing a challenge as I want to add additional screens that do not require tabs for navigation. These screens will be accessed using this.props.navigati ...

How can I obtain the download link for an image that has been resized using Node.js in Google Cloud Functions?

I have recently started exploring node js and google cloud functions. Successfully, I can resize an image to create a thumbnail. However, I am stuck at finding the download URL for the newly generated thumbnail. Below is the code snippet: exports.gener ...

Is there a way to download a file using an ajax request?

We are faced with a particular scenario in our application where: Client sends a request Server processes the request and generates a file Server sends the file back as a response Client's browser prompts a dialog for downloading the file Our appli ...

There seems to be an issue with the syntax in ReactJS: the URL is

I'm facing an issue in my React code. I have a function that doesn't seem to be in the correct format for React. check(img) { console.log(img,typeof img) const url=""; const arrN = ["15","16","35","36","37","38","39","40" ...

Issue with MiniCssExtractPlugin during compilation of the entry point build

We have integrated webpack into our deployment process to bundle resources efficiently. However, we are now facing a challenge as we aim to include the bundling of sass files through webpack in order to streamline our build process. The MiniCssExtractPlugi ...

Cross-Site Scripting: Building a JavaScript object with the help of PHP's json_encode

Is this code 100% secure against XSS attacks? If not, could you provide an example of a malicious string that could make it vulnerable? <html> <body> <script> <?php $bad = "malicious string. Please provide exampl ...