Jquery Capture The Word Value
Solution 1:
You cannot do it without wrapping it in HTML nodes. You can apply some Javascript magic to an "unwrapped text", which basically means a Textnode
. This could look like:
$('#foo').contents().each(function(_, node) {
var nodelist = node.textContent.split(/\s/).map(function( word ) {
return $('<span>', {
text: word + ' ',
click: function() {
alert( $(this).text() );
}
}).get(0);
});
$('#foo').empty().append(nodelist);
});
demo: http://jsfiddle.net/LFCWp/
I just wrote that down. There is still a ton of optimize potential, but it should give you a basic idea of how to accomplish it.
Solution 2:
To find specific words in longer paragraphs you would have to create Range objects and TextRange's to find the coordinates of specific words in the paragraph. Once you have mapped the coordinates for each word, you could then match the window click event coordinates to the word that is within the range.
The question at Retrieving DOM textnode position has some similarities of what you are after.
In short, I think it should be perfectly doable to accurately get the word that is clicked, even in longer paragraphs, but it certainly isn't very easy, and for longer pieces of texts, it may end up being very inefficient.
edit for mozilla/webkit browsers, you could do it like this:
$(document).ready(function() {
$("body").click(function(){
var s = window.getSelection();
s.modify('extend','backward','word');
var b = s.toString();
s.modify('extend','forward','word');
var a = s.toString();
s.modify('move','forward','character');
alert(b+a);
});
});
example: http://jsfiddle.net/niklasvh/rD2uE/
It doesn't work on IE <= 8 though, you'd probably need to do a different kind of solution using the IE selections.
Post a Comment for "Jquery Capture The Word Value"