Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following html element:

<h1>Some text</h1>

I need to detect a click and recognize whether it landed on the text part or the blank part of the element.

To preserve consistency of the rest of the app I cannot change the display of this element to inline or inline-block.

I also cannot modify the inner html of this element so splitting it into two <span> elements is not an option either.

The text inside this element is not constant and is in fact editable.

Can I detect a click only on the visible (text) part of this heading?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
280 views
Welcome To Ask or Share your Answers For Others

1 Answer

QUESTION "I also cannot modify the inner html of this element so splitting it into two elements is not an option either." does this mean after the fact or before the fact? i.e is it that you cannot alter the HTML or that you can't go in and mutate the HTML via JS ?

Current Solution: I parse all elements with the .clickable identifier, remove & rebuild their text contents and place spans around them - this way i can add click listeners to the individual text/span elements - giving me access to the text itself.

const clickables = document.querySelectorAll('.clickable')
clickables.forEach(el => new Clickable(el))

function Clickable (el) {
  const _handleClick = ({target}) => console.log(target.innerHTML)
  const texts = el.textContent.split(/s/)
  
  el.innerHTML = ''
  
  texts.forEach(t => {
    const span = document.createElement('span')
    span.innerHTML = `${t} `
    span.addEventListener('click', _handleClick)
    el.appendChild(span)
  })
}
<h1 class="clickable">Some text</h1>

<h2 class="clickable">Some! more! text2</h1>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...