简体   繁体   中英

jQuery to center div on screen

I was wondering if i could get a little help modifying a piece of jQuery i have that animates the position of a div on the screen. Here it is:

        <script type="text/javascript">
        (function ($) {
            $(function () {
                var offset = $("#<%= pnlMessageForm.ClientID %>").offset();
                var topPadding = 15;
                $(window).scroll(function () {
                    if ($(window).scrollTop() > offset.top) {
                        $("#<%= pnlMessageForm.ClientID %>").stop().animate({
                            marginTop: $(window).scrollTop() - offset.top + topPadding
                        });
                    } else {
                        $("#<%= pnlMessageForm.ClientID %>").stop().animate({
                            marginTop: 0
                        });
                    };
                });
            });
        })($telerik.$);
    </script>

It works great, except when i am scrolling already down the page a bit. It only adjusts its position when a scroll is performed. I need it to start out in the center... Is there a easy modification here that someone could show me that would accomplish this?

Thank you

You can programmatically trigger the scroll event after binding it.

This can be done using the shotcut method .scroll() or the .trigger() method

$(window).scroll(function () {
    ...
}).trigger('scroll'); // trigger the "scroll" event    

or

$(window).scroll(function () {
    ...
}).scroll(); // trigger the "scroll" event

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM