Obtain the precise X and Y coordinates of a <li> element regardless of where the mouse is clicked using Typescript

I'm stuck and could really use some assistance!

Hey there, I have a simple question but I seem to be missing a crucial element.

Here's my fiddle where I can detect the clicked item but that's as far as I've gotten:

http://jsfiddle.net/pborregg/w6pbfuae/1/

This is the JavaScript code snippet I'm using:

function getEventTarget(e) {
  e = e || window.event;
  return e.target || e.srcElement;
}

var ul = document.getElementsByClassName('commentlist')[0];
ul.onclick = function(event) {
  var target = getEventTarget(event);
  alert(target.innerHTML);
};

This is the HTML structure in my application:

<pretty-scroll>
  <ul class='commentlist'>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
</pretty-scroll>

Here's the Stackoverflow post that inspired me to work on this:

Get Clicked <li> from <ul onclick>

What I am aiming for is to determine the central value of the mouse position when it is clicked.

In the image below, you'll see the word "ACCEPTED". When I click on that, I only require the leftmost X/Y position of the li element.

https://i.sstatic.net/0BkDv.png

Each record may contain multiple comments and the clickable area will always be at the word "ACCEPTED". Please note: "Accepted" is just placeholder text and could vary.

I want to find the MIDPOINT of each li element. The starting point for where I want my modal to appear is: transform: translate(40px, 120px); The next li is exactly 125px down the Y-axis, and so forth for subsequent lis.

Considering different viewport sizes like laptops, desktops, large monitors, etc., how can I accurately pinpoint the EXACT location (specifically, dead center) based on the fixed height of the li elements? Let's assume all li elements are 100px high; thus, 50px would be the DEAD CENTER.

Unfortunately, I am unable to modify the existing code and must rely solely on the event passed into my .ts file:

public setModalLocation(xpos: any, ypos: any): void {

  console.log("This X:", xpos);
  console.log("This Y:", ypos);

  //base modal location for first comment(x40,y120)
  const ul = document.getElementsByClassName('commentlist')[0] as HTMLElement;

  let srcEl;
  let tarEl;
  let e = window.event;
  srcEl = e.srcElement;
  tarEl = e.target;

  console.log("Target: ", tarEl);
  console.log("SrcElement: ", srcEl);

  //The xpos and ypos should be x=40 and y=120 for the first comment. Each comment is 125px lower on the y-axis.

  //Need to move the modal with the scroll Y of the mousewheel.
  //FIXME: THIS IS A STUB and cannot be used for all... this just gets me to the FIRST <li> in the list of comments.
  if (xpos !== "50") {
    xpos = "50";
  }
  if (ypos !== "120") {
    ypos = "120";
  }

  this.css.outerWrapper.transform.newxy = "translate(" + xpos + "px" + ", " + ypos + "px)";
  this.theMovingModal.style.transform = this.css.outerWrapper.transform.newxy;

} 

Answer №1

I have implemented some modifications and included additional code to accomplish your request.

function getEventTarget(e) {
    e = e || window.event;
    return e.target || e.srcElement;
}

var ul = document.getElementsByClassName('commentlist')[0];
ul.onclick = function(event) {
    var target = getEventTarget(event);
    var elemPos = getOffset(target);
    alert(target.innerHTML + " ::: " + elemPos.top + " : " + elemPos.left);
};

function getOffset(el) {
    var _x = 0;
    var _y = 0;
    while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return {
        top: _y,
        left: _x
    };
}

The getOffset function determines the top and left position of an element.

Experience it yourself at jsfiddle.net/h3vcjsr7

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

Why isn't my event handler triggering when working with TypeScript services and observables?

I am currently working on a project in Angular 2 where I am incorporating observables and services in typescript. However, I have encountered an issue where the event handler in my observable is not being triggered. Below is the code snippet: The Service ...

An HTML/CSS component that dynamically adjusts its height at random intervals

My goal is to have the footer of my page occupy just one line in height. On occasion, when I open my page in a new browser tab, the footer ends up being two lines tall. However, if I simply reload the page within the same tab, everything appears as intende ...

Is There a Glitch in IE9? Unexplained Expansion of DIV Element

Here is a small code sample that I have: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Test</title> <style type="text/css"> table.Sample { width: 600px; table-layout: fixed; } table.Sample ...

Having difficulty in getting a hyperlink to open in a new tab with _blank attribute

