I have scanned stackoverflow all over for a solution regarding my query and resulted in posting a question. Please could someone assist me, my skill sets sit in PHP and I am not 100% fluent in JS/jQuery.
My code below allows for the div text to be shorted if more than 8 characters.
<div id="theText">Very long text here</div>
<script>
function cutString(id){
var text = document.getElementById(id).innerHTML;
var charsToCutTo = 8;
if(text.length>charsToCutTo){
var strShort = "";
for(i = 0; i < charsToCutTo; i++){
strShort += text[i];
}
document.getElementById(id).title = "text";
document.getElementById(id).innerHTML = strShort + "...";
}
};
cutString('theText');
</script>
However I am now trying to do this on multiple Div as per the below code, I think the method I should be using is arrays, below is a none working version but the concept where I am looking for guidance.
Any help is appreciated.
<div id="theText[]">Very long text here</div>
<div id="theText[]">Even more long text here</div>
<script>
function cutString(id){
var text = document.getElementById(id).innerHTML;
var charsToCutTo = 8;
if(text.length>charsToCutTo){
var strShort = "";
for(i = 0; i < charsToCutTo; i++){
strShort += text[i];
}
document.getElementById(id).title = "text";
document.getElementById(id).innerHTML = strShort + "...";
}
};
cutString('theText[]');
</script>
2
Answers
One of the methods is to specify the index of the array (0,1,2…)
So in your case, you have theText[0] and theText[1] to process.
This is the code which is working:
I think Ken Lee answered the question correctly, but I think OP is wanting to take a more dynamic approach, in which case I’d recommend moving away from IDs and into classes as they (classes) lend themselves better to iteration, as shown below:
I’ve included a JSFiddle
Alternatively, if you are looking for basic width-based elipsis, CSS3 already caters for this:
Ellipsis Overflow