How Do I Add Ellipses to Text - javascript

I am trying to create a function that will take an element's text, cut off any characters beyond 80, and add an ellipses if necessary. Here's my code so far:
var maxLength = 80;
function shorten(element) {
var text = $('#' + element).text();
var ret = text;
if (text.length > maxLength) {
text = text.substr(0,maxLength-3) + "...";
}
$('#' + element).text(text);
}
shorten('slide1');
So, the function should take the element, remove extra text off the end, add an ellipses, and then replace the old text in the element with the new string I've just created.
When I run the function, I don't get any errors, but it doesn't actually cut off the text as it should. Why is this?

var text = "Some Text Goes Here. La La La La!";
var textLength = 10; // Number of characters to cut off after
function shorten(text, textLength){
if(text.length > textLength){
text = text.substring(0, textLength) + '…';
}
return text;
}
var shortText = shorten(text, textLength);
Also, using the HTML character for ellipsis is better than using three periods.
I've added a Codepen showing the code working. Additionally, I added a function spaceShorten that will split your text at the last occurrence of a space that is less than the length provided, so you don't split the text mid word.
http://codepen.io/supah_frank/pen/EaYzNz

Related

Conditionally call function in Javascript?

i have a function called as Truncate that is truncating the text. How can i conditionally call that function only when offsetheight of left div with class demo exceeds the offsetheight of right div. If the condition is not met, then just return the original content.
Here is a demo
var textHolder = document.querySelector('.demo');
var textHolder2 = document.querySelector('.demo2')
var textHolderHeight = textHolder.offsetHeight + 'px'
var textHolderHeight2 = textHolder2.offsetHeight + 'px'
console.log(textHolderHeight)
console.log(textHolderHeight2)
var fullText = textHolder.innerHTML;
var btn = document.querySelector('.btn');
var textStatus = 'full'; // use this to check the status of text and toggle;
function Truncate(textHolder, limit) {
let txt = textHolder.innerHTML;
if (txt.length > limit) {
let newText = txt.substr(0, limit) + ' ...';
textHolder.innerHTML = newText;
textStatus = 'truncated';
}
}
Truncate(textHolder, textHolder.offsetWidth / 10);
function toggleText() {
// here i want to show full text...
// and also -> btn.innerHTML = 'Hide Text' | 'Show Text;
if (textStatus === 'truncated') {
textHolder.innerHTML = fullText;
textStatus = 'full';
} else {
Truncate(textHolder, textHolder.offsetWidth / 10);
}
}
btn.addEventListener('click', toggleText);
<section class="demo" id="demo">
Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long
line of text so that the words don't wrap when they're not supposed to. Multi-line of course!
</section>
<button class="readMore btn">Read More</button>
<br><br><br>
<section class="demo2" id="demo2">
Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long
line of text so that the words don't wrap when they're not supposed to. Multi-line of course!don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long line of text so that the words don't wrap when they're not supposed to.
Multi-line of course!don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course!
</section>
Thank you in advance guys.
You can either use an if statement every time you need to call Truncate.
if(textHolderHeight > textHolderHeight2){
Truncate(textHolder, textHolder.offsetWidth / 10);
}
Or put the code inside Truncate so you don't have to duplicate the if statements.
function Truncate(textHolder, limit) {
let txt = textHolder.innerHTML;
if (txt.length > limit && textHolderHeight > textHolderHeight2) {
let newText = txt.substr(0, limit) + ' ...';
textHolder.innerHTML = newText;
textStatus = 'truncated';
}
}

jQuery counting spaces

Gretings, I have a bit complicated issue. I'm appending text to textarea with javascript. My question is - how to count, how many spaces are on the text area location, where the mouse is clicked? I'm appending text like this:
function typeInTextarea(el, newText) {
var start = el.prop("selectionStart")
var end = el.prop("selectionEnd")
var text = el.val()
var before = text.substring(0, start)
var after = text.substring(end, text.length)
el.val(before + newText + after)
el[0].selectionStart = el[0].selectionEnd = start + newText.length
el.focus()
}
$(".containeris").on("click", function() {
typeInTextarea($("#html_content"), '<div class="container">\n\n</div>')
return false
})
So the problem is, it starts appending text exactly, where mouse is clicked, but i want to make sure, that closing div, which is being printed in new line, would have same number of spaces in front of it as starting line, to keep indentation. Is it possible to achieve?
Solution was simpy to count tabulations as symbols.

How Do I Cut Off the End of AJAX Loaded Text?

