I have some text inside a < p > element, and need to find the word that was double tapped.
I am using a double tap jquery plugin ( https://gist.github.com/attenzione/7098476 ) which works great on detecting the event, but I don't know how to get the word that is under it.
How can I get it?
Added what I have so far:
$("p").on('doubletap',function(event){
alert ("double tap"); // event is working
var sel = (document.selection && document.selection.createRange().text) || (window.getSelection && window.getSelection().toString());
alert ("sel "+sel); //<-- not working
});
If you want to only get the word you double tapped on, you should use span
tags around each word. That way you add the double tap event listener on p > span
and you can fetch the word using $(clickedElement).text();
.
EDIT: Add example code based on code given on Fiddle:
$(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").dblclick(function(event) {
var res = $(this).text();
console.log ("sel "+res);
});
});
There is one similar question for selecting word on single click. Use the mouse to select only one word in text jquery
You can change the event from click to dbclick
like this : http://jsfiddle.net/tejashsoni111/EHCN6/92/
$(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("dbclick", function (event)
{
event.stopPropagation();
SelectText($(this));
});
});
function SelectText(element)
{
var doc = document,
text = element.get(0),
range,
selection;
if (doc.body.createTextRange)
{
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
}
else if (window.getSelection)
{
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
Update
Returned the selected text. Check the updated fiddle : https://jsfiddle.net/tejashsoni111/mzx6zL65/2/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.