Blog » Prevent iframe stealing focus with jquery

I recently had (good) reason to embed a complex web page into another page using an iframe. Unfortunately this caused the well-known problem of the iframe stealing focus, which meant that on page load suddenly the browser scrolled down to where the iframe was embedded. After doing some searches and many years of various and complex solutions, I came up with this simple fix: don't display the iframe until it's loaded. Like so.

My HTML looks something like this:

<iframe id="page-embed" class="init" sandbox="allow-same-origin allow-scripts" src="/path/to/embedded/page"></iframe>

And here's the dead simple jQuery:

$('#page-embed').on('load', function() { if ($(this).hasClass('init')) { $(this).removeClass('init').show(); } });

BONUS:

I also wanted to apply a bunch of CSS rules to the embedded page. Thanks to the fact that both pages are on the same domain, I was able to just force in a new css file within the iframe content, and it works like a charm.

Here's the jQuery for that too:

$('#page-embed').on('load', function() { if ($(this).hasClass('init')) { $('#page-embed').contents().find("head").append('<link rel="stylesheet" href="/path to css/page-embed.css" media="all">'); $(this).removeClass('init').show(); } });