Predict User Cursor Movements with this 500-Byte Javascript

You can do some really cool things with JavaScript and open source code makes the work even easier.

Premonish is one of the coolest libraries I’ve seen and it’s built with only 500 bytes of JavaScript. With this plugin, you can detect where the user’s mouse is moving and predict which element they’re heading towards.

This may sound like a complex idea but it’s fairly easy to implement. Not to mention this offers a ton of opportunity for developers to create some really cool effects such as pre-hover animations or dynamic layout effects.

Premonish library

You start by targeting an element on the page and defining how it’ll look when the user is moving towards that element.

All of the calculations are done on the backend with the Premonish library, so you don’t need to worry about the math or logic behind this.

Instead, you’re looking for a way to handle the prediction based on a confidence ranking of the user’s behavior. This is all passed into JavaScript, so you can write your own functions to handle the user behaviors.

Here’s an example snippet from the Premonish demo:

premonish.onIntent(({el, confidence}) => {
  // el is the expected DOM element
  // confidence is a score from 0-1 on how confident we are in this prediction.
});

The onIntent() method is baked into Premonish and it’s called whenever the library notices a user moving towards some element.

You can also use another method, onMouseMove(), which runs every time the cursor changes X/Y positions on the screen. This way you can see how Premonish is calculating the odds of user intent.

You can find a bunch of information in the main GitHub repo which includes simple code snippets to get you started. Initialization just requires a series of selectors or DOM elements that should be targeted.

How you actually use this plugin is totally up to you. This isn’t meant to be a complete solution, but rather a starting point to help you assume user intentions and build an experience around that.

Check out the live demo to see how this all works and to see a “debug mode” where you can watch how the prediction algorithm works in real time.

You can also share your thoughts and say thanks to the creator Matthew Conlen on his Twitter @mathisonian.

Debugging Premonish
WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail