简体   繁体   中英

Scroll to div on click (show div on center screen)

I have a question about a tiny JS that I have put at the bottom of the page. The script scrolls to another div when the user clicks on one div. On my website there is a contact button (example below).

<div id="contactbutton"></div>

When the user of the website clicks on this div, the page scrolls down to another div on the page with a contact form on it (example below).

<div id="contactform">
  <form>
    (form content here)
  </form>
</div>

I did that using the following JS code at the bottom of the page, that will scroll to the other div:

<script>
  $("#contactbutton").click(function() {
  $('html, body').animate({
  scrollTop: $("#contactform").offset().top
  }, 500);
  });
</script>

The code works perfect, but problem is that I have a fixed div header on my website that is on top of everything on the page. When the user scrolls to #contactform , a part of this contact form div is behind this header.

I am looking for a way to scroll to #contactform . But instead of scrolling all the way, I want it to scroll till it's a certain amount of pixels away from the top of the browser window so it will show below the header and not behind it.

I hope somebody can help me out! Thanks alot in advance.

Elmigo

You want to substract the height of your sticky header from the scroll distance, something like this ( #fixed-header is an id of your sticky header):

<script>
  $("#contactbutton").click(function() {
    $('html, body').animate({
      scrollTop: $("#contactform").offset().top - $('#fixed-header').outerHeight()
    }, 500);
  });
</script>

You could substract the height of your header so the scroll will stop a few pixels before your content leaving some spaces for the header

<script>
  $("#contactbutton").click(function() {
  $('html, body').animate({
     scrollTop: $("#contactform").offset().top - $('#header').height()
  }, 500);
  });
</script>

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