Use The Mouse To Select Only One Word In Text Jquery
I am working on rails 4 project. I need to select only one word from a paragraph. Right now i am able to select the entire paragraph using the below code:
Solution 1:
May be some browsers doesn't support this code:
document.onclick = globalOnClickHandler;
functionglobalOnClickHandler() {
var s = window.getSelection();
s.modify('move','backward','word');
s.modify('extend','forward','word');
// alert(s.toString()); // you can get selected word
}
Solution 2:
I merged the two StackOverflow questions I linked to in the comment above with the code you provided. Here's the result in code and a JSFiddle:
$(document).ready(function()
{
var words=$("#yourTextContainer").text().split(' ');
$("#yourTextContainer").html("");
$.each(words, function(i,val)
{
//wrap each word in a span tag
$('<span/>').text(val +" ").appendTo("#yourTextContainer");
});
$("#yourTextContainer span").live("click",function(event)
{
event.stopPropagation();
SelectText($(this));
});
});
functionSelectText(element)
{
var doc = document,
text = element.get(0),
range,
selection;
if (doc.body.createTextRange)
{
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
}
elseif (window.getSelection)
{
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
Post a Comment for "Use The Mouse To Select Only One Word In Text Jquery"