javascriptjquerybackground-position

Dynamically change css backgroundPosition left AND top via Jquery


I'm a new programmer and English is not my mother language, so please forgive me in advance for both programming and English mistakes.

Here is what I want to do: I have a div tag that contains an image and a table (outside this div tag). Via jquery i'm trying to archieve a 'cropping effect' so I make my table draggable and while dragging I copy the image and set it as background on my table. Now I would need to be able to set dynamically the background position of the image in the table so when dragging the picture appears to be still. The cropping effect is archived by changing (lowering) opacity on the original image. Note that I don't need to create a sellection or anything similar. The table is created first with a given size. After this is done, the table is dragged over the image creating the cropping effect.

Here is my problem: when I set the position for the background image via jquery(.css), it doesn't change the top position and the left position doesn't work as expected.

Let's see the javascript code:

<script type="text/javascript">

$(function() {
    $("#myTable").draggable({
        drag:function() {
            //$("#myTable").css("opacity", "0.6");
            var $img = $("img").clone();
            var $src = $img.attr('src');
            $("#myTable").css("background-image", 'url(' + $src + ')');
            $position = $("#myTable").position();

            $("#myTable").css({
                backgroundPosition: -parseInt($position.left) + -parseInt($position.top)});
        },
        stop:function() {
            //$("#myTable").css("opacity", "1.0");
            $("#div1").css("opacity", "0.6");
        }
    });
});

</script>

The position of the background is not properly set now but it doesn't matter too much at the moment. I Just hope there is a way to change dynamically the top position too and I'll worry about the math later. Also I hope it's clear enough. Kind regards,

Irene


Solution

  • The background-position CSS property can take two arguments, separated by a space character:

    $("#myTable").css("backgroundPosition", (-parseInt($position.left)).toString()
        + "px " + (-parseInt($position.top)).toString() + "px");