Sunitha Premakumaran
Sunitha Premakumaran

Reputation: 122

Position a div based on the mouse position clicked

I need to display a popup whose position is relevant to the clicked mouse coordinates in angular 4. A perfect example would be creating events in google calendar

Upvotes: 2

Views: 5106

Answers (1)

codeepic
codeepic

Reputation: 4112

In your HTML:

<div class="click-container" (click)="onMouseClick($event)"></div>

In your TS:

onMouseClick(e: MouseEvent) {
  console.log(e);
  //e.pageX will give you offset from left screen border
  //e.pageY will give you offset from top screen border

  //determine popup X and Y position to ensure it is not clipped by screen borders
  const popupHeight = 400, // hardcode these values
    popupWidth = 300;    // or compute them dynamically

  let popupXPosition,
      popupYPosition

  if(e.clientX + popupWidth > window.innerWidth){
      popupXPosition = e.pageX - popupWidth;
  }else{
      popupXPosition = e.pageX;
  }

  if(e.clientY + popupHeight > window.innerHeight){
      popupYPosition = e.pageY - popupHeight;
  }else{
      popupYPosition = e.pageY;
  }
}

Then you need to initialise the popup component with the relevant code.

Upvotes: 3

Related Questions