How can I shorten this jQuery .load() code? - javascript

I have a script on a page referencing a function in an external script (it converts a Markdown file to HTML and displays it as the innerHTML of a div):
$(document).ready(function() {
let input = document.getElementById('input');
let output = document.getElementById('output');
$("#input").load("convertme.md", function() {
output.innerHTML = convert(input.innerText);
});
});
with:
<div id="input" style="display: none;"></div>
<div id="output"></div>
This way, convert() works fine, the original markups become proper HTML tags. But I want to shorten the code, by merging the two div into one, say <div id="content"></div>, as the only innerText area to be handled by the function (so that I wouldn't have to hide the pre-conversion text). I changed the function to:
$(document).ready(function() {
let content = document.getElementById('content');
$("#content").load("convertme.md", function() {
content.innerHTML = convert(content.innerText)
});
});
This way, however, the conversion is imperfect: it fails to convert the Markdown paragraphs into p, such that all the paragraphs following each header become embedded inside <h1>...</h1> etc instead of <p>...</p>. Why?
Or is there a better way to merge the input and output div?

Related

Replacing Text with Images When Text is Loaded via PHP

so I'm currently working in the development of site and I'm wanting to replace text in divs with images, I've seen a few examples on here however they don't repeat for multiple strings of the same text or the javascript loads before the PHP and doesn't change the text.
<div class="text">text1</div>
<div class="text">text2</div>
<div class="text">text1</div>
I'm needing text1 to replace with image1 and text2 to replace with image2 etc etc. What would the best way to do this ?
I forgot to include that it's a CMS so I don't have access to the PHP directly, just the HTML templates it uses.
This snippet loops over the .text elements and gets the text# value from each element. Then extracts the number of each text and uses it to create a new image. Whenever the image has been loaded with the correct src it will remove the text and replace it with the image.
const textElements = document.querySelectorAll('.text');
for (const textElement of textElements) {
let text = textElement.textContent;
let numberOfText = text.split('text').pop();
const image = new Image();
image.addEventListener('load', event => {
textElement.removeChild(textElement.firstChild);
textElement.append(image);
});
image.src = `/image${numberOfText}`;
}
<div class="text">text1</div>
<div class="text">text2</div>
<div class="text">text1</div>

write html code in div and see result instantly

How to setup a div to see the instant result of html by making the div contenteditable. Like
<div id="edit" contenteditable="true"></div>
<button id="trigger">Apply code</button>
Here, div id="edit" assumed to be editor and result viewer as well itself. e.g. write code on div then click on "Apply code" button and the result of html code written in div should be appeared within the same div (i.e. div id="edit").
html
<div id="edit" contenteditable="true"></div>
<button id="trigger" onclick="applyCode()">Apply code</button>
js
function applyCode() {
$('#edit').html($('#edit').html());
}
So here's the basic setup of what you're trying to do...
<div id='editor' contenteditable></div>
<button id='trigger' value='apply'>
And the JS code:
document.getElementById('trigger').addEventListener('click', (function(dv)
{
return function()
{
dv.innerHTML = dv.textContent;
};
}(document.getElementById('editor'))), false);
Here's a fiddle.
But play around with it, and you'll soon find out that there's a problem with it: Try adding markup tags, and edit the input a second time. That's not going to work as well as you'd hope.
Also check out the resulting DOM, after the user puts in some multi-line input: new divs, paragraphs and what have you are added. You'll have to preserve that markup, using something like:
document.querySelector('#editor').addEventListener('click', function()
{
var currentMarkup = this.innerHTML;
}, false);
Then, you'll have to set about sharing that innerHTML with the trigger event handler, and find a way to check if the user changed the actual markup. Have fun with that...
I suggest you use tools that have already been written, tried and tested, instead of setting about building your own.
It'll take you too long, and you'll end up with something that's not even half as capable as the existing editors out there.
Check this related post for details: Replace words of text area
First you need to create an input box where you can type your html code.
<div id="edit"><textarea id='editor'></textarea></div>
Then there is the button, which 'renders' the code.
<button id="trigger">Apply code</button>
Next, you need to create a javascript code which changes the content of '#edit' to '#editor' 's value.
var edit = document.getElementById('edit');
var editor = document.getElementById('editor');
var trigger = document.getElementById('trigger');
trigger.onclick = function() {
edit.innerHTML = editor.value;
};
Fiddle: http://jsfiddle.net/W75Ut/1/
<div id="editable" contenteditable="true">aaaaaaa</div>
<br/>
<button onclick="texttohtml()">Click to apply Html</button>
<script>
function texttohtml()
{
var t=$("#editable").text();
$("#editable").html(t);
}
</script>

How could I place text inside a document at the script tag?

I'm wondering if its possible to write in a document with Javascript by using the script tags as a reference, instead of some section found with document.getElementById("id") or something like that.
Example: I have a form where, when you put values in the inputs and press enter, it writes text to the document that uses the previously entered values.
Now, I know it would obviously be easier to go ahead and send it to a function with onSubmit in the head, but with the way this is set up it formats easier if I can write it out in this way. So, if anyone know how this could be achieved, tell me please, thanks.
<div style="text-align: center; font-size: 15pt; padding-top: 70px;">
<form onSubmit="reveal(this.a.value, this.b.value)">
a = <input name="a"/>
b = <input name="b"/>
</form>
<hr>
<script>
function reveal(a, b)
{
[math]a + b = c[math]
}
</script>
</div>
You can see what I have so far here on it. If anyone can tell me how to write the [math]a + b = c[math] to the document using the script tags as reference.
Clarification Of Attempted Result: [math]a + b = c[math] represents the text that I want to place in the document, as of now I don't have anything set up to actually write it, which is why its just sitting there. I want it to be placed in the document at the location of the script tags, the ones surrounding the function reveal(). How can I place that text in the document at the location of the surrounding script tags?
I believe this is what you are trying to do: find the script tag that has the function reveal(), then insert the string before or after the script tag.
If it is the case, then try this: (jQuery is used for the sake of simplicity)
var tag = $("script").filter(function () {
return /reveal\(\)/.test(this.innerText); //Find the script tag that has
}); // the function "reveal()"
tag.after("[math]a + b = c[math]"); //Insert your text
- or -
$("<span>[math]a + b = c[math]</span>").replaceAll(tag); //Replace it
Demo
PS:
If you already have a script tag, then why don't you just do this:
<script>
function reveal(){
blah();
}
document.write("[math]a + b = c[math]"); //The text will be inserted where
//the script tag is located at
</script>

IE9, Javascript: Create and append a new element

I'm having some serious trouble getting my code to work in IE9, works fine in Chrome & Firefox but I throws some errors. Here are my 2 functions:
function insertHTML(content){
var body=document.getElementsByTagName('body');
body[0].appendChild(createElement(content));
}
function createElement(string){
var container=document.createElement('div');
container.innerHTML=string;
var element=container.firstChild.cloneNode(true);
return element;
}
I've tried severel methods for this and none seem to work, I'll explain exactly what I need to do...
...I need to create a new element from an html string, the string is sent back from an ajax call so my script will have almost no idea what it contains until it gets it.
I did try using element.innerHTML but this is no good, because if i have one html element (form) on the screen and the user enters data into it, and then when another element is inserted it will wipe all the user-entered data from the first form. I was doing element.innerHTML+=newData;
So basically, I need 2 things:
1) A way to create a new element from an html string.
2) A way to append the element to the document body.
It all needs to work cross-browser and I'm not allowed to use jQuery, also the new element cannot be contained in a div parent item, it has to have the body as its parent.
Thanks very much for your help,
Richard
innerHTML is read write and will destroy anything inside your div. use with extreme care
function insertHTML( htmlString ){
var bodEle = document.getElementsByTagName('body');
var divEle = createElement("div");
divEle.innerHTML = htmlString;
bodEle.appendChild(divEle);
}
So basically, I need 2 things:
A way to create a new element from an html string.
A way to append the element to the document body.
It all needs to work cross-browser and I'm not allowed to use jQuery, also the new element cannot be contained in a div parent item, it has to have the body as its parent.
The following was tested in IE8
<!DOCTYPE html>
<html>
<body>
<script>
var divBefore = document.createElement('div');
var divAfter = document.createElement('div');
var htmlBefore = '<span><span style="font-weight: bold">This bold text</span> was added before</span>';
var htmlAfter = '<span><span style="font-weight: bold">This bold text</span> was added after</span>';
divBefore.innerHTML = htmlBefore;
divAfter.innerHTML = htmlAfter;
document.body.appendChild(divBefore);
setTimeout(function() {
document.body.appendChild(divAfter);
}, 0);
</script>
<div>This content was here first</div>
</body>
</html>
Renders
This bold text was added before
This content was here first
This bold text was added after
https://www.browserstack.com/screenshots/7e166dc72b636d3dffdd3739a19ff8956e9cea96
In the above example, if you don't need to be able to prepend to the body (i.e. insert content before what already exists), then simply place the script tag after the original content and don't use setTimeout.
<!DOCTYPE html>
<html>
<body>
<div>This content was here first</div>
<script>
var divAfter = document.createElement('div');
var htmlAfter = '<span><span style="font-weight: bold">This bold text</span> was added after</span>';
divAfter.innerHTML = htmlAfter;
document.body.appendChild(divAfter);
</script>
</body>
</html>

Function to display html code rather than display elements in browser using Javascript

I want to have the innerHTML of my div element to contain some HTML code, rather than displaying the expected result of that html as the browser normally would. How do I do this using Javascript?
With normal JavaScript:
var div = document.getElementById('foo');
while (div.firstChild) {
div.removeChild(div.firstChild);
}
div.appendChild(document.createTextNode(html));
With jQuery:
$('#foo').text(html);

Categories