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.
That's almost convincing enough to stop using DDG over Google, but not quite 🙂
i hear ya. biG brother sees all
o.O without making each character its own DOM element? (fifteen little [:span]s) ... i'm not sure
Oh, I think I misread your goal. How would you do it in JavaScript? Maybe it'd be easier to translate that reasoning.
Yeah, there could be any number of preceding spans as well as some plain text.
I think in JS I could just keep accumulating the length of the previousSibling until there are no more.
You can use previousSibling in cljs too. Maybe this is helpful https://github.com/thheller/shadow/blob/master/src/main/shadow/dom.cljs#L533
Hmm, yeah, looks like it would be. I'll give it a try. Thanks!
Sure! 😃
When you figure it out let me see 😄
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?
@sova 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)
very nice! just some searching. I searched for "clojurescript previousSibling" and it was the first result