I'm using this code to show a translation of the text in a span as a tooltip on click:
$(document).ready(function () {
$('.word').tooltipster({
trigger: 'click',
touchDevices: true,
content: 'Loading...',
functionBefore: function (origin, continueTooltip) {
continueTooltip();
if (origin.data('ajax') !== 'cached') {
$.ajax({
type: 'GET',
url: 'translate.php?word=' + $(this).text(),
success: function (data) {
origin.tooltipster('content', data).data('ajax', 'cached');
}
});
}
}
});
});
I would like to also show (trigger) the tooltip when text is selected and send the selected text as a url parameter like this: translate.php?word={selected text}
. This needs to work even though the text is in separate spans, partial text of a span, not in a span, etc; basically any text selected on the page.
I found the code below (jsfiddle), but I can't figure out how to integrate it into what I already have:
$('div').mouseup(function() {
alert(getSelectedText());
});
function getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
Here is what my html looks like:
<div class="container">
15, 16. (<span class="word">a</span>)
<span class="word">Paano</span>
<span class="word">napaibig</span>
<span class="word">ni</span>
<span class="word">Esther</span>
<span class="word">ang</span>
<span class="word">hari</span>? (
<span class="word">b</span>)
<span class="word">Bakit</span>
<span class="word">maaaring</span>
<span class="word">naging</span>
<span class="word">hamon</span>
<span class="word">kay</span>
<span class="word">Esther</span>
<span class="word">ang</span>
<span class="word">mga</span>
<span class="word">pagbabago</span>
<span class="word">sa</span>
<span class="word">buhay</span>
<span class="word">niya</span>?<br>
15
<span class="word">Nang</span>
<span class="word">panahon</span>
<span class="word">na</span>
<span class="word">para</span>
<span class="word">iharap</span>
<span class="word">si</span>
<span class="word">Esther</span>
<span class="word">sa</span>
<span class="word">hari</span>
...