Home Get absolute position and size of the current DOM element clicked
Reply: 0

Get absolute position and size of the current DOM element clicked

user2071
1#
user2071 Published in April 25, 2018, 8:25 pm

I'm using IONIC 2.

I want to get the absolute position of the element clicked (div, img, ion-slide,...) in JS. For instance, with the codes below, the absolute position in Chrome (Desketop) on DELL XPS 13 is X = 1525 and Y = -163. I don't understand why I got a negative value for the Y position on my image... Also, I didn't find a good and complete tutorial for learning how to manipulate HTML/CSS from JS in IONIC even if I found some lessons on the basics like modifying the background color and other CSS attributes.

Thanks for your help!

HTML:

<ion-content>
  <ion-slides class="image-slider" loop="true" slidesPerView="1">
    <ion-slide *ngFor="let img of pos">
      <img src="assets/imgs/{{ img.URL }}" class="thumb-img" (click)="position($event)">
    </ion-slide>
  </ion-slides>
</ion-content>

JS:

retrievePosition(e) {
  var el = e.currentTarget;
  var position = this.getPosition(el);
  alert(el.tagName + " : X = " + position.x + " ; Y = " + position.y);
}

JS function getPosition(e) :

getPosition(el) {
    var xPos = 0;
    var yPos = 0;

    while (el) {
      if (el.tagName == "BODY") {
        // deal with browser quirks with body/window/document and page scroll
        var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
        var yScroll = el.scrollTop || document.documentElement.scrollTop;

        xPos += (el.offsetLeft - xScroll + el.clientLeft);
        yPos += (el.offsetTop - yScroll + el.clientTop);
      } else {
        // for all other non-BODY elements
        xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
        yPos += (el.offsetTop - el.scrollTop + el.clientTop);
      }

      el = el.offsetParent;
    }
    return {
      x: xPos,
      y: yPos
    };
}

CSS:

page-gallery {
    .header-item {
        background: transparent;
        border: none;
    }
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.299975 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO