Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading an HTML file into a DIV with a link

There are several topics on this, but none that completely answer my question.

I would like to be able to have a link which loads a whole HTML file into a DIV.

This, for example, will load just text into my "MainBack" DIV. It works fine:

<a href="#computing" onclick="document.getElementById('MainBack').innerHTML = '<p>1</p>';">Computing</a>

but I would like to load an entire file into it like this:

<a href="#computing" onclick="document.getElementById('MainBack').innerHTML = 'HTML FILE';">Computing</a>

Any advice? I'm pretty new to this!

like image 277
Mark Brewerton Avatar asked Feb 13 '11 21:02

Mark Brewerton


3 Answers

You can use an <iframe> to do just that:

<iframe src="link.html" width="100%" height="300"></iframe>

Live Demo

Code:

<a href="#computing" onclick="document.getElementById('MainBack').innerHTML = '<iframe src=\'http://www.google.com\' scrolling=\'no\' frameborder=\'0\' width=\'100%\' height=\'600px\'></iframe>'">Computing</a>

Or you could use lightbox to do it in a really pretty manner...

It will display; photos, videos, HTML... basically anything you want.

like image 117
Myles Gray Avatar answered Oct 07 '22 02:10

Myles Gray


Using the jQuery ajax API you can grab the content of a particular tag inside the document from some URL:

<a href="#computing" 
   onclick="$('#MainBack').load('/path/file.html body')"
>
    Computing
</a>

Important:

  1. #MainBack is the ID of the placeholder tag in your parent document
  2. /path/file.html id the URL for the document you want to load data from
  3. body is the tag holding the content you want to load.

What can go wrong:

  • check #1 above, does your parent document has a tag with the exact ID you are using in the ajax call?
  • check #2, can you load the URL in a separate browser window?
  • if you can load the URL, use the "view source" option to inspect the HTML source and make sure you have the selector you are using in #3 above. Perhaps the content you want is being generated dynamically from JavaScript instead of being served by the HTTP server, in this case use the iframe solution from the other answer.
  • check the JavaScript console and look for some message about cross-domain issues, CSRF, CORS, etc. If the content is from another domain you may stumble upon the browser security rules; this is a whole new can of worms and I will not cover the possible solutions here, take the error message from the console and google for it.
like image 39
Paulo Scardine Avatar answered Oct 07 '22 01:10

Paulo Scardine


<a href="#computing" onclick="document.getElementById('MainBack').innerHTML = '<iframe src=\'http://www.google.com\'></iframe>'">Computing</a>

--> Demo <--

like image 28
Shaz Avatar answered Oct 07 '22 02:10

Shaz