Tuesday, September 28, 2010

jQuery plugin to disable text selection on elements

It took my a while to find a bit of script that worked cross browser, but the jquery plugin at http://code.jdempster.com/jQuery.DisableTextSelect/ does the job!
When working on the UI of a web application text would often get selected by the browser incorrectly, for example while dragging an element, or clicking on an element with an onclick event.
If you are using jquery already; download it, include it, then use:
$(‘.elementsToDisableSelectFor’).disableTextSelect();
If you need this functionality without including the whole of jquery, take a look at the source code for the plugin. It’s only about 20 lines long. It uses a different method for Firefox and Internet Explorer, with a fallback for everything else but it should be easy to convert in to native JS or another javascript framework.

(function($) {
    if ($.browser.mozilla) {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).css({
                    'MozUserSelect' : 'none'
                });
            });
        };
        $.fn.enableTextSelect = function() {
            return this.each(function() {
                $(this).css({
                    'MozUserSelect' : ''
                });
            });
        };
    } else if ($.browser.msie) {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).bind('selectstart.disableTextSelect', function() {
                    return false;
                });
            });
        };
        $.fn.enableTextSelect = function() {
            return this.each(function() {
                $(this).unbind('selectstart.disableTextSelect');
            });
        };
    } else {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).bind('mousedown.disableTextSelect', function() {
                    return false;
                });
            });
        };
        $.fn.enableTextSelect = function() {
            return this.each(function() {
                $(this).unbind('mousedown.disableTextSelect');
            });
        };
    }
})(jQuery);

http://www.blograndom.com/blog/2009/07/jquery-plugin-to-disable-text-selection-on-elements/

No comments: