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

Error encountered in React Native packager due to naming conflict between "lodash" and "yeoman-generator" libraries

Issue Description Within my current project, I am utilizing "react-native": "0.36.0" along with the following dependencies: "lodash": "^4.15.0" "yeoman-generator": "^0.24.1" Upon using versions above "^3.10.1" for "lodash" and "0.21.2" for "yeoman-gene ...

Need help displaying a file link from a server using the href attribute in a PHP echo statement?

Having some trouble creating a table with PHP. I managed to create the table, but I'm trying to link a file from an FTP server in a td tag. When I use href, it gives me an error. Can you please help me correct my code? echo "<a href = '../pub ...

The API key fails to function properly when imported from the .env file, but performs successfully when entered directly

Working with Vite has been quite an experience for my project. I encountered a situation where using my API key directly worked fine, but when trying to import it from .env file, I faced the error message in the console below: {status_code: 7, status_me ...

Downloading EJS File instead of Displaying on Express.js Router

As I embark on the journey of developing a live video sharing/watching feature using Pure Node.js and without relying on any frameworks, an unexpected issue arose in the middle of the process. The problem occurred when Express started downloading an EJS fi ...

When I try to import script files into my ASP.NET page, Intellisense displays the methods accurately. However, when I attempt to call one of them, an

I added a function to an existing .js file (I tried two different files) in order to make the method accessible in multiple locations without having to repeat the code. I also created a simple function just to confirm that my function wasn't causing a ...

Prevent submitting a form multiple times with jQuery Validate - ensuring successful submission only once

I've been working on updating my Email Contact form with the jQuery Validate Plugin and AJAX within the submitHandler. It initially worked, but I'm running into an issue where it only works once. Upon trying to submit the form again, I stop recei ...

The issue arises when the jQuery onchange event stops functioning properly after the initial ajax call

Trying to switch from a frame to a div is causing some issues. After the initial AJAX jQuery call, the onchange event doesn't seem to work. However, it works fine in the frame. When I first load my page and click on the menu, everything seems good. I ...

Utilizing multiple address parameters within a single-page application

Apologies for the lengthy post. I have encountered an issue with my code after running it through a bot that I can't seem to resolve. In my code, I aim to create functionality where you can visit the address #two, followed by two separate parameters ...

Double-click required to toggle button

Here is the code snippet for controlling an LED using a web page. The script, linked to Python, effectively controls the LED. However, there is an issue where the button toggles to the right side (ON position) only after a double click. Upon first click ...

Exploring the depths of JavaScript JSON elements

After processing my PHP code, it generates a JSON output that contains multiple entries in the same structure. Here is an example with two entries: { "0": { "campaign_id": "31", "title": "new title", "description": "new descrip ...

Named Graph's Title on Image Save in Echarts

Is there a way to give a title to the image graph saved in Echarts, as Echarts does not have this option available? Any suggestions on how we can achieve this? Here is a link for reference from Echarts that provides the 'saveAsImage' option: Ch ...

Disappearing Image on Hover in JavaScript and HTML

I'm encountering an issue with my JavaScript hover effect on two images. When a user hovers over the arrow image, it should change to a hover version of that image. Additionally, if the user clicks on the arrow, it should trigger another JavaScript fu ...

Ways to store Token in Browser Cache?

I am currently developing a login system for an application at my school. I have successfully implemented user registration, which is saved to my Azure DocumentDB. However, when trying to log in with the user, the token does not get saved so that I can acc ...

In AngularJS, modifying the value of a copied variable will result in the corresponding change in the value of the main

I'm facing a peculiar issue. I have an array of objects and I used angular.forEach to update the price key value of each object. However, when I make changes in each object, it also affects the main array object. Take a look at the code snippet below ...

Sending an array encoded in JSON to jQuery

I'm attempting to send an array that I've created in PHP using json_encode(). The process involves running an AJAX request, as shown below: AJAX CALL: $.ajax({ type: "POST", url: "../includes/ajax.php?imagemeta=1", data: ...

I am facing an issue where HTML is not loading images or some parts of my CSS in PHP

I've been working on connecting my website to a MySQL database using PHP. Initially, I thought I could keep the HTML and CSS the same, but after adding everything, the images on the website stopped showing up as they did before. The fonts and other el ...

Sending a POST request using Node.js Express: A step-by-step guide

Looking for help on sending a post request from node.js Express with data passing and retrieval. Preferably a straightforward method like cURL in PHP. Can anyone assist? ...

Is it necessary to set required input if the db column can be NULL?

Is there a way to dynamically add the "required" attribute (HTML5) to an input if the chosen column cannot be null in PHP? Here's an example of what I'm trying to achieve: $result = mysqli_query($db, "SELECT * FROM table"); while($row = mysqli ...

Strategies for efficiently creating reusable HTML templates for recurring content blocks?

I am just starting out in web development and have encountered a problem with navigating through my page. The layout of the pages is the same, except for a div container. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3 ...