Hey, I'm not a real programmer but I do like playing around with this stuff for my own needs. I recently began building my portfolio website and taught myself CSS and simple javascript to get it done.
I was looking for a way to load HTML, CSS and/or JAVASCRIPT content into a DIV within a page, both by onCLick and onLoad events.
I found these codes online:
<a href="javascript:void()" onclick="javascript:sendRequest('sourcepage?id=34', 'targetdiv')">Link Text</a>
<div id="targetdiv">This is the target</div>
function createRequestObject()
{
var returnObj = false;
if(window.XMLHttpRequest) {
returnObj = new XMLHttpRequest();
} else if(window.ActiveXObject) {
try {
returnObj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
returnObj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return returnObj;
}
var http = createRequestObject();
var target;
// This is the function to call, give it the script file you want to run and
// the div you want it to output to.
function sendRequest(scriptFile, targetElement)
{
target = targetElement;
try{
http.open('get', scriptFile, true);
}
catch (e){
document.getElementById(target).innerHTML = e;
return;
}
http.onreadystatechange = handleResponse;
http.send();
}
function handleResponse()
{
if(http.readyState == 4) {
try{
var strResponse = http.responseText;
document.getElementById(target).innerHTML = strResponse;
} catch (e){
document.getElementById(target).innerHTML = e;
}
}
}
These worked well, when I tried them myself. But I couldn't call the same document more than once onLoad:
</script>
<script type="text/javascript">
function loadPage(){
sendRequest('hello.html', 'content');
}
</script>
<script type="text/javascript">
function loadPage(){
sendRequest('hello.html', 'contents2');
}
</script>
<script type="text/javascript">
function loadPage(){
sendRequest('hello.html', 'contents3');
}
</script>
</head>
<body onload="loadPage();">
<a href="javascript:void()" onclick="javascript:sendRequest('hello.html', 'content')">Link Text</a>
<div id="content">This is the target</div>
<br>2<br>
<div id="contents2">This is the target</div>
<br>3<br>
<div id="contents3">This is the target</div>
What would happen in this last code, only 'contents3' would contain hello.html, and the other two would remain empty, unless i pressed the Link Text and then 'content' would then call hello.html.
I would like to call the same page more than once, I don't know how to fix it.
Would someone care to help?