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.
Here is the JSFiddle demo: http://jsfiddle.net/qox0yxb4/
I am using type() to create a typewriter affect (each character is printed on the screen with a delay in between). I use addTextToScreen(textForScreen) to add text to the queue which is then added to the screen through type(). When I call addTextToScreen() from within the JavaScript, the text seems to be formatted as it does NOT overflow on the x-axis, however when I accept input from an HTML <input> tag (printText()), the text overflows on the x-axis.
Here are the JavaScript methods:
var i = 0,
isTag=false,
text;
var typeTime = 45;
function type() {
if (text === textOnScreen){
setTimeout(function(){type();}, typeTime);
return;
}
text = textOnScreen.slice(0, i+1);
i++;
document.getElementById('paraText').innerHTML = text;
var char = text.slice(-1);
console.log(char);
if( char === '<' ) isTag = true;
if( char === '>' ) isTag = false;
if (isTag) return type();
setTimeout(function(){type();}, typeTime);
}
function addTextToScreen(textForScreen){
textOnScreen = textOnScreen + textForScreen;
}
type();
function printText(event) {
if(event.keyCode == 13){
printText = document.getElementById("inputText").value.toString();
addTextToScreen("<br>" + printText.toString());
x = document.getElementById("inputText");
x.value = "";
}
}
I also noticed that whenever I paste text into the input box (the text can be from anywhere) it seems to be formatted, and it does NOT overflow.
Add this css property to #paraText:
word-wrap:break-word;
JS Fiddle Demo
Josh suggested using break-all, here is the difference.
The magic CSS rule you're missing is word-break: break-all;. Add that, and it works just like you'd expect.
Proof
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);
});
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
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.