Thursday, February 6, 2014

Shorten length of string if it is too large and set ... at the end of sentence or word

I am getting a very large text without any space so it is overflowing parent container, so to manage that situation it will be better if we can calculate the width and trim last part and set ... at the end of the line to show continuation. To do this I have implemented following thing, here if content width is larger than parent width then it will show ... at the end of line and if not then show text as it is. While resizing the window at that time also it will work.

BEST WAY JUST USE CSS

.shortenText {
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

}

<span class="shortenText">test string where ...will come at the end of line if line is very long</span>

Using JQUERY
Here I have user attribute to locate the text container.
Hover the content with ... will show the content in tooltip.

EXAMPLE:

<style type="text/css">
    [autowidth='auto']
    {
        display: none;
    }
</style>

<div style="width:20%">
    <div >
        <div autowidth="auto">abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz</div>      
    </div>
</div>

<script type="text/javascript">
    $(document).ready(function () {
              resizeText();
    });

    $(window).resize(function () {
        resizeText();
    });

 function resizeText() {
        $("[autowidth='auto']").parent().find('.dot').remove()
        $("[autowidth='auto']").parent().find('.resized').remove()

        $("[autowidth='auto']").each(function () {

            var width = $(this).parent().width();
            var childDivWidth = $(this).width();

            var dotwidth = 10;
            var mainContainerCalculatedWidth = width - (dotwidth + 1);
            
            var maindiv = $("<div class='resized'>").text($(this).text()).css('width', mainContainerCalculatedWidth + 'px').css('float', 'left').css('overflow', 'hidden');
            $(this).parent().append(maindiv);

            if (childDivWidth > width) {
                var extra = $("<div class='dot'>").text('...').css('width', dotwidth + 'px').css('float', 'left').attr('title', $(this).text());
                $(this).parent().append(extra);
            }
        });
    }
</script>

No comments:

Post a Comment