Search code examples
jqueryimagedraggablejsfiddlejquery-slider

Jquery Image Slide. Zoom out


I am making a banner were you can zoom the image with the jquery slide function and were you can drag the image.

Its working perfect except for 1 thing. When you zoom in the image with the slide under the image it works perfect. You can drag the image were you want. But when you want to zoom out again with the slide function. The image is moving away to the top and the left.

The image have to stay in de div. So when I zoom out the image need to stay in the div.

For that code i use:

jQuery:

var previousValueL = 30;
var previousValueT = 45;

2 vars on the top of the jQuery. I got 30 and 45 because. The the image got a margin-left from 30px and a margin-top from 45px.

        if (sliderValue < previousValueL) {
             var l;
             l = $img.position().left;
             if (l < 30) l = l + (previousValueL - sliderValue);
             $img.offset({
                 left: l
             });
         }
         previousValueL = sliderValue;

        if (sliderValue < previousValueT) {
             var t;
             t = $img.position().left;
             if (t < 45) t = t + (previousValueT - sliderValue);
             $img.offset({
                 top: t
             });
         }
         previousValueT = sliderValue;

This Code is for when you zoom out.

You can also use this example:
http://jsfiddle.net/DennisBetman/tnaGA/

Hope somebody can help me,

Dennis.


Solution

  • One of the problems is the use of position. Position returns the coordinates of the element relative to its parent. The parent may have an offset of its own. So setting the the offset to the coordinates relative to the parent may cause weird positions.

    I changed your code to use offset. http://jsfiddle.net/tnaGA/51/

        if (sliderValue < previousValueL) {
             var l;
             l = $img.position().left;
             if (l < 30) l = $img.offset().left+ (previousValueL - sliderValue);
             $img.offset({
                 left: l
             });
         }
         previousValueL = sliderValue;
    
        if (sliderValue < previousValueT) {
             var t;
             t = $img.position().left;
             if (t < 45) t = $img.offset().top + (previousValueT - sliderValue);
             $img.offset({
                 top: t
             });
         }
    

    I still don't completely like the result yet because the image kind of jumps in its size, so that sometimes some black of the background is visible. I don't know why that is happening right now.