Making a part of an uploaded text file as clickable using javascript - 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.

Related

Replace only part of text in jQuery function

I'm using this solution for replace a list of emojies:
(function($){
var emojies = ["smile", "smiley", "grin", "joy"];
var emojiRegex = new RegExp(":("+ emojies.join("|") +"):","g");
$.fn.toEmoji = function(){
return this.each(function() {
this.innerHTML = this.innerText.replace(emojiRegex,function(fullmatch,match){
return '<span class="emoji '+match.toLowerCase()+'"></span>';
});
});
};
})(jQuery);
//And use like
$(document).ready(function(){
$(".content div").toEmoji();
});
But this replace all the content div (this.innerHTML...), however, there is no way I do it and just replace the :emoji: and not all the text?
Because, if the text has a break line, for ex:
Hi!
How are you?
Will replace for:
Hi! How are you?
In addition to other problems... So, how to do?
The problem is you are reading from the DIV as innerText which will not include the HTML tags like <br/>. Instead, you can read from the DIV with innerHTML like so:
$.fn.toEmoji = function(){
return this.each(function() {
this.innerHTML = this.innerHTML.replace(emojiRegex,function(fullmatch,match){
return '<span class="emoji '+match.toLowerCase()+'"></span>';
});
});
};
Note this.innerHTML.replace instead of this.innerText.replace!
JSFiddle: http://jsfiddle.net/ybj7gpn6/ (inspect HTML after clicking button to see spans are present -- looks like blank space)

variable value is not appending in h2 element

DEMO
Hi, I have variable called "var node = "Hi Mr", Iam trying to append this value on click of a button, im not sure why its not appending.
I tried using html and text, none worked.
JS:
$(function(){
$('.customerResultIndex').on('click',function(){
openCustomerOverlay();
})
});
function openCustomerOverlay(){
var node = "Hi Mr"
$('.customerPopHeading').text(node)
var overlayContainer =
'<div class="customerOverlayShadow">'+
'<div class="customerOverlay borderRadius10px">'+
'<h2 class="customerPopHeading">-- </h2>'+
Create the element first, them after this, set the text...
You are setting the text befero creating it.
Put this:
var node = "Hi Mr";
$('.customerPopHeading').text(node);
After this:
$(document).keyup(function(e) {
if (e.keyCode == 27) {
$('.customerOverlayShadow').remove();
}
});
Final result:
http://jsfiddle.net/pc2tx1us/3/
You cannot append a value like this instead you can concatenate it this way:
'<h2 class="customerPopHeading">--'+ node +'</h2>'+
or you can move this line:
$('.customerPopHeading').text(node);
below this:
$("body").prepend(overlayContainer).focus();
$('.customerPopHeading').text(node);
Fiddle
The element has to be available to make a jQuery selector, here when you prepend in body only then it is available to put the desired text in it.

How to replace only the text of this element with jQuery?

I'm trying to make a kind of simple search engine, where
the user enters a string and if it's equal to the text inside
an element, that portion of text must be highlighted some way.
This is the html:
<input type="text">
<input type="button" value="Change text"><br>
Click here to get more info!
this is the css:
.smallcaps{
color:red;
}
and this is the jquery function that makes the search and replace:
$("input[type='button']").click(function(){
var textValue = $("input[type=text]").val();
$("a").html(function(_, html) {
return html.replace(new RegExp(textValue,"ig"), '<span class="smallcaps">'+textValue+'</span>');
});
});
This is an example of how it looks like:
Everything works fine, until the search string is equals to the name of a node element, so for example if the search string is a, the html will be broken.
How can I avoid the replace of the html itself?. I just want to work over the text.
This is the codepen:
http://codepen.io/anon/pen/mefkb
Thanks in advance!
I assume that you want to only highlight the last search and not store the ones from before.
With this assumption, you can store the old value if it is the first call and use the stored value in the calls afterwards:
$("input[type='button']").click(function(){
// Escape the html of the input to be able to search for < or >
var textValue = $('<div/>').text($("input[type=text]").val()).html();
if(textValue === '') return;
$("a").html(function(_, html) {
var old = $(this).data('content');
if(!old) {
old = html;
$(this).data('content', old);
}
var replacer = function(match) {
return match.replace(new RegExp(textValue, "ig"), '<span class="smallcaps">'+textValue+'</span>');
};
if(/[<>]/.test(old)) {
return old.replace(/^[^<>]*</gi, replacer).replace(/>[^<>]*</gi, replacer).replace(/>[^<>]*$/gi, replacer);
}
return replacer(old);
});
});
Also i fixed two bugs I found when testing:
if you search for an empty string, everything is broken.
If you search for html characters like < or > nothing is found as in the text they are converted to < or >.
One thing is not solved, as it is not possible to easily implement it without destroying the subelement structure: It is not possible to search in different subelements, as you have to remove the tags, search then and insert the tags at the right position afterwards.
Working fiddle: http://codepen.io/anon/pen/KlxEB
Updated Demo
A workaround would be to restore <a> to original text, instead of complicating the regex.
Your problem is a form the <span> tag is getting replaced.
var init = $("a").text(); //save initial value
$("input[type='button']").click(function(){
$('a').text(init); //replace with initial value
var textValue = $("input[type=text]").val();
$("a").html(function(_, html) {
return html.replace(new RegExp(textValue,"ig"), '<span class="smallcaps">'+textValue+'</span>');
});
});

Replace text with HTML element

How can I replace a specific text with HTML objects?
example:
var text = "some text to replace here.... text text text";
var element = $('<img src="image">').event().something...
function ReplaceWithObject(textSource, textToReplace, objectToReplace);
So I want to get this:
"some text to replace < img src...etc >.... text text text"
And I would like manipulate the object element without call again $() method.
UPDATE:
I solved.
thanx #kasdega, i made a new script based in your script, because in your script i can't modify the "element" after replace.
This is the script:
$(document).ready(function() {
var text = "some text to replace here.... text text text";
var element = $('<img />');
text = text.split('here');
$('.result').append(text[0],element,text[1]);
$(element).attr('src','http://bit.ly/mtUXZZ');
$(element).width(100);
});
I didnt know that append method accept multiples elements.
That is the idea, only need to automate for multiple replacements
thanx to all, and here the jsfiddle
do a split on the text you want to replace then use the array indexes 0 and 1...something like:
function ReplaceWithObject(textSource, textToReplace, objectToReplace) {
var strings = textSource.split(textToReplace);
if(strings.length >= 2) {
return strings[0] + objectToReplace.outerHTML() + strings[1];
}
return "";
}
UPDATE: I found another SO post Get selected element's outer HTML that pointed me to a tiny jquery plugin that helps here.
I believe this jsfiddle has what you want. outerHTML is the tiny jquery plugin I included in the JSFiddle.
You can also use replace which will reduce some code: http://jsfiddle.net/kasdega/MxRma/1/
function ReplaceWithObject(textSource, textToReplace, objectToReplace) {
return textSource.replace(textToReplace, objectToReplace.outerHTML());
}
function textToObj (text,obj,$src){
var className = "placeholder-"+text;
$src.html($src.html().replace(text,"<div class='"+className+"'></div>"));
$("."+className).replace(obj);
}
you can use $(selector).outerHtml to get the html string of an element
You can replace the html directly: http://jsfiddle.net/rkw79/qNFKF/
$(selector).html(function(i,o) {
return o.replace('old_html','new_html');
})

Read more/less without stripping Html tags in JavaScript

I want to implement readmore/less feature. i.e I will be having html content and I am going to show first few characters from that content and there will be a read more link in front of it. I am currently using this code :
var txtToHide= input.substring(length);
var textToShow= input.substring(0, length);
var html = textToShow+ '<span class="readmore"> … </span>'
+ ('<span class="readmore">' + txtToHide+ '</span>');
html = html + '<a id="read-more" title="More" href="#">More</a>';
Above input is the input string and length is the length of string to be displayed initially.
There is an issue with this code, suppose if I want to strip 20 characters from this string:
"Hello <a href='#'>test</a> output", the html tags are coming between and it will mess up the page if strip it partially. What I want here is that if html tags are falling between the range it should cover the full tag i.e I need the output here to be "Hello <a href='#'>test</a>" . How can I do this
Why not just hide the hidden part of the content instead of adding it later? I usually just use a display: none for hidden content and have it set to display: block when the read more is clicked..
Edit:
I'm sorry I didn't read the question good enough.
This should work though:
<div id="test">
This links to google
<strong>and</strong> some random text to make it a little bit longer!
</div>
<script type="text/javascript">
$(document).ready(function() {
var max_length = 21;
var text_to_display = "";
var index = 0;
var full_contents = $("#test").contents();
// loop through contents, stop after maxlength is reached
$("#test").contents().each(function(i) {
if ($(this).text().length + text_to_display.length < max_length) {
text_to_display += $(this).text();
index++;
} else {
return false;
}
});
// second loop removes unwanted content
$("#test").contents().each(function(i) {
if (i > index) {
$(this).remove();
}
return true;
});
// add link to show the full text
$('read more...').click(
function(){
$("#test").html($(full_contents));
$(this).hide();
}).insertAfter($("#test"));
});
</script>
This can be accomplished quite easilly using jQuery
<div id="test">This is a link to google</div>
<script type="text/javascript">
$(document).ready(function() {
alert($("#test").text());
});
</script>
Good luck!
You stated that the html tags would become an issue, so why not remove in the string conversion and replace with plain text, then on the Show More click, Toggle plain + Html
$(document).ready(function(){
var Contents = $('#post p'); //Object
var Plain = Contents.text(); //truncate this
//Hide the texts to Contents
Contents.hide();
var PlainContainer = $("<div>").addClass("Plain_Container").val(Plain)
//Add PlainContainer div after
Contents.append(PlainContainer);
var $('.show_hide').click(function(){
$(Plain_Container).remove(); //Delete it
Contents.Show(); //Show the orginal
$(this).remove(); //Remove the link
return false; //e.PreventDefault() :)
});
});
This way using the text() function will convert html tags to there values and remove the tag itself, all you have to do is toggle them :)
Note: The code above is not guaranteed to work and is provided as example only.

Categories

Resources