Question

I've looked at several tutorials online and a few similar questions on SO but not been able to work out how to make the screen autoscroll left and right so that my #sheep stays in the centre of the screen.

I'm using javascript and jquery to move a simple div across the screen.

Here's my jsfiddle

http://jsfiddle.net/JosephByrne/CkkVr/

What's the best method of making the screen follow my div?

Was it helpful?

Solution

I think you're trying to move the wrong element left/right. I think you need to leave your sheep in the middle of the screen then move the background.

Something like:

var walkLeft = function() {
    $('#background').animate({left:"-=10px",top:"-=2px"}, 100);
    $('#background').animate({left:"-=10px",top:"+=2px"}, 100);
};

var walkRight = function() {
    $('#background').animate({left:"+=10px",top:"-=2px"}, 100);
    $('#background').animate({left:"+=10px",top:"+=2px"}, 100);
};

http://jsfiddle.net/CkkVr/22/ (you'll need to "jump right" to see the sheep), but you get the general idea!

OTHER TIPS

You need something similar to this:

function scrollContainer() {
    var $sheep = $("#sheep");
    $("body").scrollLeft($sheep.position().left + $sheep.width());
}


That utilizes jQuery's scrollLeft() function as well as the position() function (on the sheep).


You just need to keep messing with the math until it works out properly...

I've implemented it on the "jump" functions here: http://jsfiddle.net/Dxe8a/11/

function scrollContainer() {
    var $sheep = $("#sheep");
    var $body = $("body");
    var windowWidthOver2 = ($(window).width()/2);
    var pos = $sheep.position().left + windowWidthOver2 - $sheep.width() - 80;
    if($body.width() <= (pos + windowWidthOver2 - $sheep.width() - 80)) {
        $body.width($body.width() + windowWidthOver2);
    }
    $body.scrollLeft(pos);
}

You should alter it so that it looks a bit better, but at least it follows your sheep somewhat.

P.S. it works better in fiddle if you view it in "/show": http://jsfiddle.net/Dxe8a/11/show

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top