snipt

Ctrl+h for KB shortcuts

JavaScript

scroll to element with jQuery

1
2
3
4
5
6
function scrollGo() {
   var x = $(this).offset().top - 100; // 100 provides buffer in viewport
   $('html,body').animate({scrollTop: x}, 500);
}
// set focus event on element
$('#myForm :input').focus(scrollGo); 
https://snipt.net/embed/c95e32050ff7e981ab98d22e2581547a/
/raw/c95e32050ff7e981ab98d22e2581547a/
c95e32050ff7e981ab98d22e2581547a
js
JavaScript
6
2019-07-21T13:03:38
True
False
False
/api/public/snipt/7396/
scroll-to-element-with-jquery
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><a href="#L-1">1</a> <a href="#L-2">2</a> <a href="#L-3">3</a> <a href="#L-4">4</a> <a href="#L-5">5</a> <a href="#L-6">6</a></pre></div></td><td class="code"><div class="highlight"><pre><span></span><span id="L-1"><a name="L-1"></a><span class="kd">function</span> <span class="nx">scrollGo</span><span class="p">()</span> <span class="p">{</span> </span><span id="L-2"><a name="L-2"></a> <span class="kd">var</span> <span class="nx">x</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="k">this</span><span class="p">).</span><span class="nx">offset</span><span class="p">().</span><span class="nx">top</span> <span class="o">-</span> <span class="mi">100</span><span class="p">;</span> <span class="c1">// 100 provides buffer in viewport</span> </span><span id="L-3"><a name="L-3"></a> <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;html,body&#39;</span><span class="p">).</span><span class="nx">animate</span><span class="p">({</span><span class="nx">scrollTop</span><span class="o">:</span> <span class="nx">x</span><span class="p">},</span> <span class="mi">500</span><span class="p">);</span> </span><span id="L-4"><a name="L-4"></a><span class="p">}</span> </span><span id="L-5"><a name="L-5"></a><span class="c1">// set focus event on element</span> </span><span id="L-6"><a name="L-6"></a><span class="nx">$</span><span class="p">(</span><span class="s1">&#39;#myForm :input&#39;</span><span class="p">).</span><span class="nx">focus</span><span class="p">(</span><span class="nx">scrollGo</span><span class="p">);</span> </span></pre></div> </td></tr></table>
jquery, scroll