Cameron Cameron - 7 months ago 11
Javascript Question

jQuery scroll a div up and down using two buttons

I have a simple set of two buttons that when hovered should make a div move up and down to simulate a scrolling effect:

$("#down").hover(function () {

$('.scroll').animate({ "marginTop": "-=50px" }, "fast");

});

$("#up").hover(function () {

$('.scroll').animate({ "marginTop": "+=50px" }, "fast");

});


However I have two issues:

1.) I need it to stop when it gets to the end and then hide the button so they know they've reached the end

2.) It needs to scroll continually when the user has their mouse over, currently it does it just once on mouse over and then runs it again on mouse leave.

3.) If the content does not exceed the parent element height then hide both buttons as we don't need to scroll it.

Can anyone help?

I was thinking that perhaps 1 could be solved by finding out the height of the scroll panel and judging its offset to its parent element that holds it and creates the framed view?

Thanks

Answer

This code still need some debugging, but you can get the idea in it:

$(document).ready(function() {

    if ($('.content').height() > $('.container').height()) {
        $("#down").hover(function () {
            animateContent("down");
        }, function() { $('.content').stop(); });

        $("#up").hover(function () {
            animateContent("up");
        }, function() { $('.content').stop(); });
    }
});

function animateContent(direction) {  
    var animationOffset = $('.container').height() - $('.content').height();
    if (direction == 'up') {
        animationOffset = 0;
    }

    $('.content').animate({ "marginTop": animationOffset + "px" }, "fast");
}

Code: http://jsfiddle.net/a89DF/6/