Adjust the jQuery.ScrollTo plugin to smoothly scroll an element to the middle of the page both vertically and horizontally, or towards the center as much as possible

Visit this link for more information

Have you noticed that when scrolling to an element positioned to the left of your current scroll position, only half of the element is visible?

It would be ideal if the entire element could be visible and even centered on the page, right?

After reviewing the source code, it's not immediately clear how the plugin determines when to stop scrolling.

I'm aware of the offset setting that can adjust the final scroll position vertically, but since the size and position of the element may vary, I'd rather find a universal solution that takes into account the size and position of the element being scrolled to, automatically centering it.

Answer №1

I decided to create a simple and efficient code implementation from the ground up. The approach is tailored for situations where the element needing scrolling is directly nested within the scrollable container. This solution is effective even in a CSS transform-scale environment, as it does not rely on $.position()

  function scrollIntoView($target) {
    var $parent = $target.parent(),
        top = parseInt($target.css('top')),
        left = parseInt($target.css('left')),
        height = $target.height(),
        width = $target.width(),
        bottom = top + height,
        right = left + width,
        xCenter = left + width / 2,
        yCenter = top + height / 2,
        sWidth = $parent[0].scrollWidth,
        sheight = $parent[0].scrollHeight,
        pWidth = $parent.width(),
        pHeight = $parent.height(),
        destLeft, destTop; // the destination values for scroll left and top of the parent

    // if element does not overfow on an axis, scroll to zero for that axis;
    destTop = bottom < pHeight ? 0 : bottom - pHeight / 2 - height / 4;
    destLeft = right < pWidth ? 0 : right - pWidth / 2 - width / 4;

    $parent.animate({ scrollLeft: destLeft, scrollTop: destTop }, 600);
}

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 process of transferring form data to an email using jQuery ajax and then redirecting to a different page while passing POST variables is not functioning properly

I've implemented a custom form on my Wordpress site that redirects to a thank you page after submission, displaying the user's input. Additionally, the form data is sent to both the user and admin emails before redirection occurs. Here's an ...

The necessary data is missing in the scope of the callback function

I'm facing an issue with a callback function's variable losing its scope. Consider the following simplified array of two objects: const search = [{socket: new WebSocket('ws://live.trade/123')}, {socket: new WebSocket( ...

Click on each item within the v-for loop to gather relevant information, and subsequently iterate through the collected data

Within a v-for loop, I have implemented a button that, when clicked, retrieves specific data. The objective is to display this data below or in place of the clicked button. <div v-for="(item, index) in items" :key="index"> <button @click="fetch ...

Place a div on top of a table

I am facing a challenge with table rows and divs. The height of the table row is set to 100px, while divs can be up to 200px. I want the div to overlay the table and cover the bottom row if it exceeds the row's height. Currently, I have achieved this ...

What could be causing media queries to not update values even after being changed through JavaScript?

I have a simple navigation bar on my website, featuring links to different subpages. To enhance the user experience on mobile devices, I added a hamburger menu icon that is displayed on smaller screens. The links in the navigation bar are hidden using CSS ...

What is the best way to retrieve all information from GitLab API using Axios?

I am looking to retrieve data from all the projects stored on my GitLab server. As I understand, GitLab usually displays a default of 20 projects per page, so I need to adjust the setting to show more projects at once: https://gitlab-repo.com/api/v4/proje ...

The functionality of Ng-Show is acting up

$scope.stay = function() { alert("Inside Keep me In") $scope.timed = false; $scope.isLogStatus = true; } $scope.displayAlert = function() { $scope.timed = true; alert("inside display") } function idleTimer() { var t; $window.o ...

Horizontalize your lists

Is there a way to make the li elements horizontal in this pagination setup? I've attempted display: inline and display: float, but neither seem to be working for me. <ul class="pagination" style="display:inline; text-align: center; margin:0;">& ...

Converting Typescript library into a standalone global JavaScript file

Currently working on developing a Typescript library that follows this structure: https://i.stack.imgur.com/YyCHk.jpg This includes the following files: restApi.class.ts import { restApiOptions } from '../models/rest.options.model'; import { ...

"Is it possible to draw on top of a canvas element that's already been

I'm currently working with an OpenLayers map that includes WMS layers with time steps. My goal is to create a loop that updates the time for each step and then saves the image once it's rendered. I've been referencing the example code from t ...

Utilizing jQuery AJAX for sending variables via POST method in PHP

Despite my belief in having the correct syntax, I seem to be missing something important. I have been searching for a solution but can't figure out why the POST variable is not being detected. My .ajax function is triggering as indicated by changes in ...

The CSS effect fails to take effect following an AJAX response

After a successful ajax response, I am attempting to apply a jQuery .css effect. However, it seems that this process is not working as expected because I am trying to retrieve the height of a newly created element and then applying it to another newly crea ...

Unable to choose anything within a draggable modal window

Can someone please assist me? I am struggling to figure this out. I can't select text inside the modal or click on the input to type text into it. I suspect it may be due to z-index issues, but I'm having trouble locating them. var currentZ = n ...

What to do when encountering the error "Uncaught (in promise) SyntaxError: Unexpected end of JSON input"?

While signing in to my website from localhost is successful, I encounter an issue when trying to do the same from my production build. The login attempt from the prod build (hosted on Vercel) does not post to , but instead goes to . I am perplexed by the a ...

The execution of jQuery code from PHP using $.ajax is not functioning properly

I am attempting to run a jQuery code from a PHP page using AJAX. Modify the HTML of div.error Here is the code (Let me know if there is a simpler method): - no $.load HTML/jQuery: jquery.js already loaded <input type='text' id='test&a ...

Creating a dynamic hyperlink variable that updates based on user input

I am attempting to create a dynamic mailto: link that changes based on user input from a text field and button click. I have successfully achieved this without using the href attribute, but I am encountering issues when trying to set it with the href attr ...

Update the div each time the MySQL table is refreshed

My website functions as a messaging application that currently refreshes every 500ms by reading the outputs of the refresh.php file. I'm looking to explore the possibility of triggering the refresh function only when the 'messages' table upd ...

What is the implementation of booleans within the Promise.all() function?

I am looking to implement a functionality like the following: statusReady: boolean = false; jobsReady: boolean = false; ready() { return Promise.all([statusReady, jobsReady]); } ...with the goal of being able to do this later on: this.ready().then(() ...

When you click on the text, the calendar will pop up for you to

When the text "SetExpiryDate" is clicked, a date picker opens. After selecting a date, the text changes to "Expires ${date}" where the selected date is inserted. If no date is selected, the text remains as it is. I'm curious how I can implement this ...

Link to Reply Comment Feature in Wordpress

It seems like I've tried numerous solutions to fix my issue but haven't had any luck, so now I'm seeking help here. Despite trying methods that have worked for others, they do not seem to work for me. My problem lies with nested comments on ...