How To Make A Scrollable Div Scroll On Click And Mouseover Using Jquery
Using the markup below how would I get the '#content' div to scroll up or down when I click or hover over the '#scrollUp' or '#scrollDown' anchor tag. Scrolling should be smooth pr
Solution 1:
You can use jQuery's animate function to accomplish a smooth-scrolling effect on click or mouseover:
var step = 25;
var scrolling = false;
// Wire up events for the 'scrollUp' link:
$("#scrollUp").bind("click", function(event) {
    event.preventDefault();
    // Animates the scrollTop property by the specified// step.
    $("#content").animate({
        scrollTop: "-=" + step + "px"
    });
}).bind("mouseover", function(event) {
    scrolling = true;
    scrollContent("up");
}).bind("mouseout", function(event) {
    // Cancel scrolling continuously:
    scrolling = false;
});
$("#scrollDown").bind("click", function(event) {
    event.preventDefault();
    $("#content").animate({
        scrollTop: "+=" + step + "px"
    });
}).bind("mouseover", function(event) {
    scrolling = true;
    scrollContent("down");
}).bind("mouseout", function(event) {
    scrolling = false;
});
functionscrollContent(direction) {
    var amount = (direction === "up" ? "-=1px" : "+=1px");
    $("#content").animate({
        scrollTop: amount
    }, 1, function() {
        if (scrolling) {
            // If we want to keep scrolling, call the scrollContent function again:scrollContent(direction);
        }
    });
}
Working example: http://jsfiddle.net/andrewwhitaker/s5mgX/
(You'll have to disable the mouseover and mouseout events to see the effects of the click event handler properly)
How it works:
- Uses the animatefunction mentioned above to scroll smoothly by a specified amount on click.
- Uses a flag to enable continuous scrolling on when the link's mouseoverevent handler is called, and disable scrolling when the link'smouseoutevent handler.
- When scrollContentis called, if thescrollingflag is stilltrueafter the animation is completed, animate again in the same direction. The callback function parameter ofanimateallows us to take an action after animation has completed.
Solution 2:
Try using JavaScript instead of jQuery for this task. Google the function scrollBy() as in window.scrollBy()
Post a Comment for "How To Make A Scrollable Div Scroll On Click And Mouseover Using Jquery"