I am trying to cut off (truncate) extra characters off of the end of an AJAX-loaded element with text in it. Here's how I'm loading the element:
$("#destinationElement").load("/sourcePageName .classWithinPage");
I would like to limit the length of the text inside of #destinationElement to 140 characters, but the text within .classWithinPage may be longer, so I need to cut it off after that point somehow. I'd also like to add an ellipses afterwards, if possible.
I tried adding a function afterwards that would do this (see the following) but it didn't seem to work, and I would prefer it ran before the text was added to #destinationElement, so that the script would do its work before the text displayed.
var maxLength = 140;
function shorten(element) {
var text = $(element).text();
if(text.length > maxLength){
text = text.substring(0, maxLength);
var lastIndex = text.lastIndexOf(" ");
text = text.substring(0, lastIndex) + '...';
}
$(element).text(text);
};
shorten('#destinationElement');
^^ That didn't work. Plus, I think I should probably be adding in my function as a part of the jQuery load function I have up above, I'm just not sure how.
How do I truncate the text that's being loaded to 140 characters before it appears on-screen?
Use the $.get method instead if you want to modify the data
$.get('/sourcePageName', function(data) {
var text = $('<div />', {html : data}).find('.classWithinPage').text();
if (text.length > 140) {
text = text.slice(0, 140) + '...';
}
$("#destinationElement").text(text);
});

JAVASCRIPT - if last character is : (colon), change font weight

Is it possible to change font weight if last character is colon with JavaScript?
I have site, where people can add recipe. And i want to highlight parts of ingredients of recipe. For example:
topping:
-chocolate
-milk
filling:
-...
-...
I searched and i found that codes:
for last character
if (myString.charAt(myString.length - 1) == ':')
and for weight change
function changeWeight(600)
{
document.getElementById("id_1").style.fontWeight = fontWeight;
}
I do not know how to write the code to work. I am beginner.
Thank you very much.
Try this
if (myString.charAt(myString.length - 1) == ':') {
changeWeight("600");
}
function changeWeight(weight) {
document.getElementById("id_1").style.fontWeight = weight;
}
It seems that you want to make specific text bold, not all text within an element. You would need to get the text out of the element, change it, and put it back.
You can use code like this to but a bold tag around all words in the element that ends with a colon:
var element = document.getElementById("id_1");
var text = element.innerHTML;
text = text.replace(/([A-Za-z]+:)/g, '<strong>$1</strong>');
element.innerHTML = text;
Note: For that to work properly, you can't have other HTML elements inside the element that has words with colons in the actual markup. I you have for example SO in the code, it would break because of the http: in the link.
If you have that single word alone in an element, you would get the text and check for the colon:
var element = document.getElementById("id_1");
var text = element.innerHTML;
if (text.charAt(text.length - 1)) == ':') {
element.style.fontWeight = 'bold';
}

how to highlight all the occurrence of a particular string in a div with java script?

