Sébastien Gicquel
Sébastien Gicquel

Reputation: 4386

How to apply an effect depending on mouse move / position?

I have 3 buttons in position absolute :

.micro {
position:absolute;
}

#micro_1 {
left:1165px;
top:176px;
}

#micro_2 {
left:800px;
top:300px;
}

#micro_3 {
left:300px;
top:400px;
}

I would like to fade these 3 elements when the mouse move and come closer to one of the images. If mouse comes closer to image 1, images 1 is fading in. Images 2 and images 3 are fading out. And so on.

I can use jQuery to know the mouse position :

$('body').mousemove(function(e){
    $('#mouse_position').html("mouse position: x=" + e.pageX + "; y=" + e.pageY);

So i guess i can do some math to apply the effect.

What i've done :

$('body').mousemove(function(e){
        $('#mouse_position').html("mouse position: x=" + e.pageX + "; y=" + e.pageY);
        if (e.pageX > 394 && e.pageX < 533) {
            $('#lueur_video_1').fadeIn('slow');
            $('#lueur_video_2').fadeOut('slow');
            $('#lueur_video_3').fadeOut('slow');
        }

        if (e.pageX > 533 && e.pageX < 722) {
            $('#lueur_video_2').fadeIn('slow');
            $('#lueur_video_1').fadeOut('slow');
            $('#lueur_video_3').fadeOut('slow');
        }

        if (e.pageX > 722 && e.pageX < 1116) {
            $('#lueur_video_3').fadeIn('slow');
            $('#lueur_video_1').fadeOut('slow');
            $('#lueur_video_2').fadeOut('slow');
        }

Upvotes: 1

Views: 837

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191749

You can compare the mouse position (e.pageX / e.pageY) to the center of the image and set the opacity based on that. You can check where the elements are on the page with $("#micro_3").offset().

You will need to decide on the minimum and maximum distance for the fading on your own. When it's out of the maximum distance, opacity is 0 and inside the minimum, opacity is 1. For anything in between calculate the opacity by (Range - CurrentDistance) / Range.

Upvotes: 2

Related Questions