Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery - Scroll element to the middle of the screen instead of to the top with an anchor link
    primarykey
    data
    text
    <p>I'm building a one-page site with a fixed-positioned navigation bar which scrolls smoothly to the different section elements through anchor links. The default behaviour for scrolling to an element is to align it to the top of the browser window. Instead, I want to align the element to the middle of the screen.</p> <p>I use this markup for navigation:</p> <pre><code>&lt;nav class="main-nav"&gt; &lt;a href="#top"&gt;Top&lt;/a&gt; &lt;a href="#section-1"&gt;Section 1&lt;/a&gt; &lt;a href="#section-2"&gt;Section 2&lt;/a&gt; &lt;a href="#section-3"&gt;Section 3&lt;/a&gt; &lt;a href="#section-4"&gt;Section 4&lt;/a&gt; &lt;a href="#section-5"&gt;Section 5&lt;/a&gt; &lt;/nav&gt; </code></pre> <p>I use <a href="https://github.com/kswedberg/jquery-smooth-scroll" rel="noreferrer">kswedberg's jQuery Smooth Scroll plugin</a> to smooth the scrolling. I initiate it like this:</p> <pre><code>$('.main-nav a').smoothScroll({ offset: 0, speed: 700 }); </code></pre> <p>I want to set the offset to be <code>((window).height / 2) - (element height / 2)</code> so that it's vertically centered, but I need help to figure out how to execute it properly.</p> <p>I need it to:</p> <ul> <li>Get the height of the window and divide it by two</li> <li>Get the height of the element and divide it by two </li> <li>Subtract the former from the latter</li> <li>If possible, align it to the top as per default if the element is higher than the window</li> </ul> <p>Since there are many anchor links I assume I either need to check the height of the element the anchor link that was clicked links to, or initiate smoothScroll for every anchor link.</p> <p>Does anybody know how to do this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload