How to load html element in .js file - javascript

I want to know how to load an HTMl element into a .js file that I can modify using HTML DOM
Like this
var para = document.createElement("p");
But instead of creating an element I want to get an already existing element, but this isn't possible to put it directly in a .js file because it's html, and it's a pain to write it using plain text
Why do I want to do this? Well I want to make a universal header bar for all my pages and I don't want to keep updating each one of them so I'm using a universal .js script which every page uses

You can use .querySelector() and give it a CSS-like selector.
Example:
const myElement = document.querySelector('.element_to_select') // Notice the dot, it's really important
<p class="element_to_select"></p>

function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
<div include-html="h1.html"></div>
<div include-html="content.html"></div>
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_html_include_2

Related

How can I edit one nav/menu document and change the elements in all my blog pages?

I know HTML and CSS but not JS yet. I am building a static blog from scratch and faced myself with a problem. When I create a post I am repeating all pages elements inside all the posts document, so, if I want to add a link to a menu, for example, I will need to edit all the files.
So, I was looking for a way to separate the menus and navs in different documents. Because if I edit them the menus will update in all de posts.
I found this method that apparently work: https://www.w3schools.com/howto/howto_html_include.asp (code below)
But, now, I don't know if this is the best method and I don't want to discover problems with it in the future, and discover that I will need to edit all the files.
This is a good method or another is better?
ps: no, I don't want a CMS.
This is the method:
Past this in head
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/* Loop through a collection of all HTML elements: */
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/* Make an HTTP request using the attribute value as the file name: */
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/* Remove the attribute, and call this function once more: */
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/* Exit the function: */
return;
}
}
}
</script>
and this in the body
<div w3-include-html="content.html"></div>
<script>
includeHTML();
</script>

Uploading Images to WYSIWYG editor and having default styling applied

I have created a wysiwyg text editor for my site and am trying to work with images.
So far I've got my image being uploaded and being added to my text editor where I want it using something like this:
$("#upload_wysiwyg_image").unbind("click").bind("click", function() {
var formData = new FormData();
var image_to_upload = document.getElementById("wysiwyg_image").files[0];
formData.append("wysiwyg_image", image_to_upload);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
if(this.responseText.includes('uploaded')){
var upload_string = this.responseText;
var image_name = upload_string.replace("uploaded ","")
var image_path = '../media/wysiwyg_images/'+image_name;
execCmdWithArg('insertImage', image_path);
}
}
};
xmlhttp.open("POST", "upload_wysiwyg_image.php", true);
xmlhttp.send(formData);
});
function execCmdWithArg (command, arg){
richTextField.document.execCommand(command, false, arg);
}
I want to be able to format the image at this point when it is being inserted. So for instance set a max-width/max-height or be able to select a float value for positioning.
Can this be done at this point while it is being inserted or will I need to insert it, and then call another function to set values for styling?
If anyone can point me in the right direction for this it would be greatly appreciated.

How to update innerHTML without modifying the entire content?

I have a javascript (AJAX) that periodically makes an XMLHttpRequest to get some data from a PHP file and append the returned data to the innerHTML of a <p> tag. However, every time the new content gets added to the block, the entire content of the paragraph seems to reload: when I select some text, the selection disappears when the data is updated.
Here's the code:
<script>
function requestChange(){
setInterval(updateData, 2000);
}
function updateData(){
var req = new XMLHttpRequest();
var url = "content_provider.php";
req.open("POST", url, true);
req.send();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
var data = req.responseText;
//updating the innerHTML content
document.getElementById('data').innerHTML += data;
}
};
}
</script>
<body onload="requestChange()">
<p id="data"></p>
</body>
How do I make the change in the innerHTML static?
You can try .insertAdjacentHTML()
It's what you need in this case because insertAdjacentHTML inserts the resulting nodes into the DOM tree at a specified position (first parameter), but does not reparse the hole tree.
document.getElementById('data').insertAdjacentHTML('beforeend', data);
Unfortunately using innerHTML will always destroy the previous content, if you are using jQuery you can instead use the append method, you haven't mentioned jQuery, so I'll assume that you're not using it.
You can instead use insertAdjacentHTML() instead of innerHTML, this method requires you to pass one of the positions below as the first argument and then the text you wish to add.
'beforebegin' // Before the element itself.
'afterbegin' // Just inside the element, before its first child.
'beforeend' //Just inside the element, after its last child.
'afterend' //After the element itself.
In your case here's how it would look:
document.getElementById('data').insertAdjacentHTML('beforeend', html_to_insert);
I didn't tested it but I think, this will work if you append a new container everytime you receive a new response:
function requestChange(){
setInterval(updateData, 2000);
}
function updateData(){
var req = new XMLHttpRequest();
var url = "content_provider.php";
req.open("POST", url, true);
req.send();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
var data = req.responseText;
var newInfoBox = document.createElement('SPAN');
newInfoBox.innerHTML = data;
//updating the innerHTML content
document.getElementById('data').appendChild(newInfoBox);
}
};
}
</script>
<body onload="requestChange()">
<p id="data"></p>
</body>

How to display image from another page in my page

I want to start a greasemonkey plugin to an existing page. The plugin should fetch and display some images automatically, each image from different pages.
I thought of using jQuery.get("link", function(data)) and hide the page and display the images only but on an average to display 4 images I should load 6 webpages into present webpage it is creating a delay in loading.
Is there any other work around to create a function that loads the page html of all image pages in background or in another tab and get the href of <a> tag's in that page, into my page and load only images into my page?
You can try this solution below.
Just put the URLs you want in the "pages" array. When the script runs, it makes Ajax calls in the background. When they are ready, it searches the source returned for images and picks one randomly. If found, it wraps the image in a link to the page where it found it (or if available, the image's url) and inserts the linked image to the top of the body of your own current page.
You can try the code by pasting it into your browser's JavaScript console and it will add the images to the current page.
You also see a demo here: http://jsfiddle.net/3Lcj3918/3/
//pages you want
var pages =
[
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random'
]
//a simple function used to make an ajax call and run a callback with the target page source as an argument when successful
function getSubPageSource(url, successCallback)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
//when source returned, run callback with the response text
successCallback(xhr.responseText);
}
};
//requires a proxy url for CORS
var proxyURL = 'https://cors-anywhere.herokuapp.com/';
xhr.open('GET', proxyURL+url, true);
//set headers required by proxy
xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");
xhr.setRequestHeader("Access-Control-Allow-Origin","https://cors-anywhere.herokuapp.com/");
xhr.send();
}
//a function that extract images from given url and inserts into current page
function injectImagesFrom(url)
{
getSubPageSource(url, function(data)
{
//trim source code to body only
var bodySource = data.substr(data.indexOf('<body ')); //find body tag
bodySource = bodySource.substr(bodySource.indexOf('>') + 1); //finish removing body open tag
bodySource = bodySource.substring(0, bodySource.indexOf('</body')); //remove body close tag
//create an element to insert external source
var workingNode = document.createElement("span");
//insert source
workingNode.innerHTML = bodySource;
//find all images
var allImages = workingNode.getElementsByTagName('img');
//any images?
if (allImages.length > 0)
{
//grab random image
var randomIndex = Math.floor(Math.random() * allImages.length);
var randomImage = allImages.item(randomIndex);
//add border
randomImage.setAttribute('style', 'border: 1px solid red;');
//restrain size
randomImage.setAttribute('width', 200);
randomImage.setAttribute('height', 200);
//check if parent node is a link
var parentNode = randomImage.parentNode;
if (parentNode.tagName == 'A')
{
//yes, use it
var imageURL = parentNode.getAttribute('href');
}
else
{
//no, use image's page's url
var imageURL = url;
}
//add a link pointing to where image was taken from
var aLink = document.createElement("a");
aLink.setAttribute('href', imageURL);
aLink.setAttribute('target', '_blank');
//insert image into link
aLink.appendChild(randomImage);
/* INSERT INTO PAGE */
//insert image in beginning of body
document.body.insertBefore(aLink,document.body.childNodes[0]);
//remove working node children
while (workingNode.firstChild) {
workingNode.removeChild(workingNode.firstChild);
}
//unreference
workingNode = null;
}
});
}
for (var ii = 0, nn = pages.length; ii < nn; ii++)
{
injectImagesFrom(pages[ii]);
}

Get the text from an external HTML document

My goal is to get the text from a HTML document which does not call any functions from my .jsp file.
I've looked around and I thought I had found the answer to my problem but it doesn't seem to be working, and other answers consist of using jQuery (which I am both unfamiliar with and not allowed to use).
This is my code so far:
function getText(divID) {
var w = window.open("test.html");
var body = w.document.body;
var div = document.getElementById(divID);
var textContent = body.textContent || body.innerText;
console.log(textContent);
//div.appendChild(document.createTextNode(textContent));
}
So as you can see, I'm trying to get the body of one HTML document and have it appear in another. Am I on the right tracks?
EDIT: Ok so I seem to have made my problem quite confusing. I call the function in a HTML document called html.html, but I want to get the text from test.html, then have it appear in html.html. It has to be like this because I can't assume that the HTML document I want to read from will include my .jsp file in its head.
At the moment I am getting the following error.
Uncaught TypeError: Cannot read property 'body' of undefined
The reason document.body in the other window is undefined, is because the other window has not loaded and rendered the document yet.
One solution would be to wait for the onload event.
function getText(divID) {
var w = window.open("test.html");
w.addEventListener("load", function() {
var body = w.document.body;
var div = document.getElementById(divID);
var textContent = body.textContent || body.innerText;
console.log(textContent);
});
}
Make sure you run the getText function on a user event like a click, else window.open will fail.
If all you want to do is get the contents of the other window, using AJAX would probably be a better option.
function getText(divID) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 ) {
var body = xhr.response.body;
var div = document.getElementById(divID);
var textContent = body.textContent || body.innerText;
console.log(textContent);
}
};
xhr.open("GET", "test.html", true);
xhr.responseType = "document";
xhr.send();
}

Categories

Resources