Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
prevent iframe from scrolling parent document when calling focus

I have an iframe that calls someElement.focus. When this happens the parent scrolls to show the iframe. How can I prevent the parent from scrolling? Effectively I want the iframe itself to scroll so within the iframe the correct element is scrolled into space of the iframe itself but the parent page should be unaffected.

const lines = new Array(100).fill(0).map((e,i) => i).join('\n')
const script = 'script';
const frameContent = `
<style>
pre { font-size: 60pt; }
</style>
<body>
  <pre>${lines}</pre>
  <input type="text" id="target">
</body>
<${script}>
document.querySelector('#target').focus();
</${script}>
`;



document.querySelector('pre').textContent = lines;
const iframe = document.querySelector('iframe');
iframe.src = URL.createObjectURL(new Blob([frameContent], {type: 'text/html'}));
<style>
  pre { font-size: 60pt; }
}
</style>
<div>you should see this element</div>
<pre></pre>
<iframe></iframe>
<div>you should NOT be scrolled to see this element</div>

It makes sense to me that calling focus would move the input area on to the screen, but at the same time, it makes no sense to me that any random iframe can get the parent page to jump to it on demand by calling focus.

Is it possible to prevent the iframe from affecting the parent?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can try passing options when setting focus:

document.querySelector('#target').focus({preventScroll: true});

The preventScroll option is described in the MDN docs on HTMLElement.focus().

Note that this will likely only work for same-origin iframes.

Browsers apply restrictions that might prevent the preventScroll option being respected inside cross-origin/third-party iframes.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!