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 ....
Related
I have an AJAX call whose reponse will feed some HTML into a DIV's innerHTML.
The response can contain images, and I'd like to have all these images loaded before my custom loading-div will hide.
I want to do this in vanilla JS. Unfortunately every question I've found here so far does it via jQuery.
I've tried adding an onload Event Listener to both the DIV and the xhttp object, but neither works. The loader disappears as soon as the HTML code is received and inserted, and then the user can witness each image loading individually.
document.getElementById("pageloader").className = "fadein";
var poststring = "&page="+encodeURIComponent(page);
var xhttp = new XMLHttpRequest();
xhttp.addEventListener("load", function() {
document.getElementById("pageloader").className = "fadeout";
});
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("content").innerHTML = this.responseText;
}
};
xhttp.open("POST", "myajax.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(poststring);
I'm reading a text file into with a temporary email address and let this snippet built a HTML link.
<script>
//<![CDATA[
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementsByClassName('temporary_email')[0].innerHTML = "Email";
}
};
xhttp.open("GET", "/temporary_email.txt", true);
xhttp.send();
//]]>
</script>
The whole thing works as expected and I can just place <span class="temporary_email"></span> anywhere and get a link.
The problem: it seems I can only fetch this one time; if I have a mailto: link in the body and another one in my footer the script won't work. So, I figure this isn't actually a variable and me being a JS noob is the real problem.
PS: I'm trying to avoid jQuery. Tried a few dummy workarounds like duplicating the script and assigning another name for document.getElementsByClassName, but nothing. Basically I'm working for a quick and dirty fix until I know enough JavaScript to do this properly.
The reason you're only getting the JS appended to the first instance of the class name match, is because document.getElementsByClassName() returns an array of matched elements.
By using document.getElementsByClassName('temporary_email')[0], you're only ever going to select the first matched element.
You'd need to update to the following code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var elements = document.getElementsByClassName('temporary_email');
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "Email";
}
}
};
xhttp.open("GET", "/temporary_email.txt", true);
xhttp.send();
Here's a basic fiddle.
This way, you're iterating trough the array, and each one you're changing the innerHTML to what you need. Plus, no jQuery!
you could iterate over your temporary_email links and update each of them:
Array.from(document.getElementsByClassName('temporary_email'))
.forEach(function(el){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
el.innerHTML = "Emai l";
}
};
xhttp.open("GET", "/temporary_email.txt", true);
xhttp.send();
})
I want to load an AngularJS app inside a “friendly” IFRAME (due to SEO reasons).
See example code here:
https://jsfiddle.net/tomsoderlund/mssca32k/
var embedDiv = document.getElementById('weld-embed');
// Create friendly IFRAME
var newIframe = document.createElement('iframe');
newIframe.src = 'about:blank';
newIframe.width = '100%';
newIframe.height = '100%';
newIframe.frameBorder = '0';
embedDiv.appendChild(newIframe);
// Create contents inside
var htmlContent = '<!doctype html>'
// ...
+ '<\/body><\/html>';
newIframe.contentWindow.document.write(htmlContent);
The AngularJS app doesn’t start up, probably because document.ready doesn’t trigger in a normal fashion. Can I bootstrap/force the AngularJS code to start up?
The problem was solved by:
Moving from JSFiddle to a simpler web structure.
Loading htmlContent from a separate template.html HTML file*.
Bootstrapping AngularJS from within template.html**.
*Code from point 2 above (adapted from “HTTP GET request in JavaScript?”):
var httpGetAsync = function (theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
callback(xmlHttp.responseText);
}
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
httpGetAsync('/template.html', function (htmlContent) {
newIframe.contentWindow.document.write(htmlContent);
});
**Code from point 3 above:
<script type="text/javascript">
angular.bootstrap(document, ['myAngularModule']);
</script>
I am working on getting a dynamic page set up on my site where clicking a "More Info" button triggers a loadBCW.js script which updates a <div>'s innerHTML using a text file saved elsewhere. I've got that working perfectly using this loadBCW.js:
document.getElementById("loadBCW").addEventListener('click',function(){
var url = "/wp-content/themes/DICE/js/descriptionBCW";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
document.getElementById("demo").innerHTML = url;
}, false);
My issue is, when I click one of the "More Info" buttons in order to change the <div>'s innerHTML, it will flash the variable url in the <div>, then the correct elements overwrite it.
How can I instruct js to NOT flash the variable url onscreen before actually updating the <div>?
Maybe get rid of the code that sets the div content to be the URL in the first place? I've commented out the line you should remove:
document.getElementById("loadBCW").addEventListener('click',function(){
var url = "/wp-content/themes/DICE/js/descriptionBCW";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
// document.getElementById("demo").innerHTML = url;
}, false);
You're making an asynchronous request to an external source, so the code inside the xhttp.onreadystatechange won't run until the file was successfully retrieved. There's not really anything you can do about this other than optimize your site to run faster than . So if you don't want the URL to be visible, there's no point in setting it in the first place.
However, this would be even worse if it was a sync request, as not only will it slow you performance, but since document.getElementById("demo").innerHTML = url; is after your function, it is guaranteed to end by replacing the content with the URL.
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.