...

View Full Version : Dynamically load html without reload?



YourDirector
07-18-2011, 12:07 PM
Hey everyone,

I currently have a grid of thumnails which when clicked will load an image at the top of the page without reloading the page using the following JS:


<a href="JavaScript:;" onClick="JavaScript:document.all.Main.src='images/image01.png';"><img src='images/image01thumb.png'></a>

This works wonderfully, However, what I need to do now is to produce the same thing but instead of loading an image, load an html file into the page without reloading. Is there a way I could use a similarly simple solution?

Thanks

bullant
07-18-2011, 12:39 PM
One option is to use an onclick to change the src attribute of an <iframe> to the url of the html file you want to load.

YourDirector
07-18-2011, 12:51 PM
One option is to use an onclick to change the src attribute of an <iframe> to the url of the html file you want to load.

Hi BullAnt, Yeah I did think that but I'm trying to avoid iframes due to compatibility issues.

I have just come across this method which sounds like it should work but I cant seem to get it running yet. Any suggestions?:

JQuery + this:

function loadContent(elementSelector, sourceUrl) {
$(""+elementSelector+"").load("http://yoursite.com/"+sourceURL+"");
}
in the head, give my div an ID of "content", then have this as the link to change its content:
<a href="javascript:loadContent('#content', 'source_page.php');">Link 1</a>

VIPStephan
07-18-2011, 01:16 PM
Please, please, if you use jQuery already, do it the contemporary (unobtrusive (http://www.onlinetools.org/articles/unobtrusivejavascript/chapter1.html)) way, not with some fifteen years old method (which was bad practice at any time).

Do it like:


<a href="target.php">link text</a>
<div id="content">
some default content here
</div>

and


$('a').click(function() {
$('#content').empty().load($(this).attr('href'));
});


Which selector(s) you use depends on the mark-up. You could also add a class or a rel attribute to the link(s) but if your link(s) is/are in a navigation or whatever you can also use this as selector for jQuery.

YourDirector
07-18-2011, 01:28 PM
Ok, so are you suggesting that the latter code you offered there should be placed in the page header?
If so I have just tried this and resulted in it simply downloading my page when the link is clicked.

VIPStephan
07-18-2011, 05:20 PM
Show us your effort and we’ll tell you what’s wrong.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum