Removing an element from a text rendered by Javascript - javascript

I have a page with scripts that insert and convert a Markdown file:
<head>
<script type="module" src="https://cdn.jsdelivr.net/gh/zerodevx/zero-md#2/dist/zero-md.min.js"></script>
</head>
<body>
<article>
<zero-md id="text"></zero-md> <!-- the area into which each .md is to be inserted and converted -->
<script>
document.getElementById("text").src="CONVERTME1.md";
</script>
</article>
</body>
The conversion itself works, the text gets displayed. Each .md file will be part of a series, and the scripts will enable me to bypass the process of manually converting the texts, so that I can go back to them for editing frequently and easily. I plan to turn the getElement into navigation buttons for the sequence of .md files, like the chapters of a book to flip back and forth. Before creating those buttons, there is an element in each output of the conversion that will have to be regularly removed. It's a string from the top (first line) of each original .md file. It starts with "tags:", followed by one or more keywords. It's used by the Markdown editor (WriteMonkey) for internal search operations, and I intend to keep them on each .md file for later editing (and auto-conversion/updating), while they serve no purpose in the final output on the HTML page. This string gets converted by the zero-md script as
<p>
::before
"tags: KEYWORD"
</p>
inside
<zero-md id="text">
#shadow-root (open)
<div class="markdown-body">
So I tried
<script>
document.getElementByTagName("p::before").contains("tags:").remove();
</script>
as the last element inside <article>, but it didn't work. Then I tried (in the same place) the jQuery
<script>
$("p::before").contains("tags:").remove();
</script>
, but it too didn't work. I wasn't sure about p::before and .contains("tags:"), so I tried just p to see if it would affect any paragraphs of the main text, and it didn't do anything, everything inside zero-md would remain intact. I checked that elements outside zero-md can be removed. So I assume the problem is that the p (or any element) that is supposed to have been converted from the .md file and available for reference is somehow inaccessible by getElementByTagName at that moment of parsing.
Any solution?
Tangentially: I tried to replace getElementById("text") with getElementByTagName("zero-md") (so as to do away with id="text"), and it didn't work. Why?
Thank you.

It seems like you wish to strip the first <p> tag from the rendered contents. The easiest way to do this looks something like:
<article>
<zero-md id="text">
<template data-merge="append">
<style>
.markdown-body>p:first-child {
display: hidden;
}
</style>
</template>
</zero-md>
<script>
document.getElementById("text").src="CONVERTME1.md";
</script>
</article>

Related

Is it impossible to load a javascript library in a Google colab cell?

