David
David

Reputation: 65

css background image movement with mouse hover

I would like to have a element in my webpage that has a background image that when the mouse hovers over it, the background image will move corresponding the mouse movement like in this website:

http://www.kennedyandoswald.com/#!/premiere-screen

I have this HTML code:

<section id="home" data-speed="3" data-type="background"></section>

I can control the speed at which the background image scrolls with the 'data-speed="3"' but I was wondering if there is any code similar to 'data-speed' that would use the mouse movement to move the background image instead of the scrolling.

Upvotes: 0

Views: 10211

Answers (2)

Max
Max

Reputation: 1478

If you want to roll your own just use a combination of the jQuery mousemove function in combination with CSS3 transforms. Something along the lines of this:

$( "#target" ).mousemove(function( event ) {
var msg = "Handler for .mousemove() called at ";
msg += event.pageX + ", " + event.pageY;
console.log( "<div>" + msg + "</div>" );
$("#movingobject").css('transform', 'translate(' + event.pageY /4 + 'px,' + -event.pageX /4+ 'px)');
});

I made an jsfiddle poc where you can see it in action. Of course you would have to adjust the movement function to your specific needs.

http://jsfiddle.net/ZmZhw/

Upvotes: 1

Rahul
Rahul

Reputation: 5774

There are many JS libraries that help you to achieve this effect. I personally used this one a lot : http://wagerfield.github.io/parallax/

This is very easy to use but achieving the same effect may take some trial and error stuff.. But that's worth it!

Another one which is not as complex as above yet powerful is : http://stephband.info/jparallax/

You can try both and see which one you find the best for your use..

Upvotes: 6

Related Questions