10

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.

context menu

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.

Sriharsha
  • 2,373
  • 1
  • 16
  • 20
  • 2
    Have you taken a look at `window.getSelection()`? You could write your own listener for it, and the `selectionchange` event is supported on IE and Chrome/Safari (though not Firefox or Opera) – hotforfeature Jul 29 '14 at 15:09
  • for not supported browsers u can add selection check via setInterval (its bad for perfomance, but will fix) – El' Jul 29 '14 at 15:20

1 Answers1

20

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.

wrxsti
  • 3,434
  • 1
  • 18
  • 30
  • better to use event selectionchange, but for unsupported browsers use other events: mouseup, drugend, touch, keyup (for shift+right and other keyboard methods of selection modifications, but only for unsupported browsers ) – El' Jul 29 '14 at 15:23
  • See the above comment – wrxsti Dec 16 '16 at 03:33
  • @Abhishek Check this out: https://stackoverflow.com/questions/11300590/how-to-captured-selected-text-range-in-ios-after-text-selection-expansion – wrxsti Dec 27 '17 at 18:11