Apply span to selected text in javascript - 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.

Related

How to add <span> within CodeMirror editor?

No jQuery please!
I'd like to add a styled span within the body of a CodeMirror editor. This is for the purposes of a mail merge like application where you can for instance do: (From Zapier)
I believe this may be possible using a CodeMirror Widget but I'm lost as to what direction to go in. I found an example of something similar (albeit far more complicated) here.
I also tried tagify which is extremely similar to what I'm after but doesn't have multi-line inputs, which is a requirement.
All I need is the ability to add and remove (via backspace with the caret just behind the tag) these spans but there doesn't appear to be a simple solution.
Also if there is a convenient library or some other direction I can go in not involving CodeMirror that'd also be fine.
CodeMirror is actually well suited for this.
First insert some placeholder into the document, such as [[tag]].
var lineNumber = 0;
var charNumber = 0;
var snippet = "[[tag]]"
editor.doc.replaceRange(snippet, {line:lineNumber, from: charNumber});
Then create your DOM element, I recommend a span.
var htmlNode = document.createElement("span");
//Style and add what you like to the span
Then use doc.markText to replace it with that node.
editor.doc.markText({line: lineNumber,ch: charNumber}, {line: lineNumber,ch: charNumber + snippet.length}, {
replacedWith: htmlNode
})

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)')

Color coding within contentEditable?

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.

How to unbold text? A tiny WYSIWYG editor

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.

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

Categories

Resources