I am working on some code that is using dynamically generated graphs. And all of these graphs have legends at the y-axis. Now my goal is to check how long the longest legend-string is, and if the longest one is bigger than 20 characters, I only want to show the first characters of every string.
With the code below, I achieved that i can alert the desired shortened strings; but I do not know how to change the text now with these new strings.
var textLengthArray = [];
var labelStrings = domContainer.find(" g > .brm-y-direction > .tick > text");
labelStrings.each(function() {
textLengthArray.push($(this).text());
});
var longestString = textLengthArray.sort(function(a, b) {
return b.length - a.length;
})[0];
if (longestString.length >= 20) {
$("g.tick text").css("font-size", "9pt");
var offsetLeft = longestString.length * 3.7;
textLengthArray.map(function(sub) {
var subString = sub.substring(0, 6);
alert(subString);
});
};
I have tried something like:
$(labelStrings).replaceWith(subString)
With this, I had no legend at all, since I have replaced the whole text tag and all of its attributes with the new string.
So is there any way of not touching the tag and its values at all, but simply change the text between the opening and closing tag?
Thanks in advance!
sth. like this?
var $nodes = domContainer.find(" g > .brm-y-direction > .tick > text");
var longestLength = 0;
$nodes.each(function(){
longestLength = Math.max(longestLength, $(this).text().length);
});
if(longestLength >= 20){
$("g.tick text").css("font-size", "9pt");
var offsetLeft = longestLength * 3.7;
$nodes.each(function(){
var $this = $(this);
var text = $this.text();
var substr = text.substr(0, 6);
console.log(substr);
$this.text(substr);
});
}
That is basics you should research Google before coming to SO, anyway you can use $(labelStrings).html(subString) or $(labelStrings).text(subString) - they will both change only the inner content between the tags
Related
I am working on inserting text to the bottom of certain wordpress posts based on the amount of times a string occurs. I've managed to add the text to the bottom with append but instead I would like to insert at a specific location using indexOf.
here is the original text:
if ($('body').hasClass("single-post")){
var count = 0;
var cSearch = $('body').text();
var words = cSearch.indexOf('Words To Find')
while (words !== -1){
count++;
words = cSearch.indexOf('Words To Find', words + 1);
}
if( count >= 2){
$('.entry-content').append('<br><br>Sample Text');
}
}
Here is how I will get the location I want to insert before:
var insertLocation = cSearch.indexOf('Show what ya');
How can I splice the "Sample Text" into the location specified with insertLocation?
I found a bit about using polyfil for .splice but I'm not sure it works for this. Using it such as:
$(cSearch).splice( insertLocation, -1 ).text( "Sample Text" );
Can someone suggest a way to do this? Thanks!
Try creating variables representing total matches , indexOf() match plus matched text .length , using .slice() to insert original text before second match , new text ti insert , followed by remainder of original text
var text = $("div").text(),
match = "Words To Find",
txt = " Sample Text ",
matches = 0,
n = 0,
// `max` : total number of `matches` before inserting `txt`
max = 2;
while (matches < max) {
if (text.indexOf(match, n) !== -1) {
i = text.indexOf(match, n);
n = i + match.length;
++matches
}
}
// insert `re` after second match of `"Words To find"`
var re = text.slice(0, i + match.length) + txt;
$("div").text(re + text.slice(i));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<body>
<div>Words To Find abc def Words To Find ghi Words To Find</div>
</body>
I have this long string and I want a part of it transformed into white colour using only JavaScript.
Example 1:
var string = document.getElementById("subtitle").innerHTML; //returns the string
var i = string.indexOf("("); //returns 80
var j = string.indexOf(")"); //return 93
Example 2: I can get the wanted text but I don't know how to change it white
var string = document.getElementById("subtitle").innerHTML; //returns the string
var i = string.indexOf("(");
var j = string.substring(i, string.indexOf(")")+1); //return the exact string I want to paint white
//j.paintWhite(); how?
I would like to paint all the characters between positions 80 and 93 (or selected as shown in example #2) white. How can I do it?
You need to create an html container for that text where you can specify a style attribute.
also, do not use the variable name string as it is reserved to the language
In order to do that, I would recommend using jQuery, as it is a bit easier.
But if you don't want to, you can do:
var text = document.getElementById("subtitle").innerHTML;
var cut = text.split("(");
var cut2 = cut[1].split(")");
var colored = cut[0] + '<span style="color:#fff;">('+cut2[0]+')</span>'+cut2[1];
document.getElementById("subtitle").innerHTML = colored;
if you assume "transformed into white colour" is doing
<span style="color:#fff">MY_TEXT_HERE</span>
then you could try the following with arrays:
var string = document.getElementById("subtitle").innerHTML;
var arr1 = string.split('(');
var arr2 = arr1[1].split(')');
var finalString = arr1[0] + '<span style="color:#fff">' + arr2[0] + '</span>' + arr2[1];
You must modify the inner Html of the element so it has a text element nested with a defind style.
http://jsfiddle.net/gsexxsbs/
var element = document.getElementById("subtitle");
var htmlText = element.innerHTML;
var i = htmlText.indexOf("(");
var j = htmlText.indexOf(")")+1;
var redText = htmlText.substring(i, j);
element.innerHTML = htmlText.substring(0,i)+"<a style='color:red;'>"+redText+"</a>"+htmlText.substring(j);
I have a script which is almost complete but I can't figure out the last bit here. The script is meant to limit the amount of words that can be entered into a text area and if they go over the word limit these extra words are removed. I have the amount of words beyond the max labeled as overage. For instance, if you were to enter in 102 words, then the overage would be 2. How would I remove those two words from the text area?
jQuery(document).ready(function($) {
var max = 100;
$('#text').keyup(function(e) {
if (e.which < 0x20) {
return;
}
var value = $('#text').val();
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
if (wordCount == max) {
// Reached max, prevent additional.
e.preventDefault();
} else if (wordCount > max) {
<!--Edited to show code from user3003216-->
<!--Isn't working like this, textarea doesn't update.-->
var overage = wordCount - max;
var words = value.split(' ');
for(var i = 0; i<overage; i++){
words.pop();
}
}
});
});
The easiest way to approach this is just to count the number of words on keypress and go from there. Check whether there are more words than the amount allowed. If so, remove all the excess words: while (text.length > maxWords). Then just replace the value of the text box with the updated text.
fiddle
JavaScript
var maxWords = 10;
$("#myText").keypress(function (event) {
var text = $(this).val().split(" "); // grabs the text and splits it
while (text.length > maxWords) { // while more words than maxWords
event.preventDefault();
text.pop(); // remove the last word
// event.preventDefault() isn't absolutely necessary,
// it just slightly alters the typing;
// remove it to see the difference
}
$(this).val(text.join(" ")); // replace the text with the updated text
})
HTML
<p>Enter no more than 10 words:</p>
<textarea id="myText"></textarea>
CSS
textarea {
width: 300px;
height: 100px;
}
You can easily test whether it works by pasting more than maxWords—in this case, 10—words into the textarea and pressing space. All the extra words will be removed.
You can put below code into your else if statement..
else if (wordCount > max) {
var overage = wordCount - max;
var words = value.split(' ');
for(var i = 0; i<overage; i++){
words.pop();
}
}
And if you want to get your string back from that words, you can use join like below:
str = words.join(' ');
well it would be better to use java script so here you go:
var maxWords = 20;
event.rc = true;
var words = event.value.split(" ");
if (words.length>maxWords) {
app.alert("You may not enter more than " + maxWords + " words in this field.");
event.rc = false;
}
jsFiddle Demo
You can use val to re-value the text-box. The array slice method will allow you to pull the first 100 words out of the array. Then just join them with a space and stick them back in the text-box.
$(document).ready(function($) {
var max = 100;
$('#text').keyup(function(e) {
if (e.which < 0x20) {
return;
}
var value = $('#text').val();
var words = value.trim().split(/\s+/gi);
var wordCount = words.length;
if (wordCount == max) {
// Reached max, prevent additional.
e.preventDefault();
} else if (wordCount > max) {
var substring = words.slice(0, max).join(' ');
$("#text").val(substring + ' ');
}
});
});
While you've already accepted an answer I thought I might be able to offer a slightly more refined version:
function limitWords(max){
// setting the value of the textarea:
$(this).val(function(i,v){
// i: the index of the current element in the collection,
// v: the current (pre-manipulation) value of the element.
// splitting the value by sequences of white-space characters,
// turning it into an Array. Slicing that array taking the first 10 elements,
// joining these words back together with a single space between them:
return v.split(/\s+/).slice(0,10).join(' ');
});
}
$('#demo').on('keyup paste input', limitWords);
JS Fiddle demo.
References:
JavaScript:
Array.prototype.join().
Array.prototype.slice().
String.prototype.split().
jQuery:
on().
val().
<div><span>aaaaaa</span> ... (many other span here) ... <span>zzzzzz</span></div>
In that case, the boxes span are placed on few line-boxes inside the div.
(The span elements can use different font-size.)
1) How can we know the number of the line-boxes ?
2) Can we know on which line-boxe an element span is placed ?
3) Can we know on which line-boxe the caret is placed (contenteditable) ?
Thank you
I'll suppose the DOM in your example is an effective example of the actual complexity of your DOM, and that a "line-boxe" is just a line of text.
1-2) For every <span> inside the <div>, you can count the number of lines they span with something like this:
var spans = div.getElementsByTagName("span"), spandata = [];
for (var i = 0; i < spans.length; i++) {
var rects = spans[i].getClientRects();
if (i > 0)
if (rects[0].bottom > obj.rects[obj.rects - 1].bottom)
var inirow = obj.lastRow + 1;
else var inirow = obj.lastRow;
var obj = {
element: spans[i],
rects: rects,
iniRow: inirow,
lastRow: inirow + rects.length - 1
};
spandata.push(obj);
}
Now spandata is a list of all the data you want about the <span> elements. I'm also supposing that each one of them may span through more than one line.
Keep in mind that getClientRects has some issues in IE<8.
3) In modern browsers, the getSelection method can help you:
var sel = window.getSelection();
if (sel.type === "Caret")
var span = sel.anchorNode.parentNode;
About the line position, I must say it's not an easy task. You can't easily get the page position of the caret. The simplest thing you can do is to place a dummy inline element in the place of the caret:
var text = sel.anchorNode.nodeValue;
sel.anchorNode.nodeValue = text.substring(0, sel.anchorOffset);
var dummy = document.createElement("i");
span.appendChild(dummy);
var pos = dummy.getBoundingClientRect();
sel.anchorNode.nodeValue = text;
span.removeChild(dummy);
pos contains the info of the position of the caret. Now you have to compare them with the rect infos about the span:
var rects = span.getClientRects();
for (var i = 0; i < rects.length; i++)
if (rects[i]].bottom === pos.bottom) break;
if (i < rects.length) {
for (var i = 0; i < spandata.length; i++) {
if (spandata[i].element === span) {
var line = spandata[i].iniRow + i;
break;
}
}
}
In the end, if line != null, it contains the line of the caret.
Man, that was complicated...
Let's say your div is in the el variable:
el.children.length; // Number of direct children
// You have one of the children in the "child" variable, to know its index:
[].indexOf.call( el.children, child ); // Index of child in el.children
I'm not mentioning the cross-browser issues there, but Array.prototype.indexOf is only available starting IE9 (so it works in all modern browsers).
I'm developing a Classic ASP page that pulls some content from a database and creates a Read more link after the first 100 characters as follows;
<div class="contentdetail"><%=StripHTML(rspropertyresults.Fields.Item("ContentDetails").Value)%></div>
<script type="text/javascript">
$(function() {
var cutoff = 200;
var text = $('div.contentdetail').text();
var rest = $('div.contentdetail').text().substring(cutoff);
if (text.length > 200) {
var period = rest.indexOf('.');
var space = rest.indexOf(' ');
cutoff += Math.max(Math.min(period, space), 0);
}
var visibleText = $('div.contentdetail').text().substring(0, cutoff);
$('div.contentdetail')
.html(visibleText + ('<span>' + rest + '</span>'))
.append('<a title="Read More" style="font-weight:bold;display: block; cursor: pointer;">Read More…</a>')
.click(function() {
$(this).find('span').toggle();
$(this).find('a:last').hide();
});
$('div.contentdetail span').hide();
});
</script>
However, the script obviously just cuts the text off after 100 characters. Preferably I would like it to keep on writing text until the first period or space, for example. Is this possible to do?
Thank you.
var cutoff = 100;
var text = $('div.contentdetail').text();
var rest = text.substring(cutoff);
if (text.length > cutoff) {
var period = rest.indexOf('.');
var space = rest.indexOf(' ');
cutoff += Math.max(Math.min(period, space), 0);
}
// Assign the rest again, because we recalculated the cutoff
rest = text.substring(cutoff);
var visibleText = $('div.contentdetail').text().substring(0, cutoff);
EDIT: shortened it a bit.
EDIT: Fixed a bug
EDIT: QoL improvement
How about:
var text= $('div.contentdetail').text();
var match= text.match( /^(.{100}([^ .]{0,20}[ .])?)(.{20,})$/ );
if (match!==null) {
var visibleText = match[1];
var textToHide = match[3];
...do replacement...
}
The {0,20} will look forward for a space or period for up to 20 characters before giving up and breaking at exactly 100 characters. This stops an extremely long word from breaking out of the length limitation. The {20,} at the end stops a match being made when it would only hide a pointlessly small amount of content.
As for the replacement code, don't do this:
.html(visibleText + ('<span>' + textToHide + '</span>'))
This is inserting plain-text into an HTML context without any escaping. If visibleText or textToHide contains any < or & characters you will be mangling them, perhaps causing a XSS security problem in the process.
Instead create the set the text() of the div and the span separately, since that's the way you read the text in the first place.
Here is a fairly simple approach to getting endings at the word level, and shooting for about your given limit in characters.
var limit = 100,
text = $('div.contentdetail').text().split(/\s+/),
word,
letter_count = 0,
trunc = '',
i = 0;
while (i < text.length && letter_count < limit) {
word = text[i++];
trunc += word+' ';
letter_count = trunc.length-1;
}
trunc = $.trim(trunc)+'...';
console.log(trunc);