HTML: nesting strings in strings in attributes - javascript

My website contains bootstrap popovers with HTML code. Such a popover looks like this (instead of the popup HTML, I've put in a placeholder for readability):
<mark data-content="Fancy HTML here" data-html="true" data-toggle="popover">
This mark has a popover
</mark>
Inserting real HTML in the data-content brings up the problem of escaping quotes properly. I found this question, which looks like an exact duplicate:
How do I encode html for Bootstrap popover and tooltip content
The accepted answer recommends to escape quotes to "
This doesn't work, the escaped quotes are not parsed properly. I've set up an example in this fiddle: https://jsfiddle.net/z4t2sud3/3/
Another option is to use single quotes ' for strings inside the popup. This option is also in the fiddle and it works properly.
But what if I want to nest deeper? For example, the HTML that I insert into the data-content could contain popovers, too. While this seems like a very bad design idea, it would be nice to make it work.
Here is a fiddle for the double-nested popover: https://jsfiddle.net/cwz3sayj/3/

Hoping the snippet below looks like what you wanted, you can pass an option while creating a popover instance where you set the content that will be showed when the instance is clicked. Since the first level isn't present in the DOM when you first run the script, you have to activate the second popover after the first one has been clicked. Using template literals, you can use either apostrophe or quotation mark in the html code you're writing.
$('#firstPopover')
.popover({
html: true,
content: `<button id="secondPopover" class="btn">
Goto second level
</button>`
})
.on('shown.bs.popover', function() {
$('#secondPopover').popover({
html: true,
content: `This is the last level`
});
});
<br />
<button id="firstPopover" data-html="true" class="btn">
Goto first level
</button>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
The only problem is see right now is when the first layer is closed before the second one.

Related

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.

Is there a way to change a style/html on a specific tagged page on Tumblr blog?

I have a pretty good understanding of HTML & CSS, but I am having trouble with the Tag Page feature of tumblr. On my blog for every tagpage, I have a heading being grabbed from the name of the tag. I do not want to change the URL. I want to change the heading on the page, but that heading is being grabbed from the {tag}. The tag is vld. Instead of the page saying vld, I want it to say "All Designs". Pretty much overriding the {tag} for just the /tagged/vld tagpage. The TagPage code is:
{block:TagPage}
<div class="tagtitle">{tag}s</div>
{/block:TagPage}
For /tagged/vld, I want the heading on the page to be "All Designs" instead of "vld". how can I make this change for this specific tagpage?
I have tried
{block:TagPage}
<div class="tag" id="{Tag}">All Designs</div>
{/block:TagPage}
My code being:
{block:TagPage}
<div class="tagtitle" id="vld">All Designs</h2>
{/block:TagPage}
I have also tried
<script>
switch(window.location.pathname) {
case "/tagged/vld":
$('.tagtitle').text('All Designs');
break;
}
});
</script>
But neither of the methods have worked - everything is still showing the tag as the heading. You can see my blog at vintagelovedesigns.tumblr.com
OK, I have a test version working here using one of your themes:
https://madox-test.tumblr.com/tagged/vld
Your switch statement should be throwing an error as you have an additional closing bracket.
The script should look like this:
<script type="text/javascript">
$(document).ready(function(){ // if you are using jquery it is a good idea
// to wrap code in a document ready function
switch(window.location.pathname) {
case "/tagged/vld":
$('.tagtitle').text('All Designs');
break;
};
});
</script>
Hope this helps.

Javascript / Greasemonkey / Userscript.js identify element and remove one of many classes

I've spent far too many hours trying to figure this out and as JavaScript is not my primary language and not yet a jQuery guru I've determined I need to ask for help.
In a case where a generated page has a structure where it has a DIV for some odd reason no ID, multiple non-standard data tag attribute tags, but at least standard style CLASS assignment....however...it has been assigned MULTIPLE classes.
Now, just one of those style classes is such that it has a code event associated that I want to neuter and leave all other classes still assigned. What I've tried there (this list is far from complete I have tried many things):
document.getElementsByClassName('Goodclass01')[0].remove('BADCLASS');
document.querySelectorAll('[data-tag-one="["value",
"value"]"]').remove('BADCLASS');
Various jnode calls that all fail due to claims of being unknown
A couple variations of something referred to as the "location hack" none of
which I could get to work but may have very well have been user error.
Safewindow attempt to just replace BADCLASS javascript function all together
but not ideal explained below.
Here is an example of the kind of structure of the target:
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one="["value", "value"]">
</div>
In this example there is a javascript function that fires upon clicking the href link above due to the function being associated with BADCLASS style assignment. So, from lots of searching it seemed like I should be able to grab that DIV by any of the initially assigned classes (since there is unfortunately not a class ID which would make it very easy) but then reassign the list of classes back minus the BADCLASS at page load time. So, by the time the user clicks the link, the BADCLASS has been removed to look like this:
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03"
data-tag-one="["value", "value"]">
</div>
I also read that simply using unsafewindow to replace the BADCLASS javascript function could be possible, so I am open to hearing one of you gurus help with how easy (or hard) that would be. In a case where BADCLASS could be shared function code perhaps called by another element on the page still having that initial class that perhaps we desire to continue to function which is why if it is only a single element that needs to be altered, I would rather just change this one href div.
Hope the explanation makes sense and what is probably a laughable simple example above for the Javascript gurus so forgive me but your help is greatly appreciated and will save more hair pulling! :)
EDIT: This must work above all in Chrome browser!
Remove the class from all elements
If you want to remove the class from all elements that have the class, simply select all of the elements with that class and remove the class from their class lists.
[...document.querySelectorAll('.BADCLASS')]
.forEach(e => e.classList.remove('BADCLASS'));
const elements = [...document.querySelectorAll('.BADCLASS')];
elements.forEach(e => e.classList.remove('BADCLASS'));
console.log(elements);
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one='["value", "value"]'>link</a>
</div>
Using jQuery:
$('.BADCLASS').removeClass('BADCLASS');
const elements = $('.BADCLASS');
elements.removeClass('BADCLASS');
console.log(elements);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one='["value", "value"]'>link</a>
</div>
Remove the class from a subset of elements
If you only want to remove the class from a subset elements, select those elements then from the class from their class lists.
[...document.querySelectorAll('.Goodclass01, .Goodclass02, .Goodclass03')]
.forEach(e => e.classList.remove('BADCLASS'));
const elements = [...document.querySelectorAll('.Goodclass01, .Goodclass02, .Goodclass03')];
elements.forEach(e => e.classList.remove('BADCLASS'));
console.log(elements);
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one='["value", "value"]'>link</a>
link
</div>
Using jQuery:
$('.Goodclass01, .Goodclass02, .Goodclass03').removeClass('BADCLASS');
const elements = $('.Goodclass01, .Goodclass02, .Goodclass03');
elements.removeClass('BADCLASS');
console.log(elements);
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one='["value", "value"]'>link</a>
link
</div>
Run at document idle
The default for the run-at directive is document-idle, but if for some reason that has been changed, either it needs to be document-idle, or you need to otherwise delay execution of the script until the document has loaded.
You could use the run-at directive in the userscript header like so:
// #run-at document-idle
Or attach a load event listener to the window
window.addEventListener('load', function() { /* do stuff */ }, false);
Include jQuery
If you're using one of the jQuery solutions, you will have to include jQuery using the require userscript header directive like so:
// #require https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
Got it with the help of both of the clear, awesome correct answers below that literally came in within seconds of each other and only a few min after my post, so thanks to both #Tiny and #Damian below!
I'm upvoting both as they both listed the same correct jQuery answers, and Tiny also provided the pure JS.
I am posting the full answer below because without the other steps, with Tamper/Greasemonkey neither will produce the desired results.
First, Tamper/Greasemonkey do not load jQuery by default, so it is just easy as add #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.mi‌​n.js to your current script and also put this.$ = this.jQuery = jQuery.noConflict(true); to avoid any versioning conflicts.
Also, in this case unfortunately I HAD to change my TamperMonkey header to:
// #run-at document-idle
along with the above mentioned:
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
and begin the script with:
this.$ = this.jQuery = jQuery.noConflict(true);
and finally the primary accepted/best answer in this case of:
$('.Goodclass01').removeClass('BADCLASS');
NOTE: The above #run-at line is required, and since so many (all) of my current Tamper/Greasemonkey scripts are actually set by default to run at START, this is of importance as it means functions like this must be separated to their own scripts to run instead AFTER the page loads (idle). Once this is added, even the above pure JS answer from Tiny did in fact produce the desired result.
As the simplest one-line answer that I was hoping was possible in Javascript, as it is so many other languages in a single line of code. I've used it in the past, but was not aware of this particular removeClass method.
Your question mentions jQuery. Did you want a solution in jQuery?
If so, it's as easy as:
$(".Goodclass01").removeClass("badclass");
Explanation:
jQuery can be referenced as jQuery() or $(). The parameters you can pass are: 1, a Selector statement (like CSS), and 2, context (optional; default is document).
By stating $(".Goodclass01") you are stating, "Give me a jQuery object with all elements that have the class Goodclass01." Then, by using the removeClass() function, you can either pass it no parameters and it would remove all classes, or you can pass it specific classes to remove. In this case, we call .removeClass("badclass") in order to remove the undesired class.
Now, if you need to select only specific elements, such as links that have Goodclass01, you can do:
$("a.GoodClass01").removeClass("badclass");
Or, if you want to select anything that has Goodclass01, but NOT Goodclass02, you can do:
$(".Goodclass01:not(.Goodclass02)").removeClass("badclass");
jQuery is not as intimidating as it looks. Give it a shot!
Edit: I also noticed you were trying to capture a link with maybe a specific property. You can use the [property] syntax to select elements that have a specific property. Most typically, people use $("a[href^=https]") or something to that effect to select all a tags with the property href that begins with ^= the string https.
You could, in your case, use the following...
$("a[data-tag-one]")
... to select all links that have the property data-tag-one.
Note: One thing to keep in mind is that, a jQuery object is different than a pure DOM element. If you have a collection of multiple elements and want to use a pure JavaScript function on one element in particular, you would have to reference it with either [0] or .get(0). Once you do that, you will no longer be able to use jQuery methods until you convert it back to a jQuery object.
But, since jQuery has a whole slew of methods to use to make DOM manipulation easier, you can probably accomplish what you need to using those methods.
Edit: I've included a snippet below so you can see some of the jQuery selectors in action.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
div#main * { background-color: #66ff66; }
div#main .BADCLASS, div#main .BADCLASS * { background-color: #ff8888 !important; }
</style>
<div id="main">
<div class="main_content" data-tag-id="12345">Some stuff sits above</div>
<a href="SOME LINK" class="Goodclass01 Goodclass02 Goodclass03 BADCLASS"
data-tag-one='["value", "value"]'>All classes and data-tag-one</a><br />
<a href="SOME LINK" class="Goodclass01 BADCLASS" data-tag-one='["value", "value"]'>Goodclass01 and data-tag-one</a><br />
All classes, no data-tag-one<br />
<a href="SOME LINK" class="BADCLASS" data-tag-one='["value", "value"]'>Just BADCLASS and data-tag-one</a><br />
<br />
<table class="Goodclass01 BADCLASS"><tr><td>Here is a table</td></tr><tr><td>with Goodclass01 and BADCLASS</td></tr></table>
</div>
<hr>
<div id="buttons">
$(".Goodclass01").removeClass("BADCLASS");<br />
$("a.Goodclass01").removeClass("BADCLASS");<br />
$(".Goodclass01:not(.Goodclass02)").removeClass("BADCLASS");<br />
$("a[data-tag-one]").removeClass("BADCLASS");<br />
Reset the HTML<br />
</div>
<script>
$("#button1").click(function(){
$(".Goodclass01").removeClass("BADCLASS");
});
$("#button2").click(function(){
$("a.Goodclass01").removeClass("BADCLASS");
});
$("#button3").click(function(){
$(".Goodclass01:not(.Goodclass02)").removeClass("BADCLASS");
});
$("#button4").click(function(){
$("a[data-tag-one]").removeClass("BADCLASS");
});
$("#button5").click(function(){
var str = '<div class="main_content" data-tag-id="12345">Some stuff sits above</div>All classes, no data-tag-one<br /><a href="SOME LINK" class="BADCLASS" data-tag-one=\'["value", "value"]\'>Just BADCLASS and data-tag-one</a><br /><br /><table class="Goodclass01 BADCLASS"><tr><td>Here is a table</td></tr><tr><td>with Goodclass01 and BADCLASS</td></tr></table>';
$("div#main").html(str);
});
</script>

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"

How to keep line breaks in CKEditor WYSIWYG editor

I have an HTML code as follows
<div class="editable" ...>
<div class="code">
This is an example.
This is a new line
</div>
</div>
In CSS, code has "word-wrap: pre" attribute, such that the text in the inner DIV will show two lines. I use CKEditor with DIV replacement method to edit it. However, it becomes
<div class="code">
This is an example.This is a new line
</div>
The text inside the HTML tag will become one line long, beginning and trailing spaces and new line are stripped. So in CKEditor, although I have specified the config.contentsCss, it still shows one line because CKEditor has merge those two lines into one (I checked this in Chrome "Inspect Element" in CKEditor's iframe editor). Therefore, I see the source code or saved HTML, two lines format is not preserved because they are only one line.
I've googled and tried the CKEditor HTML writer or addRules to restrict the indent format and new line in begin/close tags, however, those seems work on HTML tags, not the document text. Is there any other methods to preserve line breaks of text?
I found it.
// preserve newlines in source
config.protectedSource.push( /\n/g );
http://docs.ckeditor.com/#!/api/CKEDITOR.config-cfg-protectedSource
$(document).on('paste', 'textarea', function (e) {
$(e.target).keyup(function (e) {
var inputText = $(e.target).val();
$(e.target).val(inputText.replace(/\n/g, '<br />'))
.unbind('keyup');
});
});
Use the <pre> HTML tag. Like this:
<div class="editable" ...>
<div class="code"><pre>
This is an example in a "pre".
This is a new line
</pre></div>
</div>
<div class="editable" ...>
<div class="code">
This is an example NOT in a "pre".
Therefore this is NOT a new line
</div>
</div>
Or you can put a <br/> tag in between your lines. Its the ssame as hitting enter.
In my particular case, it was an extra tag, univis, that I needed to give similar semantics (i.e., leave indentation and inebreaks alone), and what we ended up doing was:
CKEDITOR.dtd.$block.univis=1;
CKEDITOR.dtd.$cdata.univis=1;
CKEDITOR.dtd.univis=CKEDITOR.dtd.script;
But that looks like it might or might not be extensible to classes.
I got some Craft sites running and I don't want to paste the config file everywhere. For everyone else still having the problem: Just use redactor. Install and replace the field type. Correct everything once and you're done.

Categories

Resources