Steps for positioning the scroll-thumb in the middle of the scrollbar

Currently, I am working on a react application and facing an issue while trying to display images with custom zoom-in/zoom-out functionality. Due to the need to add markers to each image that require precise positioning, using a pre-existing library for zooming is not providing accurate coordinates.

To overcome this challenge, I have implemented the following functions for Zoom-In and Zoom-Out :

 zoomOut = () => {
        var myImg = document.getElementById("action-image")
        var currWidth = (myImg.style.maxWidth.split("v"))[0];
        var currHeight = (myImg.style.maxHeight.split("v"))[0];

        myImg.style.maxWidth = (Number(currWidth) - 50) + "vw";
        myImg.style.maxHeight = (Number(currHeight) - 50) + "vh";
        if (this.state.scale == 0)
            this.resetImage()
        else if (this.state.scale != 0) {
            this.setState((state) => ({
                ...state,
                scale: this.state.scale - 1
            }))
        }
    }
    zoomIn = () => {
        console.log(this.state.scale);
        if (this.state.scale < 11) {
            var myImg = document.getElementById("action-image")
            var currWidth = (myImg.style.maxWidth.split("v"))[0];
            var currHeight = (myImg.style.maxHeight.split("v"))[0];
            myImg.style.maxWidth = (Number(currWidth) + 50) + "vw";
            myImg.style.maxHeight = (Number(currHeight) + 50) + "vh";
            this.setState((state) => ({
                ...state,
                scale: this.state.scale + 1
            }))
        }
    }

    resetImage = () => {
        var myImg = document.getElementById("action-image")
        myImg.style.maxHeight = '95vh'
        myImg.style.maxWidth = '75.4vw'
        this.setState((state) => ({
            ...state,
            scale: 0,
        }))
    }

Below is the code snippet for image rendering:

 <RegionSelect
    maxRegions={1}
    regions={this.state.imageLoad ? [] : this.state.regions}
    regionStyle={regionStyle}
    constraint={false}
    onChange={this.onChange}
    Draggable={false}
    regionRenderer={this.regionRenderer}
 >
<img id="action-image" style={{ zIndex: 1, maxHeight: '95vh', maxWidth: '75.4vw' }} 
src={this.state.imageURL} onLoad={((load) => {
  this.setState((state) => ({
    ...state,
    imageLoad: false,
    height: 'unset',
    width: 'unset'
   }))
  })} />
</RegionSelect>

View Image before zoom In

View Image after zoom In

The main issue arises when the image is centered to maintain its aspect ratio. As the image is zoomed in, the scrollbar should also be repositioned to the center to allow scrolling in all directions. However, currently, the scrollbar starts at the top-left position, causing parts of the image (from the top and left side) to be hidden.

Answer №1

To start, the first step is to determine the height of the scroll-bar thumb. Once you have that information, you can utilize the window.scroll function to set the desired distance for it to move. Understanding the height of the scroll-bar thumb is crucial because the scroll function does not reposition the scroll bar based on its center.

var arrowHeight = 25;
var viewportHeight = window.innerHeight;

var contentHeight = getComputedStyle(document.body).height;

contentHeight = parseFloat(contentHeight);
var viewableRatio = viewportHeight / contentHeight;

var scrollBarArea = viewportHeight - arrowHeight * 2; 

var thumbHeight = scrollBarArea * viewableRatio; 

var scrollAmount = (contentHeight / 2) - thumbHeight;

window.scroll({
    top: scrollAmount,
  left: 0,
  behavior: 'smooth'
})

For a demonstration of how this code works, check out the complete fiddle provided below.

https://jsfiddle.net/mahdiar_mansouri/5ypaeo4q/5/

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

Customizing the layout of div elements with Twitter Bootstrap for a responsive design

Utilizing Bootstrap's responsive style sheet, I have organized 4 squares in divs that span 12 columns - |3|3|3|3|. However, when I access this layout on a mobile browser, it displays as: |12| |12| |12| |12| My desired display format is: |6 ...

Contrast in spacing: comparing display block versus inline-block

