
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.
$(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.
Post A Comment:
0 comments: