Skip to content Skip to sidebar Skip to footer

Detect Click On Text Part Of A Block Element

I have the following html element:

Some text

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

Solution 1:

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 Answer : 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 =>newClickable(el))

functionClickable (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)
  })
}
<h1class="clickable">Some text</h1><h2class="clickable">Some! more! text2</h1>

Solution 2:

By the use of Jquery you can use the .click function to know if the h1 tag is clicked.

$('#test').click(function(){
    alert("Clicked!");
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><h1id='test'>TEST</h1>

Post a Comment for "Detect Click On Text Part Of A Block Element"