JQuery Image Hover Effect

I am trying to achieve this effect using jQuery.

I wrote part of the code, but this is a mistake (go to the lower right order and you will see).
check him

Basically, if there is a jQuery plugin already built that you know about, I would be very happy to use it, if not, then any help with my formula will be appreciated. This is what I get for not paying attention to Maths classes :)

Thanks in advance.

Mikel

+6
javascript jquery css image hover
source share
2 answers

All in all, I think this is what you are looking for:

$.fn.sexyImageHover = function() { var p = this, // parent i = this.children('img'); // image i.load(function(){ // get image and parent width/height info var pw = p.width(), ph = p.height(), w = i.width(), h = i.height(); // check if the image is actually larger than the parent if (w > pw || h > ph) { var w_offset = w - pw, h_offset = h - ph; // center the image in the view by default i.css({ 'margin-top':(h_offset / 2) * -1, 'margin-left':(w_offset / 2) * -1 }); p.mousemove(function(e){ var new_x = 0 - w_offset * e.offsetX / w, new_y = 0 - h_offset * e.offsetY / h; i.css({ 'margin-top':new_y, 'margin-left':new_x }); }); } }); } 

You can test it here .

Noticeable changes:

  • new_x and new_y should be divided by the height / width of the images, not the width / width of the container, which is wider.
  • this already a jQuery object in the $.fn.plugin function, there is no need to wrap it.
    • i and p were also jQuery objects, no need to wrap them.
  • No need to bind mousemove to the mouseenter (which mousemove ) mousemove will only appear when you're inside anyway.
+7
source share

Nick Craver beat me to answer for about 10 minutes, but this is my code for this, using background-image to put the image in place of the actual image.

 var img = $('#outer'), imgWidth = 1600, imgHeight = 1200, eleWidth = img.width(), eleHeight = img.height(), offsetX = img.offset().left, offsetY = img.offset().top, moveRatioX = imgWidth / eleWidth - 1, moveRatioY = imgHeight / eleHeight - 1; img.mousemove(function(e){ var x = imgWidth - ((e.pageX - offsetX) * moveRatioX), y = imgHeight - ((e.pageY - offsetY) * moveRatioY); this.style.backgroundPosition = x + 'px ' + y + 'px'; }); 

There are a huge number of variables, because the mousemove event mousemove should be as efficient as possible. This is a bit more restrictive because you need to know the sizes, but I think the code can be easily changed to work with img , for which the size can be easily calculated.

A simple demonstration of this: http://www.jsfiddle.net/yijiang/fq2te/1/

+3
source share

All Articles