1

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>
2
  • 1
    It looks like it's working for me. Is your problem that it's scrolling to the wrong spot, or that it's not scrolling at all? If it's not scrolling at all, what browser are you using? Commented Feb 3, 2016 at 16:38
  • 1
    just remove the -500. Commented Feb 3, 2016 at 16:59

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.