Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Tuesday, February 21, 2012

Truncating Text by Pixel Width

If you've ever tried truncating text by the number of characters then you've probably noticed that most of the fonts we use are not fixed-width, resulting in different lengths depending on which characters are used. This is particularly true of spaces which are much thinner than other characters.



I ran into this problem recently when creating a message preview module and I solved it by placing the text in a hidden div set to my desired width, then chopping off characters from the end until it fit. Of course, we don't want partial words so I wait until we reach a space before returning the truncated text.

Here is the div (placed in the page body):
<div id="hiddenTruncateHelper" style="position: absolute; visibility: hidden; display: block; height: auto;"></div>

...and the JavaScript:
var truncate = function (str, width, height) {
    var bits, bit, i;
    $("#hiddenTruncateHelper").width(width);
    $("#hiddenTruncateHelper").text(str);
    bits = str.split('');
    if ($("#hiddenTruncateHelper").getHiddenDimensions().height > height) {
        for (i = bits.length - 1; i > -1; --i) {
            $("#hiddenTruncateHelper").text(bits.join(''));
            bit = bits[i];
            bits.length = i;
            if (' ' === bit && $("#hiddenTruncateHelper").getHiddenDimensions().height <= height) {
                break;
            }
        }
    }
    return bits.join('');
};

One problem I had was that the browser kept returning zero for the div height because it is hidden. While searching for an answer I found a blog by Tim Banks where he shares an extension method to get the dimensions for a hidden element.
//Optional parameter includeMargin is used when calculating outer dimensions
(function ($) {
    $.fn.getHiddenDimensions = function (includeMargin) {
        var $item = this,
        props = { position: 'absolute', visibility: 'hidden', display: 'block' },
        dim = { width: 0, height: 0, innerWidth: 0, innerHeight: 0, outerWidth: 0, outerHeight: 0 },
$hiddenParents = $item.parents().andSelf().not(':visible'),
includeMargin = (includeMargin == null) ? false : includeMargin;

        var oldProps = [];
        $hiddenParents.each(function () {
            var old = {};

            for (var name in props) {
                old[name] = this.style[name];
                this.style[name] = props[name];
            }

            oldProps.push(old);
        });

        dim.width = $item.width();
        dim.outerWidth = $item.outerWidth(includeMargin);
        dim.innerWidth = $item.innerWidth();
        dim.height = $item.height();
        dim.innerHeight = $item.innerHeight();
        dim.outerHeight = $item.outerHeight(includeMargin);

        $hiddenParents.each(function (i) {
            var old = oldProps[i];
            for (var name in props) {
                this.style[name] = old[name];
            }
        });

        return dim;
    }
} (jQuery));

That's all there is to it. We just call our method and pass in the string, desired height and width (in pixels) and it returns the truncated text. Just add some ellipses with a tooltip (title) and we're done!
<a href="#" title="FULL TEXT">...</a>

If you have a suggestion for how this solution could be improved or a question, please post it here. Thanks for reading!

Friday, October 21, 2011

Knockout.js, AmplifyJS, FubuMVC and RavenDB

Working on a project for Street Theatre Company at Nashville Give Camp with Chris MeadowsJim Cowart and Alex Robson. I get to play with lots of nifty frameworks. We're using Knockout.js to bind the html view to the JavaScript object model. The AmplifyJS publish and subscribe (Pub/Sub) library allows us to wire up client-side model events to the Request layer. FubuMVC is a front controller pattern that we're using to serve up the model through RESTful endpoints.

Alex was the primary resource for data access and spent many hours working with RavenDB and FubuMVC. "Raven was huge", Alex said. "It made storage trivial. I loved how Fubu enabled us to build something that was test-able. I also think that Amplify and KO made it possible to deliver a UI that the customer (and a few devs) liked." We did encounter problems with FubuMVC handling REST and AmplifyJS receiving 500 response codes, but overall it worked well.

Of course, there was more to this project than technology. Jaime Janiszewski and Cathy Street from Street Theatre Company made themselves available all weekend and did a great job at working with us on what features were most important to them and could be accomplished during the weekend. "I was delighted with how easy it was to talk through things with Cathy and Jaime and would honestly request the opportunity to do more work for them in the future if given the chance," said Alex. Jim commented, "I loved interacting with a knowledgeable, appreciative and exciting end user."
"I loved GiveCamp, it was a great experience and we learned so much through the experience that we can't wait until the next one."
-Alex Robson

In the end, Give Camp was a great success. The charities got some great websites and the developers/designers had a blast. Many thanks to the organizers and sponsors who made it possible.


Tuesday, November 23, 2010

HTML5 Mobile Development

I received an email this morning with the master schedule for Code PaLOUsa and it looks like I'll be speaking on HTML5 Mobile Development. I'd love feedback on the session topic/description.

One of the biggest hurdles for mobile development is bridging the gap between incompatible platforms. From the very beginning HTML has been the only true cross platform solution and, with the introduction of HTML5, developers are now able to create rich applications. Microsoft has even begun shifting away from Silverlight and stated at PDC that HTML5 is the future. This session will provide the tools and techniques you need to get started developing mobile applications using HTML5, CSS3 and JavaScript.

Also, here's what I came up with for a speaker bio. I'm sure it could use some tweaking and would appreciate input.

Gaines Kergosien is a .NET Solutions Consultant for TEKsystems and is currently working with HCA Physician Services. Gaines founded the Nashville Web Developer Group and serves as a board member for the Nashville .NET User Group. With over 12 years in solutions development using Microsoft technologies, his work includes consulting for such companies as Lexis Nexis, Gibson Guitars, and Cardinal Healthcare.

Friday, January 23, 2009

Nashville Web Developer January Meeting Review

We had a great turnout for our first meeting and came up with some great suggestions for presentations. Thanks to everyone who participated. Here's a list of the meeting topics we're considering:
- Silverlight & XAML
- Silverlight 3rd Party Components
- ASP.NET Performance Considerations
- ASP.NET Security Considerations
- ASP.NET Page Lifecycle
- Introduction to JQuery
- Ajax/JavaScript Development
- Designing with Cascading Style Sheets (CSS)
- DotNetNuke Installation & Configuration (1/2)
- DotNetNuke Module Development (2/2)
- Overview of Visual Studio 2010
- Converting Classic ASP/ActiveX to ASP.NET
- Search Engine Optimization (SEO)

Joseph Wichman shared his experience creating streaming videos with Silverlight. They can be found in the Research Videos section of tnbackpackers.org.