Paul Benbow
Paul Benbow

Reputation: 329

Scroll a div with Jquery

I have a click function that slides a contact form down from the top of the page and pushes the rest of the page down. I have an absolute position DIV which stays where it is currently and I need it to scroll down as if it didn't have an absolute position.

$("#contact-tab").toggle(function() {
    $('#contact-form-wrapper').slideToggle();
        // scroll #absolute DIV vertically the height of #contact-form-wrapper
    }, function() {
        $('#contact-form-wrapper').slideToggle();
        // scroll #absolute back to where it was
    });

#absolute {
    position: absolute;
    top: 500px;
}
#contact-form-wrapper {
    width:100%;
    height:370px;
    top:0;
}

Example: http://jsfiddle.net/benners/FV2sp/

Upvotes: 0

Views: 959

Answers (3)

Akram Berkawy
Akram Berkawy

Reputation: 5060

consider change the position method, anyway using progress callback can solve the problem but you should use version 1.8+ of JQuery.

$(document).ready(function() {
    $('#contact-form').hide();

    $("#contact-us").toggle(function() {
        $('#contact-form').slideToggle({
            progress:function(anime,progr,remain){
                $("#absolute").css('top',( $(this).height() + 150));
            }
        });
    }, function() {
        $('#contact-form').slideToggle({
            progress:function(anime,progr,remain){
                $("#absolute").css('top',( $(this).height() + 150));
            }
        });
    });

});

see updated jsFiddle.

Upvotes: 2

antony
antony

Reputation: 2893

You can change the absolute positioning of the element to position: relative. You can get the same behaviour as position: absolute except that obviously, it's positioned relative to it's parent element. Check out this fiddle http://jsfiddle.net/FV2sp/1/

Otherwise your other option is to place the absolutely positioned element inside your .content element. Then it will move as your .content element slides up and down.

Upvotes: 1

Mhche
Mhche

Reputation: 143

You can use that jquery so your div follow the scroll

$(function() {

var $mydiv   = $(".id-of-your-div"), 
$window    = $(window),
offset     = $mydiv.offset(),
topPadding = 15;

$window.scroll(function() {
    if ($window.scrollTop() > offset.top) {
        $mydiv.stop().animate({
            marginTop: $window.scrollTop() - offset.top + topPadding
        });
    } else {
        $mydiv.stop().animate({
            marginTop: 0
        });
    }
});

});

Place it on the bottom of your page or somewhere.

Upvotes: 0

Related Questions