Hi I want to have a ability to show the custom menu (or context menu) when a user selects some text much simillar to what medium provides.
How do implement this something like this? I am aware of native/jquery context menu plugins, but how do I know when the user selects the text? Browser's onselect seems to be supported only on input elements.
Selector = {}; x. Selector. getSelected = function() { var t = ''; if (window. getSelection) { t = window.
getSelection() Method in JavaScript. The window. getSelection() method in JavaScript allows us to get the text highlighted or selected by the user on the screen. This method returns an object that contains information related to the text highlighted on the screen.
Here is a pretty basic listener for .getSelection()
: DEMO
if (!window.x)
{
x = {};
}
x.Selector = {};
x.Selector.getSelected = function()
{
var t = '';
if (window.getSelection)
{
t = window.getSelection();
}
else if (document.getSelection)
{
t = document.getSelection();
}
else if (document.selection)
{
t = document.selection.createRange().text;
}
return t;
}
$(document).ready(function()
{
$(document).bind("mouseup", function()
{
var selectedText = x.Selector.getSelected();
if(selectedText != '')
{
alert(selectedText);
}
});
});
Instead of an alert, simply make your popup/toolbar visible. Hope this helps!
EDIT I changed the demo to show one possible way to show the popup menu/toolbar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With