Fork me on GitHub
#clojurescript
<
2021-06-25
>
sheluchin18:06:50

I'm trying to figure out how to get the click position of an element node like <p>this is <i>just a</i> test</p>, where the click happens somewhere such that there are previous siblings. I want to know how many text characters there were in all the previous parts of the element. So, for example, if I click on the first t in test, the result should be 15 for this is just a . Can anyone suggest how I might do this? I'm able to use the selection API to pull siblings but not totally clear on how to iterate over all previous siblings.

sova-soars-the-sora18:06:53

o.O without making each character its own DOM element? (fifteen little [:span]s) ... i'm not sure

sova-soars-the-sora18:06:11

Oh, I think I misread your goal. How would you do it in JavaScript? Maybe it'd be easier to translate that reasoning.

sheluchin18:06:23

Yeah, there could be any number of preceding spans as well as some plain text.

sheluchin18:06:39

I think in JS I could just keep accumulating the length of the previousSibling until there are no more.

sheluchin18:06:29

Hmm, yeah, looks like it would be. I'll give it a try. Thanks!

sova-soars-the-sora18:06:20

When you figure it out let me see 😄

sheluchin18:06:19

How did you find that fn in that lib, btw? Just a lib you're familiar with, or some fancy searching skills brought ya there?

sheluchin20:06:59

@U3ES97LAC something along these lines:

{:onClick #(let [selection (. js/window getSelection)
                             srange (.getRangeAt selection 0)
                             start-offset (. srange -startOffset)
                             node (. selection -anchorNode)
                             siblings (. srange -commonAncestorContainer.parentNode.childNodes)
                             prev-sibs (vec (take (index-of node) siblings))
                             preceding-char-count (reduce
                                                    (fn [c n]
                                                      (+ c (count (or (. n -data)
                                                                      (. n -innerText)))))
                                                    0 prev-sibs)

sova-soars-the-sora21:06:55

very nice! just some searching. I searched for "clojurescript previousSibling" and it was the first result

sheluchin10:06:30

That's almost convincing enough to stop using DDG over Google, but not quite 🙂

sova-soars-the-sora17:06:08

i hear ya. biG brother sees all