views:

33

answers:

2

I want to make an element dbl clickable, and when they do it, it selects text which is a little ugly. Is there a way to deselect text with JavaScript (or jQuery) or just make it not select text in the first place? Its on an <h1> element by the way.

Also, some have suggested:

$.fn.extend({ 
        disableSelection: function() { 
            this.each(function() { 
                if (typeof this.onselectstart != 'undefined') {
                    this.onselectstart = function() { return false; };
                } else if (typeof this.style.MozUserSelect != 'undefined') {
                    this.style.MozUserSelect = 'none';
                } else {
                    this.onmousedown = function() { return false; };
                }
            }); 
        } 
    });

However, this doesn't work unless i call it every time the new H1 is generated... Any ideas?

+1  A: 

I found this with a quick google:

http://chris-barr.com/entry/disable_text_selection_with_jquery/

Looks like exactly what you need. Basically every browser has a unique text selection implementation, and this jQuery snippet sniffs the browser and stops the text selection for each element you specify using CSS or JavaScript events, depending on which is needed.

Stephen
This works for all elements that are not dynamic :\ if i do it on, lets say, a <p> thats there on load, works great, for any of the AJAX elements i have to call this each time... any ideas?
Oscar Godson
+1  A: 

This will do it in all the major browsers, though it does unfortunately select text and then unselect it again when you double click:

document.ondblclick = function() {
    if (window.getSelection) {
        window.getSelection().removeAllRanges();
    } else if (document.selection) {
        document.selection.empty();
    }
};
Tim Down
Best working one so far. I dont mind the flicker at all. It was just ugly because i had a modal popup on dbl click and and you could see the highlighted word under the faded out background. Thanks!
Oscar Godson