Today, I stumbled upon something quite intriguing that has left me puzzled. Consider the following HTML: <div class="a"><div class="b"></div></div> And CSS: .a { background: blue; } .b { display:inline-block; height ...

The slider is malfunctioning and not functioning properly in JSFiddle

As a beginner in the world of coding, I decided to start my journey with Codecademy. Everything seemed to be going smoothly as I created a carousel image slider using JQuery. However, when I tried implementing the same code on jsfiddle, the slider became s ...

Issue: The data type 'void' cannot be assigned to the data type 'ReactNode'

I am encountering an issue while calling the function, this is just for practice so I have kept everything inside App.tsx. The structure of my class is as follows: enum Actor { None = '', } const initializeCard = () => { //some logic here ...

Vercel server fails to run Nextjs API "pages/api" on its platform

Hey everyone, I need some assistance. I'm currently facing an issue with configuring my fake API for personal projects. When I try to set it up using the /pages/api folder, it only works on localhost. However, when I deploy it to Vercel, the project ...

Tips for displaying a list of objects in React

I'm currently developing an application using React, where I have created two components. One of these components is supposed to receive an object from its parent component for rendering. This object consists of multiple elements, one being an array c ...

display div only if the adjacent element does not contain a specific class

I have a situation with two divs, one of which has the class "d-none": <div class="inexistente"> Ainda não existem documentos adicionados </div> <div class="existentes d-none"></div> ...

Is there a way to position the twitter embed at the center of a webpage?

I am attempting to embed a Twitter video and twit in such a manner that they are perfectly centered on the page and also take up the entire width of the container (my-container). Here is the HTML code that I currently have: <div class="my-container"&g ...

CORS problem arises specifically in NestJS and Vercel when sending POST requests

GET requests are functioning correctly, however, I am encountering issues with SWR when attempting to make POST requests to submit data to Firebase. The goal is to mutate state based on these requests, but I am unable to successfully perform POST requests. ...

In order to manage this specific file type, you may require a suitable loader. React in conjunction with Material UI could be the

I recently created a project using Material UI and React JS, but I encountered a puzzling error without making any changes to my app. Despite reaching out for help by creating an issue on MUI, I received no response. The app was generated using npx-create ...

Initiating a transition in the state due to an occurrence in the subordinate component

In the process of developing a basic shopping cart in React, I've hit a roadblock. Here's the plan: the App component will manage the JSON data (obtained from a local file), while the Cart component will handle the state of the shopping cart - p ...

Align and resize image using CSS styling

Seeking assistance on centering and cropping images using CSS. Tried implementing the technique from this specific article. However, experiencing inconsistencies in device UI output. Can someone shed light on this behavior? Scenario: The objective is t ...

Ways to keep selected values in the Select box without unchecking them again?

Hello there, I am relatively new to ReactJS and currently facing an issue with Selects. Specifically, I have a Select component that displays a list of names using MenuItem. My goal is to have certain names pre-selected in the Select dropdown upon initial ...

Incorporate CSS styling within a PHP document

Many individuals are aware that HTML can be embedded within a PHP file. However, can CSS also be included in a PHP file and accessed using <link rel="stylesheet" type="text/css" href="mystyle.php" /> to make it act as a CSS file? While it is possib ...

Using Private and Protected Methods in Typescript with React: Best Practices

Currently, I am engrossed in developing a React application utilizing Typescript. In cases where a component needs to offer functionality through a reference, I typically incorporate a public method (public focus() : void {...}). However, I find myself pon ...

Setting the state for an element in React after it has been mounted - a step-by-step guide

My React application features a user data form with a notification message that appears after submitting the form. The notification can be either a success or fail message, with the latter potentially containing multiple error types. I handle the error typ ...

What is the process for submitting data to an API through a ReactJS website?

I am a beginner in both react and APIs, and I have a query regarding posting to an API. My goal is to post the content of my textarea to an API and receive scores based on the text. The issue lies in the fact that the textarea would send something like th ...

Issues with Jquery show and hide functionality within a list element

My menu items are displayed using show and hide functions, sliding up and down on hover. The issue I am facing is that when a list item expands, the overall background of the menu also expands. However, when it contracts, the background also contracts. If ...

Place images within a card container using Bootstrap 4

I'm currently working with Bootstrap 4 and I am utilizing a card div. The card uses display flex and I am having trouble floating images within it, possibly because the card is configured to only allow one image. How can I successfully float multiple ...

What is the best way to display the content of a swagger.json file in a

I am currently working on developing a document portal for my API's using Express and ReactJS. My goal is to retrieve the JSON content (swagger.json) from the Express server and present it in Swagger UI on the client side. While exploring the documen ...