Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show custom menu on text selection

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.

like image 673
Sriharsha Avatar asked Jul 29 '14 15:07

Sriharsha


People also ask

How do you display the custom menu on text selection in HTML?

Selector = {}; x. Selector. getSelected = function() { var t = ''; if (window. getSelection) { t = window.

How do you highlight selected text in JavaScript?

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.


1 Answers

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.

like image 63
wrxsti Avatar answered Sep 22 '22 13:09

wrxsti