Binding event to text node

Here's my HTML. I need to bind a click event to "someText"

<div id="container">
    someText <a href="#">A link</a>
</div>

"someText" could be any string of text

Answers:

Answer

Use jQuery to wrap the text node with a <span>, the place the click on that.

Try it out: http://jsfiddle.net/3F4p4/

$('#container').contents()  // Get all child nodes (including text nodes)
               .first()     // Grab the first one
               .wrap('<span/>')    // Wrap it with a span
               .parent()           // Traverse up to the span
               .click(function() { alert('hi'); });??  // add the click to the span

The .contents() method returns all child nodes, including text nodes. So you grab the first child, wrap it, traverse to its parent (which is now the span), and add the click.

Answer

After a bit of messing I found a slightly better solution to Patrick's. It can select nodes after the link in this situation, making it more univerally usable. Probably better posting it here :)

$('#container')
.contents()
.filter(function() {
    return this.nodeType == Node.TEXT_NODE;
})
.wrap('<span/>')
.parent()
.click(function(){
   alert($(this).text());
});
Answer

Hacky way whithout any changing of html markup:

  1. Add contenteditable attribute to container.
  2. On click look at the selected node via document.getSelection() and check it.
  3. If selected text node is the very node, do what you want.
  4. Reset selection.

http://jsfiddle.net/quqtk8r6/2/

var el = document.getElementById("container")
el.setAttribute("contenteditable", "true")
el.style.cursor = "pointer"
el.style.outline = "none"
el.addEventListener("click", function () {
  var selection = document.getSelection(),
      node = selection.baseNode

  selection.removeAllRanges()
  if (node.nodeType == 3 && node.parentNode == el) {
    alert("someText are clicked")
  }
})
el.addEventListener("keydown", function (event) {
  event.preventDefault()
  return false
})

PS: It's more food for thought rather than real recommendation.

Answer

Either wrap it in <a> or <div> tags and assign the click event to that element.

  <a href="#" id="sometext">someText</a>

  $("#sometext").click(function() {
       do stuff here...
  });

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.