mongmongmong seesee
mongmongmong seesee

Reputation: 107

javascript onclick scroll to div on middle page?

javascript onclick scroll to div on middle page ?

I tested my code, but not scroll to middle page,

How to scroll to middle of page ?

https://jsfiddle.net/ytgu1fbo/2/

<script>
function scroll_to_contact_form_fn() {
    $('html, body').animate({
        scrollTop: $("#myForm").offset().top -500
    }, 200);
}
</script>

i Tried this code too but not scroll ^^

<script>
function scroll_to_contact_form_fn() {
    $('html, body').animate({
        scrollTop: $("#myForm").offset().middle
    }, 200);
}
</script>

Upvotes: 1

Views: 1367

Answers (1)

Nickey
Nickey

Reputation: 1381

Hi you can do something like this https://jsfiddle.net/ytgu1fbo/7/

Basically first you calculate the total scroll height. Then you go to the middle of the page and then up for the half of your visible area.

var body = document.body,
    html = document.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight, 
                   html.clientHeight, html.scrollHeight, html.offsetHeight );
$('html, body').animate({
    scrollTop: height/2 - window.innerHeight/2
}, 200);

I hope that I understood what you wanted to do correctly

Upvotes: 1

Related Questions