Tiny Positioning Engine In JavaScript – nanopop

Category: Javascript , Recommended | May 25, 2020
Author:Simonwep
Views Total:158 views
Official Page:Go to website
Last Update:May 25, 2020
License:MIT

Preview:

Tiny Positioning Engine In JavaScript – nanopop

Description:

nanopop is a super tiny alternative to the Popperjs library that provides a minimal, high-performance way to position elements like tooltips, popovers, etc.

How to use it:

1. Install & import the nanopop as a module.

# Yarn
$ yarn add nanopop
# NPM
$ npm install nanopop --save
import {NanoPop} from 'https://cdn.jsdelivr.net/npm/nanopop/lib/nanopop.min.mjs'

2. Create reference and popper elements on the page.

<div class="reference"></div>
<div class="popper">
  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M12 0c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm3 8h-1.35c-.538 0-.65.221-.65.778v1.222h2l-.209 2h-1.791v7h-3v-7h-2v-2h2v-2.308c0-1.769.931-2.692 3.029-2.692h1.971v3z"/></svg>
</div>

3. The proper element must be fixed positioned.

.popper {
  position: fixed;
  /* more styles here */
}

4. Initialize the NanoPop library and done.

const reference = document.querySelector('.reference');
const popper = document.querySelector('.popper');
const nanopop = new NanoPop(reference, popper);

5. Update the position of the popper element. Possible positions & variables:

  • top
  • right
  • bottom
  • left
  • start
  • middle
  • end
nanopop.update({
  position: 'right-end'
});

6. Config the library with the following parameters:

const options = {
      // set this to TRUE in case there's no non-clipping position, want to apply the wanted position forcefully
      forceApplyOnFailure: false,
      // container element
      container: document.documentElement.getBoundingClientRect(),
      // default position
      position: 'bottom-start';
      // the space between reference and poper elements
      margin: 8,
      // in case the variant-part (start, middle or end) cannot be applied you can specify what (and if) should be tried next.
      variantFlipOrder: {
        start: 'sme', // In case of -start try 'start' first, if that fails 'middle' and 'end' if both doesn't work.
        middle: 'mse',
        end: 'ems'
      },
      // the same as variantFlipOrder, but if all variants fail you might want to try other positions.
      positionFlipOrder:  {
        top: 'tbrl', // Try 'top' first, 'bottom' second, 'right' third and 'left' as latest position.
        right: 'rltb',
        bottom: 'btrl',
        left: 'lrbt'
      }
}
const nanopop = new NanoPop(reference, popper, options);

 

You Might Be Interested In:


Leave a Reply