-2

For context, I'm trying to make an approximation of how does Google Docs lets users enter comments associated with highlighted text like this:

enter image description here

I'm not trying to implement Google Docs! I just want to let an end-user comment on a specific sentence, paragraph, or heading in a static HTML page. The piece I'm missing is when the user clicks, how do I figure out (using JavaScript) where in the text or DOM that click took place?

Supported Browsers: IE 10+, Edge, Chrome, Firefox, Safari (early 2017), including recent versions of iOS and Android (plus Mac, Windows, Linux).

How to implement Google doc like text editor? is educational, but I'm looking for a way to implement an approximation of only this one feature in a couple of days. What happens on the server, how the position is stored in the database, what happens if the static HTML changes over time, all of that is OUT OF SCOPE for this question. I'm just asking about client-side JavaScript and locating where a user clicked in a document.

Community
  • 1
  • 1
GlenPeterson
  • 4,866
  • 5
  • 41
  • 49
  • 1
    To the asker: this question is asking how to do something nearly as hard as creating Google Docs in just a few days. https://developer.mozilla.org/en-US/docs/Web/API/Selection?redirectlocale=en-US&redirectslug=DOM%2FSelection for how to get the Selection. Note that walking the tree and collecting text is not that easy, really tricky code. What you requested is for someone to do the work for you, which is not what Stack Overflow is for. You also did not show what you tried, or what you searched for. – Jared Updike Feb 17 '17 at 23:19
  • @JaredUpdike Thank you for the helpful link and explanation of why this is not a good question. I didn't immediately see how it was possible to do simply in JavaScript. Kind user's answer is more or less what I was looking for. I think it's a stretch to say he did my work for me - it's only one line of code. As you said, I still have some hard problems to solve, but this question is just about how JavaScript can best report the position of a click in a document. – GlenPeterson Feb 18 '17 at 00:04

1 Answers1

2

Following code will provide you the coordinates of user's click event.

document.addEventListener("click", (e) =>  console.log(e.clientX, e.clientY)) 
kind user
  • 40,029
  • 7
  • 67
  • 77
  • This is a good start, but it tells the offset from the top of the visible portion of the page. I guess I'd need to figure out how far down the document the user had scrolled in order to know where in the whole document the click occurred. – GlenPeterson Feb 17 '17 at 21:40
  • Aha! I think if I combine your answer with this I have enough: http://stackoverflow.com/questions/2481350/how-to-get-scrollbar-position-with-javascript – GlenPeterson Feb 17 '17 at 21:41
  • @GlenPeterson I'm glad. If you want you can upvote or mark the question :) – kind user Feb 17 '17 at 22:25