Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fill Content(html) in div for fix height and widhth using javascript and jquery

I am getting long text using ajax in json form I want to fill those content in the fix height div

suppose I have div height 500px and width 300px. and font size is 16px

i want any javascript recursive method that can fill data according to height and width of div and can return me remaining text.

if any one can do that then Please provide me solution.

Thanks in Advance

like image 814
Ajay Kurmi Avatar asked Jan 22 '26 13:01

Ajay Kurmi


1 Answers

First of all, wrap the text inside a <span> in put it in your <div>. I'm assuming that div is your fixed size element here:

// Be careful about text nodes, or use firstElementChild instead
var span = div.firstChild, text = span.innerText, rest = "";
if (span.offsetHeight > 500) {
    var totalLength = 0, markLength, i = 0,
        rects = span.getClientRects();
    for (; i < rects.length; i++) {
        totalLength += rects[i].right - rects[i].left;
        if (rects[i].bottom - rects[0].top <= 500)
            markLength = totalLength;
    }
    var mark = Math.floor(text.length * markLength / totalLength);
    span.textContent = text.substring(0, mark);
    rest = text.substring(mark);
}

The variable rest contains the remaining part. Beware that this method uses some approximations, and sometimes may not fill the container to the brim. In some unlucky cases, it may even overflow the container, so you have to run it again until you get the correct size.

like image 51
MaxArt Avatar answered Jan 25 '26 04:01

MaxArt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!