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

Removing a single duplicated element from an array using jQuery

I'm facing an issue where if I try to remove the first element that I added using the button, all elements in the array get erased. However, when I remove the last element pushed, it works just fine. To tackle this problem, I attempted to use $.inArr ...

Where is the ideal location to store non-component data properties in Vue.js?

Currently, I am in the midst of a Vue.js project where components are predominantly used. However, there are moments when I simply need to incorporate some Vue.js syntax without creating an entire component. Since I am not utilizing the render function as ...

PHP Question: Why are variables within <?php ?> not accessible within if/else statements?

I'm currently working on a basic program that involves the user inputting a number, which is then processed to generate a series of random similar numbers. After this step, the program prompts the user to select the correct variable, which will be va ...

Incorporating Angular module into the mean.io bundle

Need help with adding the angular-ui-grid module to a mean.io package: $ cd packages/custom/mypackage $ npm install angular-ui-grid --save To import the JS, add this line to packages/custom/mypackage/public/index.js: import 'angular-ui-grid'; ...

Choose the list item below

I'm working on a website that includes a select list with images. Here's what I have so far: When I choose an image from the list, it should display below. <?php // Establish database connection $con=mysqli_connect("******","***","*** ...

Scanning barcode and Qrcode with Angular js HTML5 for seamless integration

Looking to scan Barcode and Qrcode on Android, iPhone, and iPad devices for a project that is built on AngularJS and HTML5 as a mobile website. The requirement is not to download any third-party native application on the device, ruling out the use of nati ...

With the addition of a key element in the opening statement

Take a look at this code snippet: <div class="content"> This is some title<br/> Some text<br/> And maybe more text. </div> I am trying to wrap the first sentence with a <span> tag before the <br/> element, like s ...

Styling text in table cells using only CSS, without the use of scripting, based on the values within those cells

I have scoured the forum and came across several older threads that suggest it is not achievable with just CSS (the system I am utilizing does not support scripts). Is there a possibility that this has changed or if someone else has an alternative idea? W ...

Efficiently submitting multiple forms in a single click

On my photo portfolio admin page, I have created a feature to caption, keyword, and credit each photo. Previously, I had multiple forms listed dynamically with submit buttons for each form. With over 20 photos/forms on the page, this process became tedious ...

The user_login view in the account views did not provide an HttpResponse object, but instead returned None

Error: Unable to register or log in - account.views not returning HTTP response # accounts/views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from account.forms import RegistrationForm, Use ...

Having difficulty retrieving the value from a database column as it consistently displays both the column name and value

I am currently working on setting up a dynamic site title that will be controlled by my database. This way, I can easily update the database with a new title and have it reflect on my website. Below is an example of the controller setup: TestController: ...

Firefox experiencing problem with retrieving video.duration in HTML5

I am currently working on developing a unique video player from scratch. <video preload="metadata" id="videoPlayer" style="width: 640px; height: 360px;"> </video> <script type="text/javascript"> var v = ""; var myV ...

Attempting to save an image captured in a Vue form and then transmit it to the Laravel backend

Hey everyone, I'm a newcomer to Vue and Laravel and I'm currently working on a REST project. I have a form that allows users to upload an image, but I keep encountering an error when trying to store it in the database: "Request failed with ...

Comparison: JavaScript Cookies vs PHP Cookies

I have been trying to implement the following code: JS: Cookies.set(post_id + '_' + user_ip, post_id + "_" + user_ip, { expires: 1 }); PHP: $cookie_str = $post_id.'_'.get_client_ip(); if (isset($_COOKIE[$cookie_str_]) ){ print_r ...

Selecting elements by class in jQuery using a variable for the class name

Is there a way in jQuery to apply actions to all elements with a specific class, where the class name is determined by a variable? I want to select elements based on this dynamically generated class name. var x = $(this).attr('href').slice(1); ...

What is the method for modifying the input element within a TextField component from MUI?

I have TextField elements in my application that appear to be too large. Upon inspection, I noticed that the input element within them has default padding that is too big.https://i.stack.imgur.com/C13hj.png My query is regarding how to adjust the styling ...

Ways to ensure that an inner div causes the outer div to shift downward

Imagine I have a div. Within this div, there are two divs positioned side by side with the float left property. The div on the left is designated for an image. However, if the image is too tall, it does not expand the outer div to accommodate it. Instead ...

The issue of banding caused by Bloom and Antialiasing in Three.js rendering

I'm attempting to incorporate a glowing effect into my scene. To achieve this, I understand that using a bloom filter with the EffectComposer is the ideal approach. However, I've encountered an issue where utilizing the EffectComposer compromises ...

Error: Null value detected while trying to access the property 'appendChild'

Can anyone help me with this error? Uncaught TypeError: Cannot read property 'appendChild' of null myRequest.onreadystatechange @ script.js:20 Here's the code snippet where I'm facing the issue // index.html <html> <he ...

The following item in the .each() sequence

How can I move on to the next element within a jQuery .each() loop? $(".row").each( function() { if ( ... ) //move to the next iteration in the .each() loop }); Appreciate any assistance. Thank you. ...