I'm currently working on a small project in which I want to convert couple (or more) Markdown files into HTML and then append them to the main document. I want all this to take place client-side. I have chose couple of plugins such as Showdown (Markdown to HTML converter), jQuery (overall DOM manipulation), and Underscore (for simple templating if necessary). I'm stuck where I can't seem to convert a file into HTML (into a string which has HTML in it).
Converting Markdown into HTML is simple enough:
var converter = new Showdown.converter();
converter.makeHtml('#hello markdown!');
I'm not sure how to fetch (download) a file into the code (string?).
How do I fetch a file from a URL (that URL is a Markdown file), pass it through Showdown and then get a HTML string? I'm only using JavaScript by the way.
You can get an external file and parse it to a string with ajax. The jQuery way is cleaner, but a vanilla JS version might look something like this:
var mdFile = new XMLHttpRequest();
mdFile.open("GET", "http://mypath/myFile.md", true);
mdFile.onreadystatechange = function(){
// Makes sure the document exists and is ready to parse.
if (mdFile.readyState === 4 && mdFile.status === 200)
{
var mdText = mdFile.responseText;
var converter = new showdown.Converter();
converter.makeHtml(mdText);
//Do whatever you want to do with the HTML text
}
}
jQuery Method:
$.ajax({
url: "info.md",
context: document.body,
success: function(mdText){
//where text will be the text returned by the ajax call
var converter = new showdown.Converter();
var htmlText = converter.makeHtml(mdText);
$(".outputDiv").append(htmlText); //append this to a div with class outputDiv
}
});
Note: This assumes the files you want to parse are on your own server. If the files are on the client (IE user files) you'll need to take a different approach
Update
The above methods will work if the files you want are on the same server as you. If they are NOT then you will have to look into CORS if you control the remote server, and a server side solution if you do not. This question provides some relevant background on cross-domain requests.
Once you have the HTML string, you can append to the whatever DOM element you wish, by simply calling:
var myElement = document.getElementById('myElement');
myElement.innerHTML += markdownHTML;
...where markdownHTML is the html gotten back from makeHTML.
Related
I will be dynamically adding elements to my main index.html using .innerHTML += "<p>example</p>"; However I do not want to store the large html-like string in this .js file, but instead import it from another file example.html
example.html:
<p>example</p>
(It is just a snippet of code and not a standalone html file, but I want to keep the .html extension for linting, autocompletion and general readability)
My attempts:
$(...).load('example.html'): did not work as it replaces of contents of ... with this example instead of appending it
import * from example.html: this and other attempts of importing file failed because of MIME error that text/html cannot be imported
I will be perfectly satisfied with a solution of a method that reads .html as text and returns it as a string (preferably not using AJAX or ES6 as I do not feel confident with them). I would then just use the string in .innerHTML += imported_string; and call it a day.
If I correctly understand what you want to do, you can use FileReader to import the content of a file and convert it to text, for example:
function readFile(event) {
var file = event.target.files[0];
var stream = new FileReader();
stream.onload = function(e) {
var fileContent = e.target.result;
alert(fileContent);
}
stream.readAsText(file);
}
document.getElementById('myFile').addEventListener('change', readFile, false);
<input type="file" accept="html" id="myFile">
The file input is for presentation purposes, you can easily adapt this to your needs.
You should also perform the customary checks, which I ommited for brevity purposes.
Create a fetch request to the file that you want to retrieve. This is, in a basic sense, the same way how a browser would request a html file from the server.
The function below sends a request based on what you input as a file. For example, 'example.html'. It then checks if the request was a success and returns the response as a string. The string can then be appended to your innerHTML.
const getFileAsText = async file => {
const response = await fetch(file);
if (!response.ok) {
throw new Error(`Fetching the HTML file went wrong - ${response.statusText}`);
}
return response.text();
};
You can use it like the example below.
getFileAsText('example.html').then(html => {
document.body.innerHTML += html;
});
Is this even a possibility? Never attempted or tried anything like this before, I have no idea where to start.
I have a local file that when a manual button is pressed, it updates an xml file changing
<status>live<\status>
to
<status>killed<\status>
I also have a HTML page that has Iframes pulling live camera feeds for IP cameras. I want to hide the iframe and show a graphic instead when the status is ‘killed’.
Does anyone know if this is possible and where I’d start? Somehow check the xml file regularly or somehow know it has been updated.
Then somehow apply classes or introduce elements such as a div to mask the iframe.
Yes, you can work with XML in JavaScript almost the same as if you were working with HTML. However, without a server-side component, writing the xml document back to the file system will not be possible. You can always download it for the user, but you can't write directly to the file system.
Here's a simple example of updating an XML document with JS. I put both the string of xml and the logic to parse string into an xml doc in the example since I'm not sure what your setup is.
const xmlString = `
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
`;
const xmlDoc = new DOMParser().parseFromString(xmlString, 'text/xml');
document.getElementById('btn').addEventListener('click', e => {
const to = xmlDoc.querySelector('note to');
to.innerHTML = 'Someone New';
console.log('The TO field is now ', xmlDoc.querySelector('note to').innerHTML);
// Set HTML Element from XML
const h1 = document.getElementById('fromXml');
h1.innerText = xmlDoc.querySelector('note heading').innerHTML;
});
<button id="btn">Set To</button>
<h1 id="fromXml"></h1>
I have a large JavaScript file that I'd rather not send to the client on each request and it's too large for the browser to cache.
My thought is that I will save the file to HTML5 local storage and attempt to retrieve it. If the file is found then I'd like to link/import/export(I don't know the proper terminology) it into the same scope that a html src tag would.
My question is: how do I take a file that I've pulled from local storage and get my webpage to recognize it as a JavaScript file that was included via src tag? (minus the logic for pulling the file from storage)
My question is: how do I take a file that I've pulled from local storage and get my webpage to recognize it as a JavaScript file that was included via src tag?
Two possible ways (amongst maybe others):
create a script element, and assign your JS code as the “text content” of that element before appending it to the DOM. “Text content” in quotes here, because it is not as simple as it sounds cross-browser – see f.e. Javascript script element set inner text, Executing elements inserted with .innerHTML, or
assign your script code to the src attribute of a script element via a Data URI, data:text/javascript,… – but that approach has several disadvantages as well, also mostly in older IE (size limitation; only “non-navigable” content, meaning no scripts). But depending on your target environment that might well work. You will not necessarily need to base64 encode the script code, URL-percent-encoding via encodeURIComponent should work as well.
Take a look at this:
http://jsfiddle.net/611e96mz/1/
var tag = getId('testjs'),
a = getId('a'),
b = getId('b'),
c = getId('c'),
script;
a.addEventListener('click', function () {
localStorage.setItem('js', tag.innerHTML);
});
b.addEventListener('click', function () {
script.textContent = localStorage.getItem('js');
});
c.addEventListener('click', function () {
document.body.appendChild(script);
alertMe();
});
var script = document.createElement("script");
script.type = "text/javascript";
function getId(x) {
return document.getElementById(x);
}
You can use JSON to stringfy your file content and put it on localstorage.
var content = JSON.stringify([1, "some info"]); // '[1,"some info"]'
localStorage.setItem('fileContent', content);
// Retrieve
var content = localStorage.getItem('fileContent');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
I'm trying to create a menu from an XML file. The HTML file that I want to create the menu in, is located my main project folder. This folder also contains an xml folder in which my xml file (fruitDB.xml) is located. I understood that there are several ways of loading XML files and that some ways only work online. Eventually the menu is used for an HTML5 mobile app (don't know if this is usefull information), build using Appcelerator.
I've read some sources but it's still not clear to me how I can load an XML file. I have the following code in my header tag:
<script type="text/javascript">
function init(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "xml/fruitDB.xml", false);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send();
var xmlDoc = xmlhttp.responseXML;
var Fruits = xmlDoc[];
alert(Fruits);
for (var i = 0; i < Fruits.children.length; i++) {
alert("hi");
var Fruit = Fruits.children[i];
var Name = Fruits.getElementsByTagName("name");
var Thumb = Fruits.getElementsByTagName("image");
var list = document.getElementById("menuButtons");
var listEntry = document.createElement("LI");
listEntry.document.createTextNode(Name);
list.appendChild(listEntry);
}
}
</script>
What I try to do here is open the init(); function using , load the xml file, though I'm not sure if giving a path (like I'm doing) is correct. After the XML is loaded it should create new 's in my HTML file and give them name (and eventually an image) which are stored in the xml file until all items from the xml are placed as list items. Sorry for the long sentence :P.
At xmlhttp.send(); I recieved the following error in my console:
XMLHttpRequest cannot load file:///D:/folder/folder/folder/xml/fruitDB.xml. Received an invalid response. Origin 'null' is therefore not allowed access.
Does this mean that using XMLHttpRequest won't work on local files and if not what other way can I use in order to achieve my goal?
XML doesn't have great support in Titanium. Also XML is often a pain to work with..
Why not use a JSON payload / document instead!
Format the JSON so it is an array of fruit objects
Then you just parse the payload into a javascript object that comes back from the web-service or your local file something like this:
var fruits = JSON.parse(yourHTTPObj.responseData);
Now you can loop over the fruit objects and say:
if (fruits[i].type === 'Apple') { //do something };
I have to create a module in a specific project, which already uses PrototypeJS.
What I have:
- An XML File with information
What I want:
- A simple div, which displays the (with XPath filterd) Content of the XML-File.
I am complete new to PrototypeJS and dont know where to begin, so I appreciate your help.
Blessing
chris
If by "local" you mean "client-side", you will have to :
include a file input for the user to upload the xml file to your server
fetch the xml file by ajax (easiest way) to have it as an xml document in your javascript
parse the xml file with the dedicated API
build an HTML representation of the content using text, images, etc. and include it in your div.
edit: to clarify the fetch part, here is how you can do it using Prototype:
new Ajax.Request('myfile.xml', {
onSuccess: function(transport) {
myParseXml(transport.responseXML);
},
onFailure: function(transport) {
alert('Failure! Status code '+transport.status+' ('+transport.statusText+')');
}
);
function myParseXml(xmlDoc) {
var root = xmlDoc.documentElement;
...
}
Try:
<xml src="MyData.xml" id="mydata" >
var mydata = document.getElementById('mydata');