Navigate to the middle of a DIV container in Angular 7

Is there a way to programmatically scroll to the center of my element on both the Y and X axes when a specific function is executed? My HTML structure includes the following (I am aiming to scroll to the middle of #viewport):


</div>
      <div #viewport class="document-view-port">
          <div #viewBox></div>
 </div>

In my TypeScript file, I have imported the elements in this manner (attempting to determine the Y center):


  @ViewChild('viewBox') viewBox: ElementRef;
  @ViewChild('viewport') viewport: ElementRef; 

Here are the latest methods I have tried to calculate the center point for scrolling:


  zoomIn() {
    const elementRect = this.viewport.nativeElement.getBoundingClientRect();
    const absoluteElementTop = elementRect.top + window.pageYOffset;
    const middle = absoluteElementTop - (elementRect.height / 2);  
    this.viewport.nativeElement.scrollTo(0, middle)
  }

I am encountering issues with achieving this functionality. Any guidance or assistance would be greatly appreciated.

[edit]

The scrollIntoView() method does not yield the desired result in my code. I am looking for a solution to identify these coordinates and implement the scroll without relying on any pre-defined functions.

Answer №1

To successfully achieve the scroll, utilize window.scrollTo(x, y).

enlargeView() {
    const elementRectangle = this.viewport.nativeElement.getBoundingClientRect();
    const absoluteTopPosition = elementRectangle.top + window.pageYOffset;
    const middlePosition = absoluteTopPosition - (elementRectangle.height / 2);  
    window.scrollTo(0, middlePosition); // ensure you have a reference to the window object in your component
  }

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

Attempting to showcase information on the Angular frontend

When attempting to retrieve the Street name, I am seeing [object Object]. What is the optimal approach for displaying JSON data on the client side? I managed to display a street name but struggled with other components. How can I access the other elements ...

Utilize the ::before selector to insert white spaces

I attempted this solution, but unfortunately it did not produce the desired outcome: .stackoverflow::before { font-family: 'FontAwesome'; content: "\f16c "; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-aw ...

Angular nested innerHTML not evaluating ternary operator

Here is a code snippet that I am struggling with: {{ Name && Name.length > 20 ? (Name | slice: 0:20) + "..." : Name }} The above code works fine when used inside a div, but when I try to use it within innerHTML, I encounter a syntax e ...

Building Firestore subcollections with the latest WebSDK 9: A step-by-step guide

I'm looking to create a subcollection within my document using the webSDK 9, specifically the tree-shakable SDK. While I have come across some solutions, they all seem to be outdated and reliant on the old sdk. Just for context, I am working with Ne ...

Facing an issue with webpack-dev-server where it displays a blank screen

Hello! I am currently in the process of creating my first MERN stack application, using Webpack as the build tool. The main objective is to have Express serving the APIs for the app and webpack-dev-server handling the static content (from my static directo ...

What is the best way to shorten string values that exceed a certain length?

Here is an array list I have: $myarray = array( array( 'name' => 'File name 1 - type.zip', 'size' => '600KB', ), array( 'name' => 'File name 2 - type.pdf&a ...

How should I integrate my JS authentication function in Rshiny to enable the app to utilize the outcome?

Currently, I have an Rshiny application set to be published on the server but in order to ensure that a specific user has access, we require an API authentication token. The process of authentication is handled within JS tags outside of the application, wh ...

What is the best way to set the first radio button as the default selection in Material UI?

The challenge I am facing involves a set of radio buttons representing dates from today to 30 days in the future. When a radio button is selected or active, it changes the background color. However, I would like the default selection to be the first radio ...

Learn how to create a smooth and consistent horizontal image slider using JavaScript to manipulate transition transforms

Does anyone know how to create a seamless sliding effect for a series of images in Vuejs? Let's say we have images 1, 2, 3, 4, and 5 When the first slide occurs, the order of images should be: 2, 3, 4, 5, 1 For the second slide: 3, 4, 5, 1, 2 And ...

Amazon Banner Integration for Angular Version 4

Having some trouble getting an Amazon banner to display inside an angular material 2 card. The div appears empty and the banner is not rendering. Any idea what could be causing this issue? Below is the code snippet showcasing my attempts: <md-card clas ...

What is the best way to transfer the data from one JavaScript object to a new, empty object?

My Angular site requires a JavaScript object (JSON retrieved from a database) to display widgets: [{'widget_id':'1','widget_name':'Blue Widget','widget_description':'A nice blue widget','wid ...

I am creating an HTML page that incorporates p5.js, and the text I'm rendering

It seems like the draw loop is continuously refreshing every x seconds, causing this behavior. Is there a way to slow down or disable the frame update without affecting the video refresh rate? I was thinking of adding an fps counter and implementing an i ...

The command "json_encode($array)" does not seem to be encoding the complete array

I ran a test on the following: <? echo json_encode($array) ?> result: ["PG","Kevin Sad","8000","12"] Upon placing it within a form option value to be selected by my script function: <option value=<? echo json_encode($array) ?> > op ...

Managing Modules at Runtime in Electron and Typescript: Best Practices to Ensure Smooth Operation

Creating an Electron application using Typescript has led to a specific project structure upon compilation: dist html index.html scripts ApplicationView.js ApplicationViewModel.js The index.html file includes the following script tag: <script ...

Unable to modify the state of data in Vue.js

After developing a weather app, I implemented some components with fields in the data section. However, when I changed the value of these fields in the methods section and attempted to access them in another method, I discovered that the old values were be ...

Show the current time of a track using VueJS

Is there a way to have the time continuously update itself without needing to click on anything? When I press play, I want the seconds to automatically start updating from 0:00 until the end of the audio track. Currently, the time only updates when clicked ...

How can I configure nest.js to route all requests to index.html in an Angular application?

I am developing an Angular and NestJS application, and my goal is to serve the index.html file for all routes. Main.ts File: async function bootstrap() { const app = await NestFactory.create(AppModule); app.useStaticAssets(join(__dirname, '..&ap ...

Animating CSS when closing a modal box

I followed the instructions from a tutorial on W3Schools here to create this code. The "open model" button triggers the modal to open with a smooth CSS animation, which looks great. However, when I click the close button, the modal abruptly closes without ...

Guide to selecting a date using JavaScript in Selenium with Ruby

I'm having some trouble selecting a date from a date picker field using JavaScript in Selenium WebDriver. I've attempted the code below, which does navigate to the date window successfully, but I can't figure out how to execute the JavaScrip ...

Send the typeahead object result from Angular to another function within the controller

In my current setup, I am utilizing the ui-bootstrap typeahead feature to fetch an object from an external API. Upon selecting the object, it triggers a callback function that stores the results in a separate function within my controller. The challenge l ...