graham73may
9/2/2016 - 9:01 PM

Check tile contents and trim them until they fit.js

Check tile contents and trim them until they fit.js


    $.fn.checkContentTileSize = function () {
        for (let i = 0; i < $(this).length; i++) {
            const $elem = $($(this)[i]);

            // Find main tile elements
            const $itemHeader = $elem.find('.js-content-check__header');
            const $itemBody   = $elem.find('.js-content-check__body');

            // What is the maximum height the contents can be?
            const maxHeight = $elem.height() - $itemHeader.height();

            // Is the content too big for the tile?
            const contentFits = (maxHeight >= $itemBody.outerHeight());

            // If the content doesn't fit, start cropping the text.
            if (!contentFits) {
                // Parts of the item
                const $title = $itemBody.find('.js-content-check__title-text');
                const $meta1 = $itemBody.find('.js-content-check__meta-1');
                const $meta2 = $itemBody.find('.js-content-check__meta-2');

                // Line heights to calculate preferred height of contents
                const titleLineHeight = $title.css('line-height').replace('px', '');
                const meta1LineHeight = $meta1.css('line-height').replace('px', '');
                const meta2LineHeight = $meta2.css('line-height').replace('px', '');

                // Max Limit for while loop
                let count = 0;

                console.log('Content doesn\'t fit inside "' + $title.text() + '"');
                console.log('--> Max content height = ', maxHeight);

                while (maxHeight < $itemBody.outerHeight() && count < 100) {
                    console.log('--> Resizing', $itemBody.outerHeight());

                    // Adjust the title
                    if ($title.height() > (titleLineHeight * 4)) {
                        $title.html($title.html().substring(0, ($title.html().length - 10)) + "...");
                    }

                    // Adjust Meta 1
                    if ($meta1.height() > (meta1LineHeight * 2)) {
                        $meta1.html($meta1.html().substring(0, ($meta1.html().length - 20)) + "...");
                    }

                    // Adjust Meta 2
                    if ($meta2.height() > (meta2LineHeight * 2)) {
                        $meta2.html($meta2.html().substring(0, ($meta2.html().length - 20)) + "...");
                    }

                    count++;
                }
            }
        }

        return this;
    };