Make words clickable in Richtext Editor Jquery - javascript

Hiiii Everyone,
I have a Rich text Editor(using nicEditor).I want to make each words in richtextEditor clickable so that onclick of word will change background of particular word and again click removes bg which works like toggle.So that I triedin 1st step to make the words clickable I wanna wrap each words with span tag.
var myInstance1 = new nicEditor({
iconsPath: 'https://cdn.jsdelivr.net/nicedit/0.9r24/nicEditorIcons.gif'
}).panelInstance('differ_paragraph');
myInstance1.addEvent('blur', function() {
var text1 = this.instanceById('differ_paragraph').getContent();
var nicInstance1 = nicEditors.findEditor('differ_paragraph');
var words = nicInstance1.getContent().split(" ");
nicEditors.findEditor("differ_paragraph").setContent(' ');
$.each(words, function(i, v) {
nicEditors.findEditor("differ_paragraph").setContent($("<span>").text(v));
});
});
I tried like above but Its return object.What is the issue? Please anyone help me.Thanks in advance.

Related

Making a part of an uploaded text file as clickable using javascript

I uploaded one file using javascript. I want to make some parts of the text file as highlighted as well as clickable. For example: I want to make all the "hello" in the uploaded file as clickable and highlighted.
I am able to highlight the text as i have used button tag and changed its background and border property in css but I am unable to do an onclick action when the button is clicked.
I tried it like this:
var sel_data=$("#sel").text(); // for taking the text file in avariable
var str='hello';
//making the regular expression of str
var re = new RegExp(str,"g");
//For replacing the 'str' by highlighted and clickable 'str'
var re_str="<button class='highlight' id='ty' onclick='alertfunc()' value="+str+">"+str+"</button>"
//replacement of 'str' by highlighted and clickable 'str'
var rep_data=sel_data.replace(re,re_str);
sel_data=rep_data;
//function to be executed when the button will get clicked
function alertfunc() {
alert('yellow');
}
I also tried it like this
var str='hello'
var re_str="<button class='highlight' id='ty' value="+str+">"+str+"</button>"
$(".highlight").click(function(){
alert("yellow");
})
or like this
var button = document.getElementById("ty");
button.onclick = function(){
alert("yellow");
}
But none of them is working , Please suggest
I referred the above examples by this link: Html make text clickable without making it a hyperlink
There are just a few things wrong here.
First, execute this code on document ready :
$(document).ready(function(){
// code
});
Then, update the actual html in the DOM :
//replacement of 'str' by highlighted and clickable 'str'
var rep_data=sel_data.replace(re,re_str);
sel_data=rep_data;
$("#sel").html(sel_data); // here
And use event delegation for the click :
$("#sel").on('click', '.highlight', function(){
alert("yellow");
});
demo
This is done by using jQuery library and the ready snippet :contains.
Here is the code you need:
jQuery.fn.highlight = function (str, className) {
var regex = new RegExp(str, "gi");
return this.each(function () {
$(this).contents().filter(function() {
return this.nodeType == 3 && regex.test(this.nodeValue);
}).replaceWith(function() {
return (this.nodeValue || "").replace(regex, function(match) {
return "<span class=\"" + className + "\">" + match + "</span>";
});
});
});
};
Using this snippet will lead the words "hello" to be wrapped around a span with class of your choice.
Now to call this function all you need to do is:
$(".testHighlight *").highlight("hello", "highlight");
Ofcourse you have to setup the .testHighlight class with CSS to be something like:
.testHighlight {
background:yellow;
}
To make them clickable you can do it easily with jQuery:
$(.testHighlight).click(function(){
//YOUR CODE HERE
});
You can check more on this snippet here.

Make a custom text editor (styler) with JS

