Calculate Text Width with jQuery

Calculate Text Width with jQuery

This jQuery plugin should calculate the textwidth of elements.

jQuery.fn.textWidth = function(){
    var _t = jQuery(this);
    var html_org = _t.html();
    if(_t[0].nodeName=='INPUT'){
        html_org = _t.val();
    }
    var html_calcS = '' + html_org + '';
    jQuery('body').append(html_calcS);
    var _lastspan = jQuery('span').last();
    //console.log(_lastspan, html_calc);
    _lastspan.css({
        'font-size' : _t.css('font-size')
        ,'font-family' : _t.css('font-family')
    })
    var width =_lastspan.width() + 5;
    //_t.html(html_org);
    _lastspan.remove();
    return width;
};

Mode of usage:

alert($('#theelement').textWidth());

PS: Works on input elements too.

  • Catatan Belajar
    March 28, 2014 at 11:06 am

    Thank guy, helpful a lot.

  • zellina
    March 2, 2015 at 10:44 pm

    Sometimes it is very difficult to find good content on this topic. But your post is my way to desired information, my problem is solved now. Thanks for posting something worth knowledge
    http://www.pro-autogas.com

  • okhomeexteriors
    March 26, 2015 at 7:25 pm

    You actually make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it!

  • Business of Guam
    June 1, 2015 at 10:23 pm

    You may post on the professional credentials for the blog owner. You could express it’s outstanding. Your blog experience can springboard your click through.

  • www.youragingpets.com
    June 6, 2015 at 9:19 am

    Hey very nice web site!! Man .. Excellent .. Amazing .. its a really great blog post of i enjoyed lot.thanks again for share with us.

  • randy-houser
    June 9, 2015 at 5:57 pm

    You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant!

Leave a comment

Your email address will not be published

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

5 + 3 =