Using this code below I can load an HTML page to a div, in my site, by clicking a link in my menu.
Now, the problem is that when it loads the HTML page into the div, it loads just fine... but without its original background color that should be loaded with the other content of the HTML page as well. All the other CSS elements seem to be just fine.
Thank you in advanced.
js code:
function processAjax(url)
{
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = targetDiv;
try {
req.open("GET", url, true);
}
catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = targetDiv;
req.open("GET", url, true);
req.send();
}
}
return false;
}
function targetDiv() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
document.getElementById("containerDiv").innerHTML = req.responseText;
} else {
alert("Problem: " + req.statusText);
}
}
}
html:
<a onclick="return processAjax(this.href)" href="example.html">CLICK ME</a>
<div id="containerDiv"></div>
Get the style element from the page and append it to the head:
var styles = document.getElementsByTagName('style');
var head = document.getElementsByTagName('head')[0];
for(var x = 0; x < styles.length; x++){
head.appendChild(styles[x]);
}
Edit:
You want to set the returned html as an element first:
var div = document.createElement('div');
div.innerHTML = req.responseText;
var styles = div.getElementsByTagName('style');
for(var x = 0; x<styles.length;x++){
document.getElementsByTagName('head')[0].appendChild(styles[x]);
}
Use the new code, not the old, and put it in the if(reg.status == 200) block.
Change .innerHTML to .html, or just use .load(req.responseText)
.innerHTML overwrites everything I believe. You just want to change a section.
Related
I am using xhlhttprequest to load an external html file. However I am trying to figure out how to load only a speicific DIV from that html file.
My external page is helpFile.html- it has dozens header <DIV>s, an each header DIV is a specific help section. On different pages, I want to be able load a specific section? How could I do this? As an example, on the dashboard.html page is a help ? icon, that when the user clicks on it, it will load just the helpFile.html#dashboard section out of the main helpFile.html page - the content would be loaded into a bootstrap modal.
Here is my code to retrieve the entire page, but how can I just retrieve the needed section.
<script>
var request;
function sendInfo() {
var url = "helpFile.html";
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send();
} catch (e) {
alert("Unable to connect to server");
}
}
function getInfo() {
if (request.readyState == 4) {
var val = request.responseText;
document.getElementById('helpModal').innerHTML = val;
}
}
</script>
Use DOMParser and look for the element
if (request.readyState == 4 && request.status == 200) {
var parser = new DOMParser();
var doc = parser.parseFromString(request.responseText;, "text/html");
var dashboardElement = doc.querySelector("#dashboard");
document.getElementById('helpModal').innerHTML = dashboardElement.innerHTML;
}
When using this code no CSS/Javascript works (It just loads the HTML):
function functionName(limit) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var text = xhttp.responseText;
document.getElementById("content").innerHTML = "";
document.getElementById("content").innerHTML = text;
}
}
xhttp.open("GET", "?x=test&limit=" + limit, false);
xhttp.send();
}
When using jQuery CSS/Javascript works, now the problem is that the page scrolls up when loading the content.
$('#content').load('?x=test&limit=" + limit);
What I want is a way to load an URL to a DIV, where CSS and Javascript works.
And like .innerHTML I want to load the content without scrolling to the top.
Hope for help, yesterday i googled for 6-8 hours, and im a google-fu guru =)
Still got the same problem!
When using XMLHttpRequest and .innerHTML it loads the HTML (without scrolling up to the start of the div). But no Javascript or CSS works...
And with this it loads Javascript and CSS when .load'ing. But it scrolls up to the start of the div.
$('#content').load("?x=test&limit=" + limit);
function functionName(limit) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var ele = document.createElement("script");
ele.src = "js/some-js-ajax.js";
document.body.appendChild(ele);
var text = xhttp.responseText;
document.getElementById("content").innerHTML = "";
document.getElementById("content").innerHTML = text;
}
}
xhttp.open("GET", "?x=test&limit=" + limit, false);
xhttp.send();
}
When adding:
var ele = document.createElement("script");
ele.src = "js/some-js-ajax.js";
document.body.appendChild(ele);
.innerHTML works with CSS and Javascript, but now it scrolls up to the start o fthe div again. Not staying in the scrolled place where you were before the functionName(limit) load ....
here is my html:
<html><body>
page starts here
this is a test page
top:
<script id="invoc_code" type="text/javascript">
window.onload = function() {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
var body = document.body;
if (xhr.readyState == 4 && xhr.status == 200) {
if(body.firstChild){
body.insertBefore(xhr.response, body.firstChild);
} else {
body.appendChild(xhr.response);
}
}
};
xhr.open("GET", "http://google.com", true);
xhr.send();
};
</script>;
page ends here
</body></html>
line body.insertBefore(xhr.response, body.firstChild); results to "NotFoundError: An attempt was made to reference a Node in a context where it does not exist". Can you please tell me what is the reason?
Thanks in advance
The insertBefore method expects a DOM element as its first parameter. If the XHR response is a HTML string, then you need to create one using this. Depending on your required DOM output you could do something like this:
var newElem = document.createElement("div");
newElem.innerHTML = xhr.response;
body.insertBefore(newElem, body.firstChild);
I've got an index page and I want to load on a DIV another page from a very different directory, but I want that the page that will be loaded into the DIV to keep the CSS and JS includes, is it possible?
It seems that it only loads into the DIV, the body of the other page and forget the JS and CSS includes.
I'm using this code to load the HTML into the div:
<script type="text/javascript">
function processAjax(url) {
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = targetDiv;
try {
req.open("GET", url, true);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = targetDiv;
req.open("GET", url, true);
req.send();
}
}
}
function targetDiv() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
document.getElementById("mContent").innerHTML = req.responseText;
} else {
alert("Problem: " + req.statusText);
}
}
}
</script>
Usage:
My Page
Why don't you use an IFRAME tag that contains the url of the page you desire to display with the js and css you want to use.
<iframe src="mypage.html"></iframe>
I have a bunch of divs with weird id and each of them contains a video. They're actually video embed codes but they're not usual to me. Here's one example:
<div id="evp-1fae4e37639894816f03591bc7009c68-wrap" class="evp-video-wrap"></div><script type="text/javascript" src="http://domain.com/evp/framework.php?div_id=evp-1fae4e37639894816f03591bc7009c68&id=cmVsYXRpb25zaGlwLW1hcmtldGluZy0xLmZsdg%3D%3D&v=1278525356"></script><script type="text/javascript">_evpInit('cmVsYXRpb25zaGlwLW1hcmtldGluZy0xLmZsdg==');</script>
What I want to do is create a video playlist. As a part of that, I created list using divs also which use the onclick attribute to trigger my JS function to switch between videos. Here's how it looks:
<div class="vid-list" onclick="switchvideo('http://domain.com/html-vids/headline-vids/second-vid.html', 2)"><p>This a video tutorial for blah blah blah.</p></div>
The problem is, each time I switch to another video the div id of the embed code changes also because otherwise it won't work. So I need to change that before loading the video script inside the div. I tried to achieve that using the following JS function:
function switchvideo(url, vidnumber)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET",url,false);
xmlhttp.send();
}
var div_node = document.getElementByClass('evp-video-wrap');
if ( vidnumber == 2 ) {
div_node.id = 'evp-78c0b7c4f6d3377954825f145734fd5c-wrap';
}
document.getElementById(div_node.id).innerHTML=xmlhttp.responseText;
}
Apparently it's not working. I suspect the problem are the lines in bold above. I tried to get the element by 'class' and its id by using 'div_node.id'. I am assuming that by doing 'document.getElementByClass', I am getting the reference to that element so I could use it to manipulate its other attributes. But I am not sure... Could anyone pls enlighten me??
There is no getElementByClass() method. There is a getElementByClassName() but it's not available in every browser.
Here is one you can use:
// http://www.dustindiaz.com/getelementsbyclass/
function getElementsByClass(searchClass, node, tag) {
var classElements = new Array();
if (node == null) node = document;
if (tag == null) tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if (pattern.test(els[i].className)) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
Then you can call it as
getElementByClass('evp-video-wrap');
Your ajax is a bit tricky, but here is a more general one:
function getXmlHttpObject() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (!xmlHttp) {
alert("Your browser does not support AJAX!");
}
return xmlHttp;
}
function ajax(url, onSuccess, onError) {
var xmlHttp = getXmlHttpObject();
xmlHttp.onreadystatechange = function() {
if (this.readyState === 4) {
// onSuccess
if (this.status === 200 && typeof onSuccess == 'function') {
onSuccess(this.responseText);
}
// onError
else if(typeof onError == 'function') {
onError();
}
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
return xmlHttp;
}
Finally your code becomes:
function switchvideo(url, vidnumber) {
var div_node = getElementByClass('evp-video-wrap')[0];
// make a call to the url, and execute the
// callback when the response is available
ajax(url, function( responseText ){
if (vidnumber == 2) {
div_node.id = 'evp-78c0b7c4f6d3377954825f145734fd5c-wrap';
}
document.getElementById(div_node.id).innerHTML = responseText;
});
}
You can see the whole code [here]
getElementByClass isn't a standard method. Is it possible for you to use a framework for this? jQuery has a nice mechanism to search for an element by class, as do the other frameworks. It also makes it much easier to do the AJAX bits in a cross-browser supported way.
function switchvideo(url, vidnumber)
{
$.get(url, function(data) {
var div_node = $('.evp-video-wrap');
if (vidnumber == 2) {
div_node.attr('id', 'evp-78c0b7c4f6d3377954825f145734fd5c-wrap');
}
div_node.html( data );
});
}
An alternative would be to write your own getElementByClass or specific code to search for a DIV by class. Note: I assume you're only interested in the first match.
function getDivByClass( klass )
{
var regex = new RegExp( '(^|\\s+)' + klass + '(\\s+|$)' );
for (div in document.getElementsByTagName('div')) {
if (regex.text( div.className)) {
return div;
}
}
return null;
}