I have been asked to create a text editor with the following features:
Import text from another source
Apply styles to the text
Styles are predefined (for example style "Level 1" may make the text bold, green and italic.
One styling effect is to add characters before and after the selection so for example, text has two stars before and after
Styles are applied to full words, no partials
The text cannot be edited/changed, only styles should be added
The article text must be saved in a version-ed manor, for example Editor A added these changes ____ on date / timestamp.
What is the best way to do this?
I have been playing with execCommand and this does most of what I want, except I cant seem to make the text non-editable, I'm not able to add chars before and after the selection like this, and I cant track individual changes.
I'm almost thinking I should make each word a label and treat them like objects but I'm having a hard time making them select-able (highlight the text with the mouse like you do in an editor).
Does anyone know of any libraries for this sort of thing?
I can give you a part of the solution: how to select full words. My script is for textarea but you can make a few changes if you want to use div contenteditable instead.
JSFIDDLE DEMO
var lastSelectStart = 0;
var lastSelectEnd = 0;
saveSelection = function(){
lastSelectStart = document.getElementById("text").selectionStart;
lastSelectEnd = document.getElementById("text").selectionEnd;
}
selectWords = function(){
var divEditable = document.getElementById("text");
html = divEditable.innerHTML;
var start = lastSelectStart;
var end = lastSelectEnd;
var before = html.substring(0,start);
var after = html.substring(end);
var split = before.match(/[ .,;]/gi);
var startIndex = before.lastIndexOf(split[split.length-1]) + 1;
split = after.match(/[ .,;]/gi);
var endIndex = after.indexOf(split[0]);
endIndex = end + endIndex;
divEditable.selectionStart = startIndex;
divEditable.selectionEnd = endIndex;
// startIndex is where you insert your stars and
// (endIndex + number of stars added) is where you insert your stars again
}

Highlight all comma's in page with jquery

I have a very very simple question and i didn't find my answer.
I have a page that is using ajax and it gets update again and again in one div of it.
Now, i want to Highlight ALL the commas , of that div.
For example, they get red color.
How can i do it with this ajax page ?
I also wanted to try with this code, but i coudn't
$(document":contains(',')").css("color","red");
I just need to find all the commas in that div every second and give a style to them .
How to do it with jquery?
Don't know about jQuery, but it can be done with pure javascript. But it's not so easy actually.
tl;dr jsFiddle
This answer does not cause DOM revalidation and does not mess-up with javascript events!
First you need to loop through page content and replace every comma (or every character) with a <span> or other node so that you can give it individual CSS style. Let's start with getting textNodes:
HTMLElement.prototype.getTextNodes = function(recursive, uselist) {
var list = this.childNodes;
var nodes = uselist!=null?uselist:[];
for(var i=0,l=list.length; i<l;i++) {
if(list[i].nodeType==Node.TEXT_NODE) {
nodes.push(list[i]);
}
else if(recursive==true&&list[i].nodeType==1&&list[i].tagName.toLowerCase()!="script"&&list[i].tagName.toLowerCase()!="style") {
list[i].getTextNodes(true, nodes);
}
}
//console.log(nodes);
return nodes;
}
You'll now need to split the spans wherever the commas are:
/*Turn single text node into many spans containing single letters */
/* #param
textNode - HTMLTextNode element
highlight - the character to highlight
#return
null
*/
function replaceLetters(textNode, highlight) {
//Get the string contained in the text node
var text = textNode.data;
//Generate a container to contain text-node data
var container = document.createElement("span");
//Create another span for every single letter
var tinyNodes = [];
//Split the letters in spans
for(var i=0,l=text.length;i<l; i++) {
//skip whitespace
if(text[i].match(/^\s*$/)) {
container.appendChild(document.createTextNode(text[i]));
}
//Create a span with the letter
else {
//Create a span
var tiny = document.createElement("span");
//If the letter is our character
if(text[i]==highlight)
tiny.className = "highlighted";
tiny.innerHTML = text[i];
container.appendChild(tiny);
}
}
//replace text node with a span
textNode.parentNode.insertBefore(container, textNode);
textNode.parentNode.removeChild(textNode);
}
The function above was originaly used for animating all letters on a page (even when it was already loaded). You only need to change color of some of these.
If the functions above are defined, call this:
var nodes = document.getElementById("myDiv").getTextNodes(true);
for(var i=0, l=nodes.length; i<l; i++) {
replaceLetters(nodes[i], ",");
}
You need to wrap the commas with an HTML tag (such as <span>).
$(window).load(function() {
$('.target').each(function() {
var string = $(this).html();
$(this).html(string.replace(/,/g , '<span class="comma">,</span>'));
});
});
Here is an example:
http://jsfiddle.net/5mh6ja1L/
I don't know how to do it in jQuery but in pure JavaScript it would be something like this:
var el = document.getElementById("content");
el.innerHTML = el.innerHTML.replace(/,/g, "<b class='highlight'>,</b>");
demo: http://jsfiddle.net/f9xs0c79/
No need to do loop. You can just select the container where you want to replace and replace.
$("p").html(
$("p").html().replace(/,/g,"<span class='comma'>,</span>")
);
http://jsfiddle.net/1570ya75/2/

Get certain text replace it and wrap it in span?

I have following html<p class="get">This is some content.</p> what I would like to do is to make it like this:<p class="get">This is <span>some</span> content.</p>. To accomplish this I know I should: 1. get my certain text (done that...)
2. Wrap my text in span (done that also...)
3. replace my text with text that contains my span (haven't done it)
My problem is step 3 I just can't figure it out. So how can I replace my "old" text with new one?Thank you guys!!!
Fiddle here
My code looks like this:
$(document).ready(function(){
//get the whole text
var ptext = $(".get").text().split(" ");
var myText = ptext[2];
//alert(ptext[2])
//alert(myText);
if($('.get').text().contains(myText)){
//$('<span>'+myText+'</span>').appendTo($('.get'));
}
else{
alert('no text');
}
});
var word = "some",
regex = new RegExp("\\b" + word + "\\b", "g");
$(".get").html(function(i, html) {
return html.replace(regex, "<span>$&</span>");
});
DEMO: http://jsfiddle.net/V7Wnk/1/
$('.get').html(function (i, v) {
return v.replace('some', '<span>some</span>');
});
$('.get').html($(".get").html().replace("some","<span> some </span>"));

highlite text parts with jquery, best practice

i have a list of items containig names.
then i have a eventlistener, which ckecks for keypress event.
if the user types i.g. an A all names starting with an A should be viewed with the A bold. so all starting As should be bold.
what is the best way using jquery to highlite only a part of a string?
thanks for your help
Here's a function you can call during your keypress event to highlight a search string:
function Highlight(search)
{
$('ul > li').each(function() {
if (this.innerHTML.indexOf(search) > -1)
{
var text = $(this).text();
text = text.replace(search, "<span id='highlight' style='font-weight: bold'>" + search + "</span>");
$(this).html(text);
}
else
{
this.innerHTML = $(this).text();
}
});
}
Test html:
<ul id='list'>
<li>Bob Jones</li>
<li>Red Smith</li>
<li>Chris Edwards</li>
</ul>
It's not quite as elegant as Pointy's answer, but it handles the matching strings requirement.
There are jQuery plugins to do text highlighting, but I've not seen one that highlights parts of words.
One possible solution would be to put all your names on the page with the first letter surrounded by a <span> tag, with a class:
<span class='A FL'>A</span>ugustine
<span class='C FL'>C</span>arlos
You can then use jQuery to fiddle with those by class name.
$('whatever').keypress(function(ev) {
var k = e.which.toUpperCase();
$('#textContainer span.FL').css('font-weight', 'normal');
$('#textContainer span.' + k).css('font-weight', 'bold');
});
Note that bold characters are fatter than normal characters, so this is going to have a "wiggly" effect that your users might not like. You might consider changing color instead.
thanks for your help...
i figured it out and the detailed resolution comes here:
var communities = $('#mylist').find('.name');
var temp_exp = new RegExp("^("+match_string+")","i");
communities.each(function(i){
var current = $(this);
var name = current.text();
name = name.replace(temp_exp, '<b>$1</b>');
current.html(name);
});
while all items have to have the class "name".

Categories

Resources