Skip to content

Instantly share code, notes, and snippets.

@UziTech
Created August 13, 2014 18:52
Show Gist options
  • Save UziTech/d45102cdffb1039d4415 to your computer and use it in GitHub Desktop.
Save UziTech/d45102cdffb1039d4415 to your computer and use it in GitHub Desktop.
jquery plugin for showing tooltip on overflow
/**
* DWTFYW License
* Author: Tony Brix, http://tonybrix.info
*
* jquery plugin for showing tooltip on overflow
*
* USAGE:
*
* $("input, select").tooltipOnOverflow();
*
*/
(function($) {
'use strict';
$.fn.tooltipOnOverflow = function() {
$(this).on("mouseenter", function() {
var text = $(this).text();
if ($(this).is("input")) {
text = $(this).val();
} else if ($(this).is("select")) {
text = $("option:selected", this).text();
}
var textWidth = text.width($(this).css("font-size"), $(this).css("font-family"), $(this).css("font-weight"));
if (this.clientWidth < textWidth) {
$(this).attr('title', text);
} else {
$(this).removeAttr("title");
}
});
};
})(jQuery);
//modified from http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript#5047712
String.prototype.width = function(fontSize, fontFamily, fontWeight) {
var fs = fontSize || '12px',
ff = fontFamily || 'Arial',
fw = fontWeight || 'normal',
o = $('<div>' + this + '</div>')
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font-size': fs, 'font-family': ff, 'font-weight': fw})
.appendTo($('body')),
w = o.width();
o.remove();
return w;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment