npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

selection-menu

v3.4.2

Published

Display a context menu after the user selects text

Downloads

449

Readme

SelectionMenu

NPM version Build status Dependency Status DevDependency Status License Downloads

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.

Live Demo

SelectionMenu screencast

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.

History

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.

Features and differences from the original

  • 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

Usage

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 was hidden or had display: none, we'll show and hide it appropriately.

  • menuHTML (string): DEPRECATED - use content 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 to Infinity.

  • id (string, optional): The ID of the menu element which is inserted. Defaults to selection-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.

Properties

  • 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)

Methods

  • hide(hideSelection=false) - hide the menu, optionally clearing the text selection as well. Useful at the end of the click handler.

Example

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) {
    ...
  }
});

Browser compatibility

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.

Known issues

  • 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.

Upcoming features

  • 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.

License and copyright

Maintainer: Dan Dascalescu (@dandv)

Copyright (C) 2015 iDoRecall, Inc.

The MIT License (MIT)