Skip to the content.

cursor-nearby-elements

This package helps you find elements near cursor position

Visitors GitHub issues GitHub forks GitHub stars GitHub license

Table of contents

Changelog

Features

Installation

npm i cursor-nearby-elements

Getting Started

Import the method using import syntax and save the output of nearbyElements method in some variable.

import {nearbyElements} from cursor-nearby-elements;
const nearby = nearbyElements();

Visual representation of the parameters

Multiple points on radius

Note: Arguments inside [ ] are optional

nearbyElements ([directions,offset])

This method helps you to set the parameters for calculations that are carried out for finding nearby elements

nearby (event, [ predicate, modifier, offsetPoints, shouldSkipAngle ])

This method takes an event object as a mandatory argument and returns an Array of DOM Elements

Example

nearby function

function handleMouseMove(e) {
  //filtering nearby elements since I don't want my container element to be returned as nearby element
  //I only want elements with class targets
  const predicate = (el) => {
    return !el.classList.contains("App") && el.classList.contains("targets");
  };

  //null checks are already present so you won't get null or undefined elements
  const modifier = (el) => {
    if (el.style) el.style.backgroundColor = "red";
    return el;
  };

  //you can scale your region by providing a larger fraction for offset also
  const offsetPoints = [0, 0.25, 0.5, 0.75, 1, 1.215];

  //skip points on X and Y axis
  const shouldSkipAngle = (rad, index) => {
    return index % 2 === 0;
  };

  //all the args except event object are optional
  const myelements = nearby(
    e,
    predicate,
    modifier,
    offsetPoints,
    shouldSkipAngle
  );
}

Extras

1. If you are using framework like react: You should not modify DOM elements directly, you must change state or use refs. Since this package returns a DOM element object, what you can do is store the ref of all the target elements in a dictionary/map like object with key as stringify version of ref and value as the ref object itself using react-ref-compare package.

2. I have a codesandbox setup for testing and demo of the package, you can playaround with the code there to get a better understanding of the package

cursor-nearby-elements DEMO