title: Onfocus Scroll To Anchor = Lose Focus. Restore Focus = Infinite Loop
body: <p>I have a text field which updates the contents of a div as the user types into it. My users on small screens sometimes scrolled past the div, and had only the input on the screen. So they were unaware that their typing was doing something.</p>
  
  <p>So I wrote the Javascript function you see below to keep both elements on-screen at the same time. The <code>onfocus</code> event in the input scrolls up the browser window to show the div.</p>
  
  <p>But that causes the input to lose focus. So, I added <code>this.focus()</code> to the function. It returns focus to the input.</p>
  
  <p>But this event triggers the function again, creating an infinite loop which exceeds the maximum call stack size.</p>
  
  <p>How can I work around this to ensure both elements are on the screen at the same time, and yet not lose focus in the input, and avoid the infinite loop?</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>(function() {
  
    document.getElementById('edit_here').onkeyup = function(){
        var result = document.getElementById('edit_here').value;
        document.getElementById('result_here').innerHTML = result;
    }
  
  
    document.getElementById('edit_here').onfocus = function(){
      location.href = '#result_here';
      this.focus();
    }
  
  }());</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="result_here"&gt;Result&lt;/div&gt;
  &lt;div&gt;Scroll down until this is not visible. Then type in the field.&lt;/div&gt;
  &lt;input id="edit_here" type="text" /&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;
  &lt;div&gt;.&lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>