SelectionMenu is a small, framework-agnostic JavaScript module that displays a custom context menu when the user selects text on the page.
This menu may offer a search feature, dictionary lookup, sharing on social media etc.
The only dependency is Tether.js for automatic positioning of the menu as the page is scrolled. Automated cross-browser testing with Selenium driven by Node.js gracefully provided by BrowserStack TBI.
The motivation for creating this module was having a sleek contextual selection mechanism in the Chrome extension for iDoRecall.
This module was inspired by Mathias Schäfer's work from 2011. It was brought up to date with modern browsers (Chrome, Firefox, Safari, Opera, IE9+) and the AMD module pattern, then revamped to use HubSpot's Tether library for better positioning. A neat trick, detecting the direction of the selection (forward vs. backward), was inspired by Xavier Damman's selection-sharer.
The idea and the implementation originally resemble the selection context menu on nytimes.com, but the script is way simpler and easier to integrate.
- Display the context menu near where the mouse button was released (the original always displayed the menu at the end of the selection, and selection-sharer displays it asymmetrically and always at the top of the selection)
- Pass any HTML for the context menu, and style it as you want
- The menu text is made unselectable (fixes a number of bugs in the original library)
- Supports minimum and maximum selection length (selection-sharer #10)
- Clicking outside the popover always closes the menu (fixes selection-sharer #11)
- Synthetic
onselect
event you can hook into - Dynamic menu depending on the content of the selection
- Selection and menu are preserved when scrolling the document via the scrollbar thumb
- The menu automatically repositions itself when it would be outside the top/bottom bounds of the visible viewport
Keyboard events are not handled, so that if the user wants to make fine adjustments to the selection with Shift+arrows, the menu will remain near the mouse cursor
Create an instance of SelectionMenu by calling new SelectionMenu
.
Pass an object literal with the following options:
-
container
(DOM element): The element where the copy event is observed. Normally that's the main text container. -
content
(string or DOM element): An HTML string for the menu, or a DOM element containing the menu. If the element washidden
or haddisplay: none
, we'll show and hide it appropriately. -
menuHTML
(string): DEPRECATED - usecontent
instead. A string of HTML for the menu, such as list of links. Typically obtained via.innerHTML
. TODO or get it from a textarea like Webix -
handler
(function): A handler function which is called when the user clicks on the menu. Use the passed click event to access the click link and respond to the user's action. -
minlength
(number, optional): Only display the menu if the selected text has at least this length. Defaults to 5 characters. -
maxlength
(number, optional): Only display the menu if the selected text is at most this long. Defaults toInfinity
. -
id
(string, optional): The ID of the menu element which is inserted. Defaults toselection-menu
. -
onselect
(function, optional): Custom event generated when the mouse/finger selection changes. Not generated when the selection is changed via the keyboard. Use it to customize the menu dynamically based on the contents of the selection:new SelectionMenu({ ... onselect: function (e) { this.menu.innerHTML = 'Selection length: ' + this.selectedText.length; } });
The menu styling is completely up to you. See selection-menu.css
in the demos
for a simple example, and iDoRecall-menu.less
for a more complex one.
menu
- the menu DOM element that SelectionMenu creates. Modify its innerHTML to adjust the menu on the fly according to the selection.selectionStartElement
,selectionEndElement
- DOM elements that the selection starts and end with (can be the same)
hide(hideSelection=false)
- hide the menu, optionally clearing the text selection as well. Useful at the end of the clickhandler
.
This observes mouseup events on the element with the ID article
. It inserts a menu
with two links which both have IDs to recognize them. In the handler function, the
selected text is read. Depending on the clicked link, the selected text is
looked up on Google or Bing.
new SelectionMenu({
container: document.getElementById('article'),
content: '<a id="selection-menu-google">Google it</a><a id="selection-menu-bing">Bing</a>',
handler: function (e) {
var target = e.target,
id = target.id,
selectedText = this.selectedText,
query = encodeURI(selectedText.replace(/\s/g, '+')),
searchURI;
if (id === 'selection-menu-google') {
searchURI = 'http://www.google.com/search?q=';
} else if (id === 'selection-menu-bing') {
searchURI = 'http://www.bing.com/search?q=';
}
location.href = searchURI + query;
}
});
To define menus more flexibly, use a hidden <div>
in your HTML, and pass its innerHTML
to SelectionMenu:
<div id="mymenu" hidden>
<ul>
<li>Option one
<li>Option two
</ul>
</div>
new SelectionMenu({
container: document.getElementById('article'),
menuHTML: document.getElementById('mymenu').innerHTML,
handler: function (e) {
...
}
});
The script uses the W3C DOM Range, which is available in modern browsers: IE9+, Chrome, Firefox, Safari, Opera. HubSpot's Tether library does not support IE8 for good reasons.
- The menu stays contained between the top and bottom boundaries of the container, but not between the left and right ones - #3
- Triple clicking to select a paragraph lands the menu below the selection in Chrome (this is a Chrome bug)
- Selecting table cells in Gecko browsers like Firefox doesn't position the menu where the selection has ended, due to multiple ranges being created.
- Automatically align left or right the menu arrow if it was created near the left or right border of the container. For now it's always centered.
Maintainer: Dan Dascalescu (@dandv)
Copyright (C) 2015 iDoRecall, Inc.
The MIT License (MIT)