Hello World
Hello World

Reputation: 1129

How make a draggable background without jquery UI?

Here's the code I've been trying to use:

$(document).ready(function() {
    var cc = 0;
    var drag = false;
    var bgp = 10;

    $('body').mousedown(function(){
        var bg =  Number($('body').css('background-position-x').replace(/[^-\d\.]/g, ''));
        bgp =+ bg;
        drag = true;
    });

    $('body').mouseup(function(){
        drag = false;
    });

    $('body').mousemove(function(e){
         $(this).mousedown(function(){
             cc =+ e.pageX;
         });
         if (drag==true) {
             cc =+ e.pageX;
         }

        function pan() {
             $('body').css('background-position',bgp+cc);
        } 

        if(drag==true) {
             pan();
        }
    });
});

it kind-of works but instead of changing the background position relative to how far you've moved your mouse, the background is positioned set according to how far your mouse is from the left edge of the page.

My idea of how to fix this is to set the background to original position+position of mouse when dragged-position of mouse when clicked. Though if there is a completely different way of solving this, that's also good.

I'm trying to teach myself jquery, so I'm open to criticism of my code

Upvotes: 0

Views: 496

Answers (1)

Ruben-J
Ruben-J

Reputation: 2693

Capture the start position of your mousedown action and your initial background-position(x and y):

var startX = event.pageX;
var startY = event.pageY;
var initialX = parseInt($('body').css('background-position-x'));
var initialY = parseInt($('body').css('background-position-y'));

In your mousemove event capture the difference between your startX and your movedX

var differenceX = startX - e.pageX;
var differenceY = startY - e.pageY;

Then add those differences to your initial background-position-x and y.

$('body').css('background-position-y', (initialY + differenceY));
$('body').css('background-position-x', (initialX + differenceX));

Upvotes: 3

Related Questions