css – Call page by HREF and load in IFRAME the id of another page

Question:

Guys, See if this situation is possible in HTML5 and CSS:

I have 3 files: index.html servicos.html desc_servicos.html

Obs.: all files inside the same folder.

In the index.html file there is a link to the servicos.html page.
Servicos.html Inside there is a iframe with src for desc_servicos.html. In desc_servicos.html there are several sections with their ID's.

There is possibility to draw servicos.html page passing the ID of a section, the desc_servicos.html file to be loaded into the IFRAME?

I'm aware of this option and I know it works when it's on the same page, but I 'm not aware of it when talking about multiple pages.

<a href="desc_servicos.html#id" target="nome_iframe">Agente</a>

Sorry if the explanation was confused.

Answer:

With .html pages, you can do this using JavaScript. You can do it this way, following the steps:

1. Add the hash with the id of the div you will load in the href of the index.html link:

<a href="servicos.html#id_da_div">Serviços</a>

2. On page servicos.html capture the hash with window.location.hash . But create two iframe s, one without src and the other hidden with display: none with the desc_servicos.html page.

Why are two iframes being one hidden? The one that is not hidden will get the div of the one that is hidden. That's because the hidden iframe will load the desc_servicos.html page and it doesn't need to appear, because it will be all loaded so you can get the desired div .

Would be like this:

<iframe id="frame" width="500" height="200"></iframe>
<iframe id="frame2" style="display: none;" src="desc_servicos.html"></iframe>

And include the script below (at the end of the body ) from the servicos.html page:

<script>
var iFrame = document.body.querySelector("#frame");
var iFrame2 = document.body.querySelector("#frame2");
var div_id = window.location.hash;
iFrame2.onload = function(){ // aguarda o iframe2 carregar

   // insere a div no iframe visível
   iFrame.contentDocument.body.innerHTML = iFrame2.contentWindow.document.querySelector(div_id).outerHTML;
   iFrame2.outerHTML = ''; // remove o iframe2 do DOM
}
</script>

Summing up:

On the index.html page (replace id_da_div with the div id from the iframe you want to get):

<a href="servicos.html#id_da_div">Serviços</a>

On the servicos.html page:

<iframe id="frame" width="500" height="200"></iframe>
<iframe id="frame2" style="display: none;" src="desc_servicos.html"></iframe>

<script>
var iFrame = document.body.querySelector("#frame");
var iFrame2 = document.body.querySelector("#frame2");
var div_id = window.location.hash;
iFrame2.onload = function(){ // aguarda o iframe2 carregar

   // insere a div no iframe visível
   iFrame.contentDocument.body.innerHTML = iFrame2.contentWindow.document.querySelector(div_id).outerHTML;
   iFrame2.outerHTML = ''; // remove o iframe2 do DOM
}
</script>
Scroll to Top