I have Python code that creates HTML to visualize a Python object using the _repr_html method. This means I can show the object by simply putting display(obj) in my cell or even just placing obj as the last statement in my cell.
That HTML loads javascript libraries from the Internet, e.g. the jquery library like so:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
However when such a script tag is part of HTML I try to visualize in Colab, it gets completely removed!
For example, the following code in a cell produces output which does not contain the script element any more:
HTML("""
<div id="containing"
<div id="div1">
some text
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</div>
""")
The alternative would be to include the verbatim javascript code in every cell (<script type="text/javascript>..actual javascript ...<script>), which works, but seems like an unnecessary overhead.
Is there a more elegant solution?
Here's an example:
from IPython.display import HTML, Javascript, display
from google.colab import output
display(HTML("""
<div id="div1">
some text
</div>
"""))
display(Javascript(url="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"))
output.eval_js('''
$("#div1").append("<p>Hello, JQuery</p>");
''');
A full notebook with this example is:
https://colab.research.google.com/drive/1xnfhiVsm6u_TkSoni0WaGydigOCPj5Mw

How can I render raw HTML [duplicate]

How can I show HTML snippets on a webpage without needing to replace each < with < and > with >?
In other words, is there a tag for don't render HTML until you hit the closing tag?
The tried and true method for HTML:
Replace the & character with &
Replace the < character with <
Replace the > character with >
Optionally surround your HTML sample with <pre> and/or <code> tags.
sample 1:
<pre>
This text has
been formatted using
the HTML pre tag. The brower should
display all white space
as it was entered.
</pre>
sample 2:
<pre>
<code>
My pre-formatted code
here.
</code>
</pre>
sample 3:
(If you are actually "quoting" a block of code, then the markup would be)
<blockquote>
<pre>
<code>
My pre-formatted "quoted" code here.
</code>
</pre>
</blockquote>
is there a tag for don't render HTML until you hit the closing tag?
No, there is not. In HTML proper, there’s no way short of escaping some characters:
& as &
< as <
(Incidentally, there is no need to escape > but people often do it for reasons of symmetry.)
And of course you should surround the resulting, escaped HTML code within <pre><code>…</code></pre> to (a) preserve whitespace and line breaks, and (b) mark it up as a code element.
All other solutions, such as wrapping your code into a <textarea> or the (deprecated) <xmp> element, will break.1
XHTML that is declared to the browser as XML (via the HTTP Content-Type header! — merely setting a DOCTYPE is not enough) could alternatively use a CDATA section:
<![CDATA[Your <code> here]]>
But this only works in XML, not in HTML, and even this isn’t a foolproof solution, since the code mustn’t contain the closing delimiter ]]>. So even in XML the simplest, most robust solution is via escaping.
1 Case in point:
textarea {border: none; width: 100%;}
<textarea readonly="readonly">
<p>Computer <textarea>says</textarea> <span>no.</span>
</textarea>
<xmp>
Computer <xmp>says</xmp> <span>no.</span>
</xmp>
Kind of a naive method to display code will be including it in a textarea and add disabled attribute so its not editable.
<textarea disabled> code </textarea>
Hope that help someone looking for an easy way to get stuff done.
But warning, this won't escape the tags for you, as you can see here (the following obviously does not work):
<textarea disabled>
This is the code to create a textarea:
<textarea></textarea>
</textarea>
Deprecated, but works in FF3 and IE8.
<xmp>
<b>bold</b><ul><li>list item</li></ul>
</xmp>
Recommended:
<pre><code>
code here, escape it yourself.
</code></pre>
i used <xmp> just like this :
http://jsfiddle.net/barnameha/hF985/1/
The deprecated <xmp> tag essentially does that but is no longer part of the XHTML spec. It should still work though in all current browsers.
Here's another idea, a hack/parlor trick, you could put the code in a textarea like so:
<textarea disabled="true" style="border: none;background-color:white;">
<p>test</p>
</textarea>
Putting angle brackets and code like this inside a text area is invalid HTML and will cause undefined behavior in different browsers. In Internet Explorer the HTML is interpreted, whereas Mozilla, Chrome and Safari leave it uninterpreted.
If you want it to be non-editable and look different then you could easily style it using CSS. The only issue would be that browsers will add that little drag handle in the bottom-right corner to resize the box. Or alternatively, try using an input tag instead.
The right way to inject code into your textarea is to use server side language like this PHP for example:
<textarea disabled="true" style="border: none;background-color:white;">
<?php echo '<p>test</p>'; ?>
</textarea>
Then it bypasses the html interpreter and puts uninterpreted text into the textarea consistently across all browsers.
Other than that, the only way is really to escape the code yourself if static HTML or using server-side methods such as .NET's HtmlEncode() if using such technology.
If your goal is to show a chunk of code that you're executing elsewhere on the same page, you can use textContent (it's pure-js and well supported: http://caniuse.com/#feat=textcontent)
<div id="myCode">
<p>
hello world
</p>
</div>
<div id="loadHere"></div>
document.getElementById("myCode").textContent = document.getElementById("loadHere").innerHTML;
To get multi-line formatting in the result, you need to set css style "white-space: pre;" on the target div, and write the lines individually using "\r\n" at the end of each.
Here's a demo: https://jsfiddle.net/wphps3od/
This method has an advantage over using textarea: Code wont be reformatted as it would in a textarea. (Things like are removed entirely in a textarea)
In HTML? No.
In XML/XHTML? You could use a CDATA block.
I assume:
you want to write 100% valid HTML5
you want to place the code snippet (almost) literal in the HTML
especially < should not need escaping
All your options are in this tree:
with HTML syntax
there are five kinds of elements
those called "normal elements" (like <p>)
can't have a literal <
it would be considered the start of the next tag or comment
void elements
they have no content
you could put your HTML in a data attribute (but this is true for all elements)
that would need JavaScript to move the data elsewhere
in double-quoted attributes, " and &thing; need escaping: " and &thing; respectively
raw text elements
<script> and <style> only
they are never rendered visible
but embedding your text in Javascript might be feasable
Javascript allows for multi-line strings with backticks
it could then be inserted dynamically
a literal </script is not allowed anywhere in <script>
escapable raw text elements
<textarea> and <title> only
<textarea> is a good candidate to wrap code in
it is totally legal to write </html> in there
not legal is the substring </textarea for obvious reasons
escape this special case with </textarea or similar
&thing; needs escaping: &thing;
foreign elements
elements from MathML and SVG namespaces
at least SVG allows embedding of HTML again...
and CDATA is allowed there, so it seems to have potential
with XML syntax
covered by Konrad's answer
Note: > never needs escaping. Not even in normal elements.
It's vey simple ....
Use this xmp code
<xmp id="container">
<xmp >
<p>a paragraph</p>
</xmp >
</xmp>
<textarea ><?php echo htmlentities($page_html); ?></textarea>
works fine for me..
"keeping in mind Alexander's suggestion, here is why I think this is a good approach"
if we just try plain <textarea> it may not always work since there may be closing textarea tags which may wrongly close the parent tag and display rest of the HTML source on the parent document, which would look awkward.
using htmlentities converts all applicable characters such as < > to HTML entities which eliminates any possibility of leaks.
There maybe benefits or shortcomings to this approach or a better way of achieving the same results, if so please comment as I would love to learn from them :)
This is a simple trick and I have tried it in Safari and Firefox
<code>
<span><</span>meta property="og:title" content="A very fine cuisine" /><br>
<span><</span>meta property="og:image" content="http://www.example.com/image.png" />
</code>
It will show like this:
You can see it live Here
You could try:
Hello! Here is some code:
<xmp>
<div id="hello">
</div>
</xmp>
This is a bit of a hack, but we can use something like:
body script {
display: block;
font-family: monospace;
white-space: pre;
}
<script type="text/html">
<h1>Hello World</h1>
<ul>
<li>Enjoy this dodgy hack,
<li>or don't!
</ul>
</script>
With that CSS, the browser will display scripts inside the body. It won’t attempt to execute this script, as it has an unknown type text/html. It’s not necessary to escape special characters inside a <script>, unless you want to include a closing </script> tag.
I’m using something like this to display executable JavaScript in the body of the page, for a sort of "literate progamming".
There’s some more info in this question When should tags be visible and why can they?.
function escapeHTML(string)
{
var pre = document.createElement('pre');
var text = document.createTextNode(string);
pre.appendChild(text);
return pre.innerHTML;
}//end escapeHTML
it will return the escaped Html
Ultimately the best (though annoying) answer is "escape the text".
There are however a lot of text editors -- or even stand-alone mini utilities -- that can do this automatically. So you never should have to escape it manually if you don't want to (Unless it's a mix of escaped and un-escaped code...)
Quick Google search shows me this one, for example: http://malektips.com/zzee-text-utility-html-escape-regular-expression.html
This is by far the best method for most situations:
<pre><code>
code here, escape it yourself.
</code></pre>
I would have up voted the first person who suggested it but I don't have reputation. I felt compelled to say something though for the sake of people trying to find answers on the Internet.
You could use a server side language like PHP to insert raw text:
<?php
$str = <<<EOD
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="Minimal HTML5">
<meta name="keywords" content="HTML5,Minimal">
<title>This is the title</title>
<link rel='stylesheet.css' href='style.css'>
</head>
<body>
</body>
</html>
EOD;
?>
then dump out the value of $str htmlencoded:
<div style="white-space: pre">
<?php echo htmlentities($str); ?>
</div>
There are a few ways to escape everything in HTML, none of them nice.
Or you could put in an iframe that loads a plain old text file.
Actually there is a way to do this. It has limitation (one), but is 100% standard, not deprecated (like xmp), and works.
And it's trivial. Here it is:
<div id="mydoc-src" style="display: none;">
LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo
<!--
YOUR CODE HERE.
<script src="WidgetsLib/all.js"></script>
^^ This is a text, no side effects trying to load it.
-->
LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo
</div>
Please let me explain. First of all, ordinary HTML comment does the job, to prevent whole block be interpreted. You can easily add in it any tags, all of them will be ignored. Ignored from interpretation, but still available via innerHTML! So what is left, is to get the contents, and filter the preceding and trailing comment tokens.
Except (remember - the limitation) you can't put there HTML comments inside, since (at least in my Chrome) nesting of them is not supported, and very first '-->' will end the show.
Well, it is a nasty little limitation, but in certain cases it's not a problem at all, if your text is free of HTML comments. And, it's easier to escape one construct, then a whole bunch of them.
Now, what is that weird LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo string? It's a random string, like a hash, unlikely to be used in the block, and used for? Here's the context, why I have used it. In my case, I took the contents of one DIV, then processed it with Showdown markdown, and then the output assigned into another div. The idea was, to write markdown inline in the HTML file, and just open in a browser and it would transform on the load on-the-fly. So, in my case, <!-- became transformed to <p><!--</p>, the comment properly escaped. It worked, but polluted the screen. So, to easily remove it with regex, the random string was used. Here's the code:
var converter = new showdown.Converter();
converter.setOption('simplifiedAutoLink', true);
converter.setOption('tables', true);
converter.setOption('tasklists', true);
var src = document.getElementById("mydoc-src");
var res = document.getElementById("mydoc-res");
res.innerHTML = converter.makeHtml(src.innerHTML)
.replace(/<p>.{0,10}LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo.{0,10}<\/p>/g, "");
src.innerHTML = '';
And it works.
If somebody is interested, this article is written using this technique. Feel free to download, and look inside the HTML file.
It depends what you are using it for. Is it user input? Then use <textarea>, and escape everything. In my case, and probably it's your case too, I simply used comments, and it does the job.
If you don't use markdown, and just want to get it as is from a tag, then it's even simpler:
<div id="mydoc-src" style="display: none;">
<!--
YOUR CODE HERE.
<script src="WidgetsLib/all.js"></script>
^^ This is a text, no side effects trying to load it.
-->
</div>
and JavaScript code to get it:
var src = document.getElementById("mydoc-src");
var YOUR_CODE = src.innerHTML.replace(/(<!--|-->)/g, "");
This is how I did it:
$str = file_get_contents("my-code-file.php");
echo "<textarea disabled='true' style='border: none;background-color:white;'>";
echo $str;
echo "</textarea>";
It may not work in every situation, but placing code snippets inside of a textarea will display them as code.
You can style the textarea with CSS if you don't want it to look like an actual textarea.
If you are looking for a solution that works with frameworks.
const code = `
<div>
this will work in react
<div>
`
<pre>
<code>{code}</code>
</pre>
And you can give it a nice look with css:
pre code {
background-color: #eee;
border: 1px solid #999;
display: block;
padding: 20px;
}
JavaScript string literals can be used to write the HTML across multiple lines. Obviously, JavaScript, ECMA6 in particular, is required for this solution.
.createTextNode paired with CSS white-space: pre-wrap; does the trick.
.innerText alone also works. Run code snippet below.
let codeBlock = `
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>My Page</title>
</head>
<body>
<h1>Welcome to my page</h1>
<p>I like cars and lorries and have a big Jeep!</p>
<h2>Where I live</h2>
<p>I live in a small hut on a mountain!</p>
</body>
</html>
`
const codeElement = document.querySelector("#a");
let textNode = document.createTextNode(codeBlock);
codeElement.appendChild(textNode);
const divElement = document.querySelector("#b");
divElement.innerText = codeBlock;
#a {
white-space: pre-wrap;
}
<div id=a>
</div>
<div id=b>
</div>
//To show xml tags in table columns you will have to encode the tags first
function htmlEncode(value) {
//create a in-memory div, set it's inner text(which jQuery automatically encodes)
//then grab the encoded contents back out. The div never exists on the page.
return $('<div/>').text(value).html();
}
html = htmlEncode(html)
A combination of a couple answers that work together here:
function c(s) {
return s.split("<").join("<").split(">").join(">").split("&").join("&")
}
displayMe.innerHTML = ok.innerHTML;
console.log(
c(ok.innerHTML)
)
<textarea style="display:none" id="ok">
<script>
console.log("hello", 5&9);
</script>
</textarea>
<div id="displayMe">
</div>
I used this a long time ago and it did the trick for me, I hope it helps you too.
var preTag = document.querySelectorAll('pre');
console.log(preTag.innerHTML);
for (var i = 0; i < preTag.length; i++) {
var pattern = preTag[i].innerHTML;
pattern = pattern.replace(/</g, "<").replace(/>/g, ">");
console.log(pattern);
preTag[i].innerHTML = pattern;
}
<pre>
<p>example</p>
<span>more text</span>
</pre>
You can separate the tags by changing them to spans.
Like this:
<span><</span> <!-- opening bracket of h1 here -->
<span>h1></span> <!-- opening tag of h1 completed here -->
<span>hello</span> <!-- text to print -->
<span><</span> <!-- closing h1 tag's bracket here -->
<span>/h1></span> <!-- closing h1 tag ends here -->
And also, you can just only add the <(opening angle bracket) to the spans
<span><</span> <!-- opening bracket of h1 here -->
h1> <!-- opening tag of h1 completed here -->
hello <!-- text to print -->
<span><</span> <!-- closing h1 tag's bracket here -->
/h1><!-- closing h1 tag ends here -->
<code><?php $str='<';echo htmlentities($str);?></code>
I found this to be the easiest, fastest and most compact.