I'm currently working with this code for my link. <a href="https://dribbble.com/jamesfrewin"><img class="socialicon" src="images/icons/dribbble_dark.png" onmouseover="this.src='images/icons/dribbble_pink.png'" onmouseout="this.src= ...

What are some methods for toggling text visibility in PHP?

I am facing confusion regarding the functionality of this code. Here is the snippet in question : //start date to end date <?php if($show5 < $show6) { ?> <a>show content</a> <?php }?> If both 'start da ...

Determine the number of visible li elements using jQuery

Currently, I am utilizing a jQuery script to count the number of li elements in my HTML code. Here is an example of the setup: HTML: <ul class="relatedelements"> <li style="display:none;" class="1">anything</li> <li style="disp ...

Is there a way to access the element reference of a component directly within the template?

When I mouse over certain elements, I use the following code to set focus: <div #divTemplateVar (mouseover)="divTemplateVar.focus()"></div> However, this method does not work for components: <component #componentTemplateVar (mouseover)="c ...

What is the process for creating a modal transition?

I am attempting to add animation to a modal using a transition effect. My goal is to open it slowly, either from the center of the screen or from the bottom. However, I am struggling to understand how this can be achieved... While searching on Google, I c ...

Extract the value from an array of objects

https://i.sstatic.net/fTShc.png Having some difficulty accessing the elements of an array. In order to assign a project name to a local variable projectName, I am seeking assistance with extracting the project name from the given JSON structure. Any hel ...

What is the best way to store client-uploaded files on the client-side using Bootstrap forms and Express server code?

Essentially, the user submits a file for upload, which is then saved on the client-side (I believe this is handled by PHP), and the upload form I am utilizing is a Bootstrap HTML form. On the server side, I am writing my code with Express. I'm feeling ...

What is the best way to reveal or conceal a div element on mouseover with jQuery?

Currently, I have a table with the following structure. <table> <tr> <td id="divOne">div one</td> <td id="divOne">2222</td> </tr> <tr> <td id="divOne">d ...

JavaScript form with radio buttons

I'm completely new to JavaScript and I'm attempting to create a basic script that will show one form when a radio button is checked, and another form when the second radio button is clicked (with no form displayed when neither is selected). I kno ...

Ensure that site content remains visible above the table when refreshing the Ajax Table

Whenever I update the table, the content above it ends up below the table. This is frustrating because the content should not be affected by the refresh. How can I resolve this issue? <!DOCTYPE html> <html> <head> <titl ...

The Angular performance may be impacted by the constant recalculation of ngStyle when clicking on various input fields

I am facing a frustrating performance issue. Within my component, I have implemented ngStyle and I would rather not rewrite it. However, every time I interact with random input fields on the same page (even from another component), the ngStyle recalculate ...

The Javascript function I created references a variable that seems to be undefined in the code

Recently, I discovered a function that is triggered with an onclick event using "openNav()" from an HTML element. Below is the code snippet for this function: function openNav() { document.getElementById("nav-drawer").classList.add("nav-drawer-open"); ...

Apply CSS styling (or class) to each element of a React array of objects within a Component

One issue I'm facing involves adding specific properties to every object in an array based on another value within that same object. One such property is the background color. To illustrate, consider an array of objects: let myObj = { name: "myO ...

Organize rows in the table while maintaining reactivity

A challenge I'm facing with a web app (Angular SPA) is that it displays a large table without the ability to sort. To work around this issue, I've managed to implement sorting via the console. However, re-inserting the rows after sorting causes t ...

What is the best way to utilize jQuery to expand an HTML form?

For my new web application project, I am working on a feature that allows users to create messages with attached files. Check out this image for multiple HTML file inputs using jQuery: http://img39.imageshack.us/img39/4474/attachments.gif One of the func ...

The integration of CSS into an HTML file is ineffective

I'm new to learning about html and css files, and I've been struggling with a particular issue for some time. I created these files, but I can't seem to apply the css to the html file: app.py from flask import Flask from flask import rende ...

What are some ways in which I can utilize the Ember Handlebars helper?

Similar Question: Using logical operators in a Handlebars.js {{#if}} statement Below is the code snippet provided: {{#each dataArray}} <li>{{#isTrue idVal1 idVal2}} display some text1 {{else}} display some text2 {{/isTrue}} & ...