Color coding within contentEditable? - javascript

I've been trying to breakdown how WYSIWYG editors work, but am having problems figuring it out (and do not need even 5% of that versatility).
My own problem is simple.
Insides a contentEditable div, I have a bunch of text. I want to color code any text that matches a simple pattern. So I may have this text:
"this is is a text we [can ignore] this earlier one, but anything that [ref=xxxxxx|aaa|bnbb] that fits the ref has to be color coded."
I want any mention that follows the pattern of [ref=<whatever>] made slightly smaller/colored.
Any idea on how to do that?

One way is using the fabulous http://alexgorbatchev.com/SyntaxHighlighter/ plugin and writing a custom brush for your syntax, which shouldn't be too difficult since your syntax coloring requirements are rather simple.

If you add a keyup event listener to your contenteditable, you can perform your regex replacements there to add $1 in the contenteditable's innerHTML.
Doing so will reset the caret position, but you can preserve it using Rangy.
function highlight(){
var selection = rangy.saveSelection();
contenteditable.innerHTML = contenteditable.innerHTML.replace(/(\[ref=[^\]]*\])([^<])/g, '<span class="ref">$1</span>$2');
rangy.restoreSelection(selection);
}
The regex may not be perfect, but if not, it should get you started.

Related

Find part of string throughout site and replace with new text

I am still having trouble understanding regex. I am also not even sure if you can target a whole page...but without knowledge of how to format regex, its getting play with it.
I have a trademarked name that appears throughout my page. I'd like to use JS to add a (r) to the end of it every time it appears.
Can jquery/js accomplish this?
$("body").each(function() {
this.innerHTML = this.innerHTML.replace(
'breathe right',
'breathe right(r)');
});
Thanks!
This is a good use case for the CSS :after pseudo-element:
CSS
.product-name:after {
content: " \00AE"; /* add restricted symbol after every element with the product-name class */
}
HTML
<span class="product-name">My Product</span>
Working Demo
The easiest way is to wrap your product name in a span and tag it with a class. I'm not sure if that's less work that just adding the symbol to your markup to begin with, though.
The benefit of this approach is it would allow you to easily apply other styles to your product name, like bolding the text or changing the font color.
You can read more about the :after pseudo-element here.
Yes, but it won't be efficient if you tell jQuery to search the entire document. To make it efficient, you'll need to have jQuery get a specific location to search if you want any efficiency in it.
You don't need jQuery :
document.body.innerHTML = document.body.innerHTML.replace(/breathe right/g, 'breathe right(r)')

detecting numbers or letters with css/js

I want to detect and style a special letter .
for example something like this
:
body["p"] /
body["2"]
how can I do this?
thanks
You could do this on a node-by-node basis with a fairly simple replace, but it wouldn't scale very well.
Given the markup:
<p>Peter Rabbit ate all of Potter's pickling cukes.</p>
If you wanted to add a style to all of the letters p in this text, you could select the paragraph node and add spans around any p (assuming a single paragraph):
var graf = document.getElementsByTagName('p')[0];
graf.innerHTML = graf.innerText.replace(/(p)/gi,'<span class="fancy">$1</span>');
That said, this would only work on plain text nodes; if you had, for example, a span tag already in the p tag, it'd get mucked up by the replace.
You cannot with CSS. The only non-element (css-created) pseudo-elements are ::first-line and ::first-letter.
However, you could search with JS through the DOM and create tags around the letters to be highlighted. Check highlight words in html using regex & javascript - almost there for how to do that.

Inserting smilies into div with jQuery

I'm working on some small chat application. I want to implement smilies over there so when i click on some smiley it will appear in textarea where user enters his message and when user clicks on select i want smilies to appear in div that contains the conversation.
After some workarounds i got to idea that replacing textarea with div contenteditable="true"
doesn't work that well so i did wrap certain smiley name with ':' like :wink: in textarea but still i need to replace :wink: with real span containing image as background.
Problem is i don't see a way to make this dynamically but doing each one by one.
for example:
if ($('.line:contains(":wink:")').length > 0) {
var oldLineHTML = $('.line:contains(":wink:")').html();
$('.line:contains(":wink:")').html(oldLineHTML.replace(/:wink:/gi, '<span class="wink></span>"'));
I have plenty of smilies so doing this very resource expensive function will costs me much and also will cause me lots of problems during maintenance.
How can i do that dynamically? Or maybe you have better solution which will require to re-design... I'm up to it if it is required.
thanks
}
var testString = "test1 :smile: test2 :wink:";
alert(testString.replace(/:([^:]*):/g, '<span class="$1"></span>'));
My suggestion is read every string that is wrapped by colons :[something]:, then convert it into span. So that you don't have to define every smile, and it is easy to maintain.
If you are doing this on page load, then you can do this in a $(document).ready(). Then you can use selector that you have $('.line:contains(":wink:")') and use the $each operator to loop over each one and perform the update. This will cover you for the page load. But if you refactor that $each code into a method, then you can call it each time the text is updated. I think this will give you the best in both cases. Something like this:
function replaceWinks(){
$('.line:contains(":wink:")').each(function(index) {
//Replace the wink here
});
}
$(document).ready(function(){
replaceWinks();
});
I would recommend replacing the winks server side for the page load though. It will be more performant. Also it will avoid content that changes when after the first view.
Jeaffrey Gilbert's idea is good, but I have another one that may be interesting:
write down you winks the way you want(let's say [SmileName]), and when processing the text with jquery, read every one of them, and replace the [ with <div class=" then replace the ] sign, with "></div>, this way, you will end up like this:
using these smilies:
1- [smile]
2- [wink]
3- [shy]
will lead to the following markup
1- <div class="smile"></div>
2- <div class="wink"></div>
3- <div class="shy"></div>
and using CSS, you will give every class of them, a different background image, which is the smile image.
by utilizing this method, every div will lead to displaying your smilies, and you will write the code once, and end up using it wherever you want, without repeating yourself

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