How to unbold text? A tiny WYSIWYG editor - javascript

Hey Stackoverflow comunity,
There is a method str.bold() to wrap a text in <b></b> tags. This is just perfect for a tiny WYSIWYG editor (I know some will say I should take one of hundrets open source solutions, but this is for learning purposes too).
The problem is how to unbold the text.
Here is my try http://jsfiddle.net/Kxmaf/178/
I know there is editor.execCommand('bold', false, ''); but this is producing different HTML results on each browser. I need to have only <b></b>, <i></i>, <u></u>
Any help is much appreciated :)

what about looping over a selected string with javascript when pushing the specific style-button. you just could save the several tags like , , .... inside an array, and than loop through the specific string you have selected. so you even can change the style of the style-buttons when any of the tags has been found, to let the user know which style is just used. After deselecting the style just loop again through and delete the tags from string.

You need to consider the case where the user's selection spans paragraphs. For example (selection boundaries indicated with pipes):
<p>One <b>t|wo</b></p>
<p>Thr|ee</p>
To handle this, you need to wrap and all the text nodes and partial text nodes within the user's selection in <b> tags while also detecting which text nodes are already bold and leaving them alone. This is non-trivial, and document.execCommand() handles it all for you, as do the big WYSIWYG editors.
Most browsers allow switching between style modes, allowing you to choose between styling using elements such as <b> and <i> or styling using <span> elements with style attributes. You can do this using the the "StyleWithCSS" command, falling back to "UseCSS" in older browsers. The following switches commands to use the non-CSS version:
try {
if (!document.execCommand("StyleWithCSS", false, useCss)) {
// The value required by UseCSS is the inverse of what you'd expect
document.execCommand("UseCSS", false, !useCss);
}
} catch (ex) {
// IE doesn't recognise these commands and throws.
}
Finally, if you switched to using CSS classes instead of <b> etc., you could use the CSS class applier module of my Rangy library.

Related

Can I open an RTE tag in a specific element with a button in html5?

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.

How to style a text string that is added by using a JavaScript function?

The link below is supposed to reveal more text when clicked, which it does, however the text uses all default styling, which cannot be seen on my black background that I use for the page. I have tried to style the tag where the text is added through JavaScript, but the added text still uses the default style.
Below is the code I have used:
HTML:
<p>
This movie might seem boring to you at first and you
might not get it after <br>first time viewing, like I did. But this
is one of the greatest movies ever made.....
Read More
<p id="atext" class="atext">dqdas</p>
<script src="Home.js"></script>
</p>
and JavaScript:
function more(e) {
e.preventDefault();
document.getElementById("atext").style.color= "white";
document.getElementById("atext").outerHTML = 'It touches many issues in our lives and packs a hell of a plot twist';
}
Simply use innerText rather then outerHTML. This should solve the issue.
I believe this happens because setting the HTML of an element overwrites any styles it may have. Setting the text does not do this.
Also, it is generally best to use innerText when necessary, as it reduces the risk of errors like yours occurring.

Text Editor with designMode. How to force designMode to use HTML tags instead of spans

I've build a small text editor with an iframe and designMode. (here is an example NOT coded by me http://jsfiddle.net/Kxmaf/6/. I've found it here on Stackoverflow).
If I retrieve the content of the iframe (document.body.innerHTML) the result is something like this: <span style="font-weight: bold;">Test</span> Text <span style="font-style: italic;">Text</span> <span style="text-decoration: underline;">TT</span>
Is it possible to set the designMode to use tags instead of spans with style attribute?
Any help is much appreciated :)
In most browsers (but not IE), you can use the "StyleWithCSS" command to switch between style modes, allowing you to choose between styling using elements such as <b> and <i> or styling using <span> elements with style attributes. You can do this using the the "StyleWithCSS" command, falling back to "UseCSS" in older browsers. The following switches commands to use the non-CSS version:
try {
if (!document.execCommand("StyleWithCSS", false, useCss)) {
// The value required by UseCSS is the inverse of what you'd expect
document.execCommand("UseCSS", false, !useCss);
}
} catch (ex) {
// IE doesn't recognise these commands and throws.
}

Manually highlight a specific section in javascript SyntaxHighlighter

I am using the Syntax highlighter library to display code on a webpage. I would like to highlight certain sections of code in response to various events on the page. It may be a single character, or a multiple line section, but it will always be a contiguous section of text.
I know that SyntaxHighlighter has functionality to highlight individual lines, but I need a little more fine grained control than that.
I know the selection start and selection length points in the original source code, but the highlighter has inserted a lot of html elements, so it is a bit difficult to find those indexes again to wrap them in another tag.
Is there a good way I can override existing formatting, and apply my own css to a specific portion of the text? Is there a different syntax highlighting plugin that may give me what I need?
How about running the generated markup through a function that searches and replaces the specific 'programmatic word' with,
<span class="customHighlight">word</span>
..and you can style it as follows,
span.customHighlight {
background:#FAFAD2;
color:#000;
}
I sort of worry about the efficiency of this though.
EDIT: I've got something, if you look at the source of the script relative to the highlighter for a language (here, CSS), http://alexgorbatchev.com.s3.amazonaws.com/pub/sh/3.0.83/scripts/shBrushCss.js,
{ regex: /!important/g,
css: 'color3' }, // !important
..which renders as,
<code class="css color3">!important</code>
..so, just define your 'word' as a rule with an equivalent CSS declaration.
You can use jQuery as in example http://www.tripbase.com/code/highlightTutorial.html. According to me provide a textbox and onchange event send the highlighted text to the function and the function will highlight the text
For your highlight and un-highlight jquery just visit bartaz.github.com/sandbox.js/jquery.highlight.html

Apply span to selected text in javascript

I would to apply a span class to selected text on browser window in Javascript (like an highlight feature).
I've tried with
function replaceSelectedTextWithHTMLString(newstring) {
var range = window.getSelection().getRangeAt(0);
range.deleteContents();
range.innerHTML = newstring;
}
but it does not work. If i try to insert as newstring= "< span = "myspan" > text < / span >" I can't look anything and the 'text' does not appear. Seems it does not like the HTML code. How can I solve it?
How easy this is depends on what exactly you need to achieve. If all you need is basic highlighting using a background colour, your best bet is document.execCommand(). See the following for code to do this: Change CSS of selected text using Javascript
If you need to apply more styling than document.execCommand() can provide (there are also various other formatting commands for things like bold and italic, but the markup this produces varies between browsers and isn't always CSS based), it's much trickier: in general, you need to surround every text node within the selection in a span with the desired class. I would suggest using Rangy and its CSS class applier module to do this in a cross-browser way. Disclaimer: this is a plug for my own library.

Categories

Resources