viewport-focus

1.0.2 • Public • Published

viewport-focus

Given a list of DOM elements, return the one closest to the focal point of the browser viewport

Demo

Table of Contents

Install

npm install viewport-focus --save
yarn add viewport-focus

Install a document.scrollingElement polyfill for older browser support

Usage

<script src="//unpkg.com/underscore@1.8.3/underscore.js"></script>
<script src="//unpkg.com/viewport-focus/dist/viewport-focus.js"></script>
<script>
  var getViewportFocus = window.viewportFocus;
  var elements = document.querySelectorAll('section');
  // jQuery: var elements = $('section')[0];
 
  function setClosestEl() {
    var closestEl = getViewportFocus(elements);
    // closestEl is at your command
  }
 
  setClosestEl();
  window.addEventListener('scroll', _.throttle(setClosestEl, 100));
</script>
});

In the Future

import throttle from 'lodash/throttle';
import getViewportFocus from 'viewport-focus';
 
document.addEventListener('DOMContentLoaded', () => {
  const elements = document.querySelectorAll('section');
 
  function setClosestEl() {
    const closestEl = getViewportFocus(elements);
    // closestEl is at your command
  }
 
  setClosestEl();
  window.addEventListener('scroll', throttle(setClosestEl, 100));
});

API

closestToMiddle(elements: Array|NodeList, offset?: String) => HTMLElement

offset

  • bounds - top and bottom are compared to the viewport middle — default
  • middle - element height is compared to viewport middle

Contribute

Pull requests accepted!

License

ISC LICENSE
Copyright © 2017 Push the Red Button

Readme

Keywords

none

Package Sidebar

Install

npm i viewport-focus

Weekly Downloads

1

Version

1.0.2

License

ISC

Unpacked Size

12.9 kB

Total Files

6

Last publish

Collaborators

  • pushred