i need to highlight all the occurrences of a string in particular div by selecting a string,
once i select a word and click a button it need to highlight all its occurrence inside a div,
eg - if i select
cricket is game
it should highlight all the occurrences of cricket is game some may be like this cricket is game or cricket is game
You can get the browser to do the hard work for you using a TextRange in IE and window.find() in other browsers.
This answer shows how to do it. It will match text that crosses element boundaries and does the highlighting for you using document.execCommand().
Alternatively, James Padolsey recently published a script that I haven't used but looks like it could help: http://james.padolsey.com/javascript/replacing-text-in-the-dom-solved/
mark.js seems pretty good for this. Here's my 3 line fiddle to take an html 'string' and highlight the search string.
$(document).ready(function() {
var html_string = "<b>Major Tom to groundcontrol.</b> Earth is blue <span> and there's something </span> i can do";
var with_highlight = $("<div/>").html(html_string).mark("can");
$("#msg").html(with_highlight);
})
Link to jsfiddle
You can tryout this script Demo
in highlightSearchTerms function of this script var bodyText = document.body.innerHTML; get replace by your divid and than it will do the task for you..
/*
* This is the function that actually highlights a text string by
* adding HTML tags before and after all occurrences of the search
* term. You can pass your own tags if you'd like, or if the
* highlightStartTag or highlightEndTag parameters are omitted or
* are empty strings then the default <font> tags will be used.
*/
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag)
{
// the highlightStartTag and highlightEndTag parameters are optional
if ((!highlightStartTag) || (!highlightEndTag)) {
highlightStartTag = "<font style='color:blue; background-color:yellow;'>";
highlightEndTag = "</font>";
}
// find all occurences of the search term in the given text,
// and add some "highlight" tags to them (we're not using a
// regular expression search, because we want to filter out
// matches that occur within HTML tags and script blocks, so
// we have to do a little extra validation)
var newText = "";
var i = -1;
var lcSearchTerm = searchTerm.toLowerCase();
var lcBodyText = bodyText.toLowerCase();
while (bodyText.length > 0) {
i = lcBodyText.indexOf(lcSearchTerm, i+1);
if (i < 0) {
newText += bodyText;
bodyText = "";
} else {
// skip anything inside an HTML tag
if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
// skip anything inside a <script> block
if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
bodyText = bodyText.substr(i + searchTerm.length);
lcBodyText = bodyText.toLowerCase();
i = -1;
}
}
}
}
return newText;
}
/*
* This is sort of a wrapper function to the doHighlight function.
* It takes the searchText that you pass, optionally splits it into
* separate words, and transforms the text on the current web page.
* Only the "searchText" parameter is required; all other parameters
* are optional and can be omitted.
*/
function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)
{
// if the treatAsPhrase parameter is true, then we should search for
// the entire phrase that was entered; otherwise, we will split the
// search string so that each word is searched for and highlighted
// individually
if (treatAsPhrase) {
searchArray = [searchText];
} else {
searchArray = searchText.split(" ");
}
if (!document.body || typeof(document.body.innerHTML) == "undefined") {
if (warnOnFailure) {
alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
}
return false;
}
var bodyText = document.body.innerHTML;
for (var i = 0; i < searchArray.length; i++) {
bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
}
document.body.innerHTML = bodyText;
return true;
}
/*
* This displays a dialog box that allows a user to enter their own
* search terms to highlight on the page, and then passes the search
* text or phrase to the highlightSearchTerms function. All parameters
* are optional.
*/
function searchPrompt(defaultText, treatAsPhrase, textColor, bgColor)
{
// This function prompts the user for any words that should
// be highlighted on this web page
if (!defaultText) {
defaultText = "";
}
// we can optionally use our own highlight tag values
if ((!textColor) || (!bgColor)) {
highlightStartTag = "";
highlightEndTag = "";
} else {
highlightStartTag = "<font style='color:" + textColor + "; background-color:" + bgColor + ";'>";
highlightEndTag = "</font>";
}
if (treatAsPhrase) {
promptText = "Please enter the phrase you'd like to search for:";
} else {
promptText = "Please enter the words you'd like to search for, separated by spaces:";
}
searchText = prompt(promptText, defaultText);
if (!searchText) {
alert("No search terms were entered. Exiting function.");
return false;
}
return highlightSearchTerms(searchText, treatAsPhrase, true, highlightStartTag, highlightEndTag);
}
This should get you started: http://jsfiddle.net/wDN5M/
function getSelText() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection();
} else if (document.getSelection) {
txt = document.getSelection();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
document.getElementById('mydiv').innerHTML = document.getElementById('mydiv').innerHTML.split(txt).join('<span class="highlight">' + txt + '</span>');
}
See: Get selected text on the page (not in a textarea) with jQuery
If you want it to work across element boundaries your code will need to be more involved than this. jQuery will make your life easier when doing the necessary DOM traversal and manipulation.
I would use jQuery to iterate over all Elements in your div (Don't know if you have other elements in the div) and then a Regular Expression and do a greedy match to find all occurrences of the selected string in your text(s) in the elements.
First you need to find needed substrings in needed text and wrap them with <span class="search-highlight">. Every time you need to highlight another strings, you just get all the .search-highlight spans and turn their outerHtml into innerHtml.
So the code will be close to:
function highLight(substring, block) {
$(block).find(".search-highlight").each(function () {
$(this).outerHtml($(this).html());
});
// now the block is free from previous highlights
$(block).html($(block).html().replace(/substring/g, '<span class="search-highlight">' + substring + '</span>'));
}
<form id=f1 name="f1" action=""
onSubmit="if(this.t1.value!=null && this.t1.value!='')
findString(this.t1.value);return false"
>
<input type="text" id=t1 name=t1size=20>
<input type="submit" name=b1 value="Find">
</form>
<script>
var TRange=null;
function findString (str) {
if (parseInt(navigator.appVersion)<4) return;
var strFound;
if (window.find) {
// CODE FOR BROWSERS THAT SUPPORT window.find
strFound=self.find(str);
if (!strFound) {
strFound=self.find(str,0,1);
while (self.find(str,0,1)) continue;
}
}
else if (navigator.appName.indexOf("Microsoft")!=-1) {
// EXPLORER-SPECIFIC CODE
if (TRange!=null) {
TRange.collapse(false);
strFound=TRange.findText(str);
if (strFound) TRange.select();
}
if (TRange==null || strFound==0) {
TRange=self.document.body.createTextRange();
strFound=TRange.findText(str);
if (strFound) TRange.select();
}
}
else if (navigator.appName=="Opera") {
alert ("Opera browsers not supported, sorry...")
return;
}
if (!strFound) alert ("String '"+str+"' not found!")
return;
}
</script>
Much better to use rather JavaScript str.replace() function then window.find() to find all occurrences of a filter value. Iterating through the whole page might be bit complicated but if you want to search within a parent div, or within a table str.replace() is just simpler.
In your example you have only one DIV, that is even simpler. Here is what I would do (having your DIV an ID: myDIV):
//Searching for "District Court"
var filter = "District Court";
//Here we create the highlight with html tag: <mark> around filter
var span = '<mark>' + filter + '</mark>';
//take the content of the DIV you want to highlight
var searchInthisDiv = document.getElementById("MyDiv");
var textInDiv = searchInthisDiv.innerHTML;
//needed this var for replace function, do the replace (the highlighting)
var highlighted = textInDiv.replace(filter,span);
textInDiv.innerHTML = highlighted;
The trick is to replace the search string with a span that is having the filter within a tag.
str.replace replaces all occurrences of the search string, so no need to bother with looping. Loop can be used to loop through DIVs or other DOM elements.

Categories