template insertion in a editor

Describing a scenario:
I am going through the code mentioned below.B asically I am trying to figure out how to program so that
when a user clicks on "Use Template" button , it gets inserted into an editor.
Page 1:
There are lot of templates present
When a user clicks on the "Use Template" button on , it gets inserted into an editor that is present in
the next page (Page 2).
Please find the code snippet below for the first two templates I am going through:
<div id="templatesWrap">
<div class="template" data-templatelocation="templateone" data-templatename="Template ONE" data-templateid="" >
<div class="templateContainer">
<span>
<a href="https://app.abc.com/pqr/core/compose/message/create?token=c1564e8e3cd11bc4t546b587jan31&sMessageTemplateId=templateone&sHubId=&goalComplete=200" title="Use Template">
<img class="thumbnail" src="templatefiles/thumbnail_010.jpg" alt="templateone">
</a>
</span>
<div class="templateName">Template ONE</div>
<p>
Use Template
</p>
</div>
</div>
<div class="template" data-templatelocation="templatetwo" data-templatename="Template TWO" data-templateid="" >
<div class="templateContainer">
<span>
<a href="https://app.abc.com/pqr/core/compose/message/create?token=c1564e8e3cd11bc4t546b587jan31&sMessageTemplateId=templatetwo&sHubId=&goalComplete=200" title="Use Template">
<img class="thumbnail" src="templatefiles/thumbnail_011.jpg" alt="templatetwo">
</a>
</span>
<div class="templateName">Template TWO</div>
<p>
Use Template
</p>
</div>
</div>
And so on ....
How does the link "https://app.abc.com/pqr/core/compose/message/create?token=c1564e8e3cd11bc4t546b587jan31&sMessageTemplateId=templatetwo&sHubId=&goalComplete=200" is inserting the template into the editor which is located on the next page? I haven't understood the token part and lot's of ID's present in the link
which I think are thereason behind inserting the template.
Has anyone come across such link before? Please advise.
Thanks
MORE CLARIFICATIONS:
Thanks for your answer.It did help me somewhat. I have few more questions:
Basically, I am using TinyMCE 4.0.8 version as my editor. The templates, I am using are from here:
https://github.com/mailchimp/email-blueprints/blob/master/templates/2col-1-2-leftsidebar.html
Some questions based on "Tivie" answer.
1) As you can see in the code for "2col-1-2-leftsidebar.html " it's not defined inside <div> tags unlike you defined it in <div> tags. Do you think that I can still
use it using "2col-1-2-leftsidebar.html " name?
2)I believe,for explanation purpose, you have included
`"<div contenteditable="true" id="myEditor">replaced stuff</div>`
and
<button id="btn">Load TPL</button>
<script>
$("#btn").click(function() {
$("#myEditor").load("template.html");
});
</script>
in the same page. Am I right? ( I understand you were trying to make an educated guess here, hence
just asking :) )
In my case, I have a separate page, where I have written code for buttons just like you wrote in editor.html like the following:
<button id="btn">Load TPL</button>. My button is defined inside <div class="templateContainer">.
Also, my templates are defined in a separate folder. So, I will have to grab the content(HTML Template), from
that folder and then insert into TinyMCE 4.08 editor. (Looks like two step process). Could you elaborate
on how should I proceed here?
More Question As of Dec 27
I have modifier my code for the template as follows:
<div class="templateName">Template ONE</div>
<p>
Use Template
</p>
Please note, I have added an additional id attribute for the following purpose.
If I go by the answer mentioned in the Tivia's post, is the following correct?
<script>
$("#temp1").click(function() {
$("#sTextBody").load("FolderURL/template.html");
});
</script>
My editor is defined like the following on Page 2 (Editor Page).
<div class="field">
<textarea id="sTextBody" name="sTextBody" style="width:948px; max-width:948px; height: 70%"></textarea>
</div>
I am confused, like, the script tag I have defined is in Page 1 where I have defined all the template related code
and the Page 2(Editor) page is a different page. It's simply taking me to Editor page (Page 2) and hence not working.
Please advise where I am wrong.
Thanks
MORE QUESTIONS AS of Jan 2
The problem Iam facing is as follows. Basically, for first template , I have the following code.
Code Snippet #1 where "Use "Template" button is present:
<div class="templateName">Template ONE</div>
<p>
Use Template
</p>
And the function suggested in the answer is as follows:
Code Snippet #2 where Editor is present:
<script>
$("#temp1").click(function() {
$("#sTextBody").load("FolderURL/template.html");
});
</script>
Since, I believe I first need to reach to that page after user clicks on "Use Template" button, where the editor is located, I have defined Code Snippet #1 on Page 1 and have defined the Code Snippet #2 and <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> as the very first two script tags in the Page 2 ( Editor Page). But still when I click on "User Template" button on Page 1, it's just letting me to next page and not loading the template into the editor.
Am I doing something wrong here? Please advise.
P.S. The problem I feel is somehow the click function on Page 2 is not getting activated with the temp1 id button mentioned on Page 1.
Thanks
Well, one can only guess without having access to the page itself (and it's source code). I can, however, make an educated guess on how it works.
The URL params follows a pattern. First you have a token that is equal in all templates. This probably means the token does not have any relevance to the template mechanism itself. Maybe it's an authentication token or something. Not relevant though.
Then you have the template identification (templateOne, templateTwo, etc...) followed by a HubId that is empty. Lastly you have a goalComplete=200 which might correspond to the HTTP success code 200 (OK).
Based on this, my guess would be that they are probably using AJAX on the background, to fetch those templates from the server. Then, via JScript, those templates are inserted into the editor box itself.
Using JQuery, something like this is trivial. here's an example:
template.html
<div>
<h1>TEST</h1>
<span>This is a template</span>
</div>
editor.html
<!DOCTYPE HTML>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div contenteditable="true" id="myEditor">
replaced stuff
</div>
<button id="btn">Load TPL</button>
<script>
$("#btn").click(function() {
$("#myEditor").load("template.html");
});
</script>
</body>
</html>
Edit:
1) Well, since those templates are quite complex and include CSS, you probably want to keep them separated from you editor page (or the template's CSS will mess up your page's css).
However, since you're using TinyMCE, it comes with a template manager built in, so you probably want to use that. Check this link here http://www.tinymce.com/wiki.php/Configuration:templates for documentation.
2) I think 1 answers your question but, just in case, my method above works for any page in any directory, provided it lives on the same domain. Example:
<script>
$("#btn").click(function() {
$("#myEditor").load("someDirectory/template.html");
});
</script>
I recomend you check this page for the specifics on using TinyMCE http://www.tinymce.com/wiki.php/Configuration:templates
EDIT2:
Let me explain the above code:
$("#btn").click(function() { });
This basically tells the browser to run the code inside the brackets when you click the element with an id="btn"
$("#myEditor").load("someDirectory/template.html");
This is an AJAX request (check the documentation here). It grabs the contents of someDirectory/template.html and places them inside the element whose id="myEditor"

innerHTML does not work with Javascript output contents

I try to make some kind of ads rotator as follows:
<html>
<head>
<title></title>
<style>
body {
margin:0;
padding:0;
}
</style>
<script>
function fillBoard() {
s = document.getElementsByClassName('slots');
board = document.getElementById('board');
board.innerHTML = s[0].innerHTML
alert(board.innerHTML);
}
</script>
</head>
<body>
<div id="board" style="width:160px; text-align: center; margin:0">
</div>
<div class="slots" style="display:none">
<!-- THE PROBLEM IS HERE -->
<!-- Begin Hsoub Ads Ad Place code -->
<script type="text/javascript">
<!--
hsoub_adplace = 1310003403401506;
hsoub_adplace_size = '125x125';
//-->
</script>
<script src="http://ads2.hsoub.com/show.js" type="text/javascript"></script>
<!-- End Hsoub Ads Ad Place code -->
</div>
<div class="slots" style="display:none">
<img src="http://lorempixel.com/160/90/sports/1/" />
</div>
<div class="slots" style="display:none">
<img src="http://lorempixel.com/160/90/sports/2/" />
</div>
<div class="slots" style="display:none">
<img src="http://lorempixel.com/160/90/sports/3/" />
</div>
<script>
fillBoard();
</script>
</body>
</html>
In the code above:
There is a div with id board to act as a board that displays contents.
The board should be filled with data supplied from other hidden divs with class name slots using innerHTML property.
To do the above a function named fillBoard() is defined in the head section of the page and then called at the end of it just before closing </body> tag.
What is happening?
The hidden divs slots works fine with divs that contain images. However, in the first div there are a javascript code that should generates ads from an ads network which it does not work.
I expect that the javascript code of the ads network should fill its div with data, then the calling of fillBoard() will just copy its content to the board div. However, this is does not occur!
I need to know how could I overcome this issue?
A live example is found here
You can just show the desired hidden div and it's usually a better practice than copying DOM content. If you make sure to only show one of the hidden divs at a time you can show the image always in the same place.
Try this to show the first "slots" element:
s[0].style.display = 'block';
Ok so after some more digging I've found the issue, although I don't have an easy solution at the moment.
The js file show.js is generating some ad content inside of an iframe for you, which you are placing in the first 'slots' div. Simple enough. When you are setting the content of the board to the content of the first slots class, an iframe is being created in the board div but without the same content.
After some searching it seems that innerHTML of an iframe will not copy the contents of the iframe if it comes from a domain other than the page domain for security reasons.
It seems to me that the solution at this point is to either show and hide the slots divs like Zhertal suggested or you can possible find some other way to physically move the content of the slots div into board, but this may still be a violation of the same security concern. I'm going to keep digging and I'll edit this answer if I find anything more.
Reference SO posts:
Get IFrame innerHTML using JavaScript
Javascript Iframe innerHTML

Updating the content of a div with javascript

Rather than trying to create tons of different pages on my website, I'm trying to update the content of a single div when different items in the navbar are click to update the maint div content. I tried to find a simple example using Javascript:
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
<div id="example1div" style="border-style:solid; padding:10px; text-align:center;">
I will be replaced when you click.
</div>
<a href="javascript:ReplaceContentInContainer('example1div', '<img src='2.jpg'>' )">
Click me to replace the content in the container.
</a>
This works just fine when I only try and update text, but when I put an img tag in there, as you can see, it stops working.
Either
1) what is the problem with how I am trying to do it?
or 2) What is a better/easier way to do it?
I'm not stuck on Javascript. jQuery would work too, as long as it is just as simple or easy. I want to create a function that will just let me pass in whatever HTML I want to update and insert it into the div tag and take out the 'old' HTML.
You just have some escaping issues:
ReplaceContentInContainer('example1div', '<img src='2.jpg'>')
^ ^
The inner ' need to be escaped, otherwise the JS engine will see ReplaceContentInContainer('example1div', '<img src=' plus some syntax errors resulting from the subsequent 2.jpg'>'). Change the call to (tip of the hat to cHao' answer concerning escaping the < and > in the HTML):
ReplaceContentInContainer('example1div', '<img src=\'2.jpg\'>')
A simple way to do this with jQuery would be to add an ID to your link (say, "idOfA"), then use the html() function (this is more cross-platform than using innerHTML):
<script type="text/javascript">
$('#idOfA').click(function() {
$('#example1div').html('<img src="2.jpg">');
});
</script>
First of all, don't put complex JavaScript code in href attributes. It's hard to read or to maintain. Use the <script> tag or put your JavaScript code in a separate file altogether.
Second, use jQuery. JavaScript is a strange beast: the principles underlying its patterns were not designed with modern-day web development in mind. jQuery gives you lots of power without miring you in JavaScript's oddities.
Third, if your goal is to avoid having to endlessly duplicate the same basic structure for all (or many) of your pages, consider using a templating system. Templating systems allow you to plug in specific content into scaffolds containing the common elements of your site. If it sounds complicated, it's because I haven't explained it well. Google it and you'll find lots of great resources.
Relying on JavaScript for navigation means your site won't be indexed properly by search engines and will be completely unusable to someone with JavaScript turned off. It is increasingly common--and acceptable--to rely on JavaScript for basic functionality. But your site should, at minimum, provide discrete pages with sensible and durable URLs.
Now, all that said, let's get to your question. Here's one way of implementing it in jQuery. It's not the snazziest, tightest implementation, but I tried to make something very readable:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Example</title>
<style type="text/css" media="all">
/* all content divs should be hidden initially */
.content {
display: none;
}
/* make the navigation bar stand out a little */
#nav {
background: yellow;
padding: 10px;
}
</style>
</head>
<body>
<!-- navigation bar -->
<span id="nav">
about me |
copyright notice |
a story
</span>
<!-- content divs -->
<div class="content" id="about_me">
<p>I'm a <strong>web developer</strong>!</p>
</div>
<div class="content" id="copyright">
<p>This site is in the public domain.</p>
<p>You can do whatever you want with it!</p>
</div>
<div class="content" id="my_story">
<p>Once upon a time...</p>
</div>
<!-- jquery code -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
// Wait for the document to load
$(document).ready(function() {
// When one of our nav links is clicked on,
$('#nav a').click(function(e) {
div_to_activate = $(this).attr('href'); // Store its target
$('.content:visible').hide(); // Hide any visible div with the class "content"
$(div_to_activate).show(); // Show the target div
});
});
</script>
</body>
</html>
Ok, hope this helps! If jQuery looks attractive, consider starting with this tutorial.
Your main problem with your example (besides that innerHTML is not always supported) is that < and > can easily break HTML if they're not escaped. Use < and > instead. (Don't worry, they'll be decoded before the JS sees them.) You can use the same trick with quotes (use " instead of " to get around quote issues).

Categories

Resources