Tutorial

Get Hover Direction with MooTools

Here is the quick MooTools tip to get the Hover direction. Here Hover direction refers to the side from where you have hovered that element.

First of all I would like to thanks Caspar, for this logic at here. I have modified this script to make it work with MooTools. That script was compatible with jQuery so as a MooTools Fan I love to create any effects in MooTools and here I have done the same.

Have a look at below code block, in this I have used Event delegation in MooTools. So in this way I can have event binded to multiple elements and elements which will added later using AJAX.

HTML Code

[cc lang=”html”]

Hover Me
Hover Me
Hover Me

[/cc]

JavaScript Code

[cc lang=”js”]
window.addEvent(‘domready’, function(){

var obj = document.id(‘hero_unit’);

obj.addEvent(‘mouseover:relay(div)’, function(event){
// Get Height and Width of the Current Div
var w = this.getCoordinates().width;
var h = this.getCoordinates().height;

/** calculate the x and y to get an angle
to the center of the div from that x and y. **/
/** gets the x value relative to the
center of the DIV and “normalize” it **/

var positions = this.getPosition();

//alert(positions[0]);
var x = (event.page.x – positions.x – (w/2)) * ( w > h ? (h/w) : 1 );
var y = (event.page.y – positions.y – (h/2)) * ( h > w ? (w/h) : 1 );

var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180 ) / 90 ) + 3 ) % 4;

switch(direction) {
case 0:
this.innerHTML = ‘From Top’;
break;
case 1:
this.innerHTML = ‘From RIGHT’;
break;
case 2:
this.innerHTML = ‘From BOTTOM’;
break;
case 3:
this.innerHTML = ‘From LEFT’;
break;
}

});

});
[/cc]

Now its time to see some code in action, follow the article for the link to live demo page.

Demo

Get Hover Direction with MooTools

If you like this demo, please consider sharing this with your friends. And yes subscribe to our rss feed, like us on facebook and follow us on twitter to get latest updates from us.

Shares:

Leave a Reply

Your email address will not be published. Required fields are marked *