Hoiw can i get y coordinates of my clicked element on the whole page?

573 Views Asked by At

I have big data on Y coordinate - there is virtual scroll and a lot of items are on the page on scroll. When i click on the data then additional data is displayed for the clicked element. That makes my page unfriendly for users because sometime the additional data is big - and when the additional data is collapsed sometimes scroll automatically goes down and the user needs to scroll a little bit up to see the data...

I need when the user click on the element- automatically page scrolls up or down to that clicked element on the Y coordinate

HTML

<div *ngFor="let mainRow of tableData; let i = index;" class="card" id="mainRow-{{i}}">
   <div (click)="renderSubTable(i, mainRow, $event)">
     ... main data
   </div>

  <div *ngIf="mainRow.subTableData">
     ... additional data
  </div>

</div>

** what i tried** TS

i tried with offsetY

  renderSubTable(numRow, mainRow, event) {
   let y = pos.offsetY;
   window.scroll(0,y);
}

but that takes only the Y coordinates of the viewport - not on the whole page. PageY does not work also.

How can i resolve my issue

2

There are 2 best solutions below

10
AudioBubble On

jQuery offset gives you the absolute position (relative to the document):

const el = document.getElementById('el');
el.onclick = function() {
    const offset = $("#el").offset();
    window.scroll(0, offset.top);
    console.log(offset);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="height: 1000px; background: blue; padding-top:200px">
  <div id="el" style="height: 100px; width: 100px; background: red; margin: 0 50px;">

  </div>
</div>

Here is a code snippet for Angular

Template

<div style="height: 1000px; background: blue; padding-top:200px">
  <div (click)="onClick($event)" style="height: 100px; width: 100px; background: red; margin: 0 50px;">

  </div>
</div>

Controller

import { Component } from "@angular/core";

import $ from "jquery";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  onClick(event: MouseEvent) {
    const offset = $(event.target).offset();
    window.scroll(0, offset.top);
    console.log(offset);
  }
}

You can test it on Stackblitz

0
munleashed On

Hard to tell without an exact example (how your HTML is structured), but you should also take a look at:

(Doing on element's api not window api) https://developer.mozilla.org/en-US/docs/Web/API/Element/scroll and https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView