I run a site where users submit basic news articles. I want to add some formatting features for their submissions, quite similar to the markdown feature used here.
For example, user can add:
**This should be bold**
And the text appears bold. Or user adds > at the beginning of the paragraph:
> This could be a lengthy paragraph
And the paragraph gets wrapped in <blockquote>.
Note that I do not want it to be processed server-side.
How can I do this using Javascript or jQuery?
EDIT:
I found a way to make text within astericks bold using the following:
<div class="content">The following will be bold: **I am bold**</div>
jQuery:
function markdown(markdownable) {
var bold = /\*\*(\S(.*?\S)?)\*\*/gm;
markdownable = markdownable.replace( bold, '<span style="font-weight:bold">$1</span>' );
return markdownable;
}
$('.content').each(function() {
var markdownable = $(this).html(),
content = markdown(markdownable);
$(this).html(content);
});
Fiddle.
However, I still have no clue on how to make a paragraph starting with > wrapped into <blockquote>.
The Markdown solution that Reddit uses is freely available, lightweight, well documented and does everything you asked for and more:
http://daringfireball.net/projects/markdown/
Please have a look at this pluggin markitUp!
markItUp! is a JavaScript plugin built on the jQuery library. It allows you to turn any textarea into a markup editor. Html, Textile, Wiki Syntax, Markdown, BBcode or even your own Markup system can be easily implemented.
Hope this will help you.
Related
By RTE tags I mean <b>, <i>, <u>, or <s> tags. I've been working on a RTE, and using jquery I can get the entire area to bold, but I want to be able to bold only a specific portion (think google docs, word, or any other text editor).
The mozilla site only had deprecated information, and inspecting elements on other sites (including this one) were no help to me.
I am trying to edit a content-editable <div> currently, although I'm open to switching to a text area if that works better.
//my jquery for bolding the entire thing
var bolded = false;
$("#bold").on('click', function(){
//access css of editor div, change status using a ternary
$("#editor").css("font-weight", bolded ? this.value : 'bold');
bolded = !bolded;
//log for debugging
console.log('clicked bold: ' + bolded);
});
my HTML5 for the editor. Sectioned off for formatting purposes.
<section>
<div id="editor" contenteditable="TRUE"></div>
</section>
My buttons are id'd as "bold", "itallic", "strike", and "underl", but I really just want to get one of them working so I can work from there.
EDIT
I realized that this question isn't as straightforward as I'd hoped. I have a <div>, and I would like to have multiple different formats inside of this <div>. The way I would do it logially is by inserting a <b> tag on the click of a button / keyboard command and then continuing to type from there, but I can't find any resources for it. Hope this clears that up.
EDIT 2
So as far as I can tell, the document.execCommand() still works but is predicted to be replaced by Input Events Level 2. I can't find any readable documentation for implementing this. Does anybody know how to do this?
Answer for current methodology (document.execCommand('command')):
Attaching a simple onclick() to the buttons works, where that onclick is a function that runs the aforementioned command with no particular focus:
function format(command, value){
//In use, "value" is left blank in order to do the current selection / no selection
document.execCommand(command, false, value);
}
<button onclick="format('bold')"><strong>B</strong></button>
<button onclick="format('italic')"><em>I</em></button>
Please note that this functionality WILL be deprecated, but no replacement has come up yet. When I know more, I will come back and edit this answer.
I have a simple search engine on one of our older websites. This site is running IIS 6.0 on Windows Server 2003. The search functionality is provided by Microsoft Indexing Service.
You can see the search functionality on our website. (Just type in "speakers" and you will see some hits.
I would like to use the "FullHit" feature offered by the indexing service. When using this feature the Indexing service inserts the full hit results in between "begindetail" and "enddetail" on a target web page.
The problem that I have is that the documents that are being returned have HTML. This looks messy. (Just click on "Hit Locator Tool" in the search results above to see what I mean.)
I would like to create a DIV section such as ...
<DIV name="target">
begindetail
enddetail
</DIV>
Then, after the page is populated I would like to use javascript to strip out all of the HTML elements (but not the data) between the opening and closing DIV.
For example, <FONT color="magenta">Good Data</FONT> would be modified to only show Good Data.
I can also use Classic ASP if necessary.
Please let me know if you have any suggestions or know of any functions that I can add to the target page to accomplish this task.
Thanks in advance.
I inspected your webpage, and there definitely must be some logic errors in your ASP code. (1) Instead of something like <div></div> being passed to the browser, it is HTML entities for special characters, so it is being passed like <DIV> </DIV>, which is very ugly and is why it is rendering as text instead of HTML code. In your ASP code, you must not be parsing the search result text before passing it to the browser. (2) All of this improperly-formatted code is inserted after the first closing html tag, and then there are closing body and html tags after the improperly-formatted code, so somewhere in your ASP code, you are telling it to append the code to the end of the document, rather than insert it inside the original <body></body>.
If you want to decode the mixture of HTML entities, <br> tags, and text into rendered HTML, this JavaScript may work:
window.onload = function() {
var text = decodeHTMLEntities(document.body.innerText);
document.write(text);
}
function decodeHTMLEntities(text) {
var entities = [
['amp', '&'],
['apos', '\''],
['#x27', '\''],
['#x2F', '/'],
['#39', '\''],
['#47', '/'],
['lt', '<'],
['gt', '>'],
['nbsp', ' '],
['quot', '"']
];
for (var i = 0, max = entities.length; i < max; ++i)
text = text.replace(new RegExp('&'+entities[i][0]+';', 'g'), entities[i][1]);
return text;
}
jsFiddle: https://jsfiddle.net/6ohc1tkr/
But first things first, you need to fix your ASP code, or whatever you use to parse and then display the search results. That's what is causing the improper formatting and display of the HTML. Show us your back-end code and then we can help you.
This is what I used to accomplish what you are trying to do.
string-strip-html
It worked pretty well for me.
I now have the search feature working as expected. I would like to thank everyone for their insightful comments. This feedback helped me identify and fix the problem.
OS: Windows Server 2003
IIS: 6.0
Microsoft Index Server
The hit locator tool will only work properly for HTML pages. If you use this tool with a simple TXT file then the results will not be displayed correctly.
I'm turning here as a last resort. I've scoured google and I'm having troubles coming to a solution. I have a form with a textarea element that allows you to type html in the area and it will render the HTML markup live as you type if you have the preview mode active. Not too different from the way StackOverflow shows the preview below a new post.
However, I have recently discovered that my functionality has a vulnerability. All I got to do is type something like:
</textarea>
<script>alert("Hello World!");</script>
<textarea style="display: none;">
And not only does this run from within the textarea live, if you save the form and reload said data on a different page this code still executes within the textarea on said different page but unbeknownst to the user; to them all the see is a textarea (if there is no alert obviously).
I found this post; Live preview of textarea input with javascript html, and attempted to refactor my JS to the accepted answer there, because I noticed I couldn't write a script tag in the JSFiddle example, though maybe that's some JSFiddle blocking that behaviour, but I couldn't get it working within my JS file.
These few lines is what I use to live render HTML markup:
$(".main").on("keyup", "#actualTextArea", function () {
$('#previewTextArea').html($('#actualTextArea').val());
});
$(".main").on("keydown", "#actualTextArea", function () {
$('#previewTextArea').html($('#actualTextArea').val());
});
Is there a way this can be refactored so it's safe? My only idea at the moment is to wipe the live preview and use a toggle on/off and encode it, but I really think this is a cool feature and would like to keep it live instead of toggle. Is there a way to "live encode" it or escape certain tags or something?
In order to sanitise your text area preview simply replace all the < and > with their html character code equivalents:
function showPreview()
{
var value = $('#writer').val().trim();
value = value.replace("<", "<");
value = value.replace(">", ">");
$('#preview').html(value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="writer" onInput="showPreview();">
</textarea>
<br/>
<hr/>
<div id="preview">
</div>
Edit: Actually, I think this solution is a little cleaner, and makes the below code unnecessary. In the velocity page all that is needed is to take advantage of the Spring framework. So I replace the textarea with this like so:
#springBindEscaped("myJavaObj.textAreaText" true)
<textarea id="actualTextArea" name="${status.expression}" class="myClass" rows="10" cols="120">$!status.value</textarea>
This paired with some backend Java validation and it ends up being a much cleaner solution.
But if you want a non-spring/ velocity solution, then this below works just fine
I cobbled together a quick fix as my main purpose is to eliminate the ability for others to execute scripts easily. It's not ideal, and I"m not claiming it to be the best answer, so if someone finds a better solution, please do share. I created a "sanitize" function like so:
function sanitize(text){
var sanitized = text.replace("<script>", "");
sanitized = sanitized.replace("</script>", "");
return sanitized;
}
Then the previous two event handlers now look like:
$(".main").on("keyup", "#actualTextArea", function () {
var textAreaMarkup = $('#actualTextArea').val();
var sanitizedMarkup = sanitize(textAreaMarkup );
$('#actualTextArea').val(sanitizedMarkup);
$('#previewTextArea').html(sanitizedMarkup);
});
// This one can remain unchanged and infact needs to be
// If it's the same as above it will wipe the text area
// on a highlight-backspace
$(".main").on("keydown", "#actualTextArea", function () {
$('#previewTextArea').html($('#actualTextArea').val());
});
Along with Java side sanitation to prevent anything harmful being stored in the DB, this serves my purpose, but I'm very open to a better solution if it exists.
Main Target :
To create a website that will have a live preview of an HTML/CSS code.
More specifically :
The HTML/CSS code will be editable form the user in some specific parts. So, the code in the live preview will not derive from text areas but from divs.
Image of what I am trying to do :
So, in my Previous Question I tried to find a way to make the live preview box work after getting the code from the black boxes. It did not work because the code was given in a div tag and not a textarea. I would like to add that the code in the div tags use xmp tags because some parts are editable from the user.
Now, I have replaced the divs with textarea tags but the EDIT function does not work.
Main Question :
How do I edit parts of a textarea text? Below, I made it work for a div tag but not a textarea. How can I make the following work for a textarea?
$('input#thebox1').keypress(function(e) {
console.log($(this).val());
if(e.which == 13 && $(this).val().length > 0) {
var c = $(this).val();
$('.popup1').removeClass().addClass(c).text(c);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Replace Title Background Color: </div><input type="text" id='thebox1'>
<div id="copyTarget1" class="innerbox css">
<blockquote>
<pre>
<code>
.title
{
background: #<b class="popup1" style="color:#FF0000;">value </b>;
vertical-align: middle;
}
</code>
</pre>
</blockquote>
</div>
<br><br><br><br><br><br>
I thought about taking another approach to make your life easier using Ace (Cloud9 Editor). It is an awesome solution to get code editors for different languages. All built in JavaScript. It is quite easy to integrate. I just downloaded it to create the case you are trying to build.
You can find the example I have just made here: https://dubaloop.io/dev/html_css_js_editor/
Basically, you load the library for ace:
<script src="src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
Then you create a "pre" container for your HTML, CSS, JavaScript editor:
<pre class="editor" id="editor_js">
function foo(items) {
alert('works');
}</pre>
You will be able to convert them into code editor by using the function:
var editor_js = ace.edit("editor_js");
editor_js.setTheme("ace/theme/monokai");
editor_js.session.setMode("ace/mode/javascript");
It will generate a nice code editor that can through error, warnings, etc. You also have different themes. It is very user friendly as you could see. In my example I just get the content of each code container and send it to an blank iframe that. In order to retrieve the content you can use:
editor_js.getValue();
Check the source code for example I sent you above. I also created .zip with the example here: https://dubaloop.io/dev/html_css_js_editor/example.zip
Have a look to see if this would work for you.
GitHub repo for ACE: https://github.com/ajaxorg/ace-builds
I hope it helps.
UPDATE:
I decided to update the response to replay to your last comment. A few things about it:
First, I updated the code in the link I sent you previously: https://dubaloop.io/dev/html_css_js_editor/
The idea was to check the guide to see how you can manipulate the input and adjust it to what you need. They have great manipulation options. This is the guide: https://ace.c9.io/#nav=howto&api=editor
I just made a short version of what you are trying to do: I am replacing the content for the <h1> in HTML editor, by entering it in a textfield input; similar to what you are trying to achieve. I set the html code editor as a readonly so you cant edit on it. Have a look and let me know.
Second, I created another example using your code. You can check it here: https://dubaloop.io/dev/html_css_js_editor/example.html
I noticed that the first problem you were having was related to how you were triggering the preview update ($('.innerbox').on("keyup"...)). There was not keyup event there. For now I set it on any input when you hit enter. The other big problem, and probably the main one you had was how you were accessing the iframes through jQuery. You need to use $('selector').contents().find('selector2'). Finally another problem was the you were retrieving the data getting the attribute value from your code wrapper. What you need to get is the actual content as flat text in order to avoid other html content. In order to do that you need to use .text() (Please check the updated GetHtml() and GetCss() functions).
I hope you can make it work from here. Still, I like option 1 :P
I hope it helps.
I am working on a multi-language function on wordpress. Each article or page will contain 2 language versions, I need to use a tag to separate them and let my JavaScript knows which section to pull according to the current language option.
I may have something like this in the editor?
[english]
English Content
[/english]
[chinese]
中文内容
[/chinese]
OK so my question is how to have a function to let javascript to recognise the [] and the text in it? or is this something that can be done in the wordpress API? since I have seen kinds of plugins using this in the article.
I would advise you don't create your own tags, but use normal html element with the lang attribute:
<div lang="en">
English Content
</div>
<div lang="zh">
中文内容
</div>
This way you can use the standard css and javascript to work with the content, like this:
*[lang=zh]{
display:none;
}
and then you could switch the display via javascript when the chinese language is chosen.
The universal selector * should be avoided if possible and replaced for a more specific selector.
Alternatively, if you don't want to bother your client with html-stuff, let them write these pseudo-tags [english] / [chinese] and convert these after saving into the divs with the according language tags.
Simple regex for capturing the content of such tags (not failproof!):
/\[english\](.*?)\[\/english\]/ // -> content will be in first capturegroup
Just for fun i coded some tiny example how such a replacement could work:
Replacement of custom tags into divs with language-id
Here is a RegEx way of doing it: http://jsfiddle.net/neuroflux/fFzJ4/17/
Too much code to put here :)