Reputation: 46479
I need to show a tooltip for a selected/highlighted text in order to allow users to make it italic/bold/normal. I will probably wrap that word in a span with related class for styling, however I need to figure out how to show such tooltip and process selected word so I can perform actions on it. I was trying to find a library that does this, but so far no luck.
Image below demonstrates what I'm after:
Where users select word Works and tooltip appears.
Upvotes: 1
Views: 694
Reputation: 140
Try this, need JQuery
https://jsfiddle.net/Ripper1992/L0suavjd/
Script
$(document).ready(function(){
$('span').mouseenter(function(){
var span = $(this);
$('.tooltip').fadeIn();
})
$('.tooltip').mouseleave(function(){
var span = $(this);
$('.tooltip').fadeOut();
})
$('a').click(function(){
var classe = $(this).attr('class');
var spanClass = $('span').removeClass();
$('span').addClass(classe);
});
})
HTML
<div>The Piano <span class=''>Works</span> is like a live</div>
<div class="tooltip">
<a href="#" class="bold">Bold</a>
<a href="#" class="italic">Italic</a>
<a href="#" class="normal">Normal</a>
</div>
CSS
.tooltip{
display: none;
border: solid 1px #CCC;
width: 130px;
text-align: center;
position: absolute;
}
.bold{
font-weight: bold;
font-style: normal;
}
.italic{
font-weight: normal;
font-style: italic;
}
.normal{
font-weight: normal;
font-style: normal;
}
Upvotes: 1
Reputation: 53991
You can bind an event to the body's mouseup
handler and check to see if there's any text selected.
From here you can check whether the selection has any text and if it does, show the tooltip as desired.
Here's an example that wraps the selected text in a span which bolds and enlarges the text: http://jsbin.com/yezake/edit?js,output
const mouseUpHandler = function () {
const sel = document.getSelection();
if(!sel.toString()) {
$('.foo').contents().unwrap();
sel.removeAllRanges();
return;
}
const newNode = document.createElement('span');
newNode.className = 'foo';
const range = sel.getRangeAt(0);
range.surroundContents(newNode);
sel.removeAllRanges();
sel.addRange(range);
};
$('body').on('mouseup', mouseUpHandler);
With a little bit more time you could add your tooltip markup to this and show that when a selection is made. This is probably a very naive implementation but it's something to get you started if you want to roll your own.
Upvotes: 1
Reputation: 15941
The jQuery .select()
event handler should be what you are looking for. There's an example on the documentation page which you should be able to repurpose.
Positioning the...tooltip element may prove tricky, however. Might be worth a second question after you get the select event functional.
Upvotes: 1