I'm trying to create something similar to Kindle's Word Wise and MacOS's Dictionary feature for a class. My goal is to allow the user double click on a word and view its definition. I'm very new to front end programming so I've been having a lot of trouble. I tried my best to research and try different methods to attain my desired end result, but I can't seem to get it to work.
So basically, every time a user double clicks on a word, a popover should appear with its definition. I wanted to find a way to create popovers on a click event, rather than hard coding in the popover attribute for every word.
Edit: Explaining a little more thoroughly...so if this is an example of how to add a popover on an element:
<a href="#" data-container="body"
data-toggle="popover" data-placement="top" data-content="Vivamus
sagittis lacus vel augue laoreet rutrum faucibus.">
Popover on top
</a>
...Is there a way to do this for every single word without having to add the individual element and attributes for each word?
This is the code I have so far.
function getSelectedText(){
var selectedText = '';
if (window.getSelection)
selectedText = window.getSelection();
return selectedText;
}
$(document).ready(function()
{
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
$(function () {
$('[data-toggle="popover"]').popover()
})
$('#selectable').on("dblclick", function () {
$('.selection').text(getSelectedText());
$('.is-selected').text(getSelectedText() != "");
});
$('#selectable').on('click',function (e) {
var text= getSelectedText();
$( '#selectable:contains(text)' ).replaceWith('<span data-toggle="popover" data-placement="bottom" data-content="testing popover>' + text +'</span>')
});
});
split()
function. Run that against your block of text, passing a space as the delimiter. Then loop over the resulting array, wrapping each "word" with the markup required to add the tooltip, appending to a new string (that will become the new block of content) as you go. – Patrick Q Feb 18 '20 at 13:43