Blogger Ever

Trigger function on mouse around an element using jQuery

Trigger a function when mouse moves in a radius around the element using jQuery.

Have you ever noticed in charts when you move mouse around a point it shows the tooltip. Write now I am into SVG charts and may publish a blog post about that in upcoming week. The challenge was to show that tooltip when user moves the mouse around that specific point. This post is not about SVGs so I am going to use HTML elements to demonstrate.
See the Pen You are nearby by Mohammad Hamza Dhamiya (@hamzadhamiya) on CodePen.
All I've done is created a fake region around the box. Each element have two position, first is relative to its offset parent and other one is relative to the DOM. To create a region around that block, just get those offset position relative to DOM then connect them with your mouse movement.

$(function() {
  // The element
  var elem = $('.box'),
    distance = 50; // The distance of trigger.  
  $('body').mousemove(function(e) {
    if (isAround(elem, distance, e)) {
      elem.text('You are around');
    } else {
      elem.text('You are not around');

This is the first step, on every mouse move you are going to test a condition. Well, isAround() returns true if mouse is around the box. First argument is the elem which is the element, second is the distance or radius around around it and third is the object that will help to get the position of the mouse - passed from mousemove function.

function isAround(element, radius, mouse) {
  var elemTop = element.offset().top - radius,
    elemLeft = element.offset().left - radius,
    elemWidth = elemLeft + element.outerWidth() + (2*radius),
    elemHeight =elemTop +  element.outerHeight() + (2*radius),
    mouseLeft = mouse.pageX,
    mouseTop = mouse.pageY;
  console.log(elemTop + ' ' + elemHeight + ' ' + mouseTop)
  return (mouseLeft > elemLeft && mouseLeft < elemWidth && mouseTop > elemTop && mouseTop < elemHeight)
 With simple maths we created a region and finally, isAround() function returns four boolean values, if all are true then if condition will proceed. These four conditions relates the position of mouse with the region around box.

2013-2016 Copyright Blogger E\ver . Coded, managed and founded by Mohammad Hamza (@hamzadhamiya) . Hosted on Blogger and fonts used are Raleway and Open Sans.