1

With this I'd like to change the default select behavior for a document. I do that for the document body with getElmentsByTagName. But the code doesn't actually have the desired effect, which is to prevent the user from clicking to select text in the document.

<script>
    $(document).ready ( function () {
        document.getElementsByTagName("body").addEventListener('mousedown', function(e) { e.preventDefault(); }, false);
    });
</script>

This works elsewhere on my site to prevent select on specific page elements. How do I do this for the entire document?

jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
user823527
  • 3,644
  • 17
  • 66
  • 110
  • You can prevent selection purely using CSS: http://stackoverflow.com/questions/826782/css-rule-to-disable-text-selection-highlighting – RoccoC5 May 19 '12 at 18:38

3 Answers3

0

You have a typo in your function. When you select an element using getElementsByTagName, you're actually receiving a collection, even if there is only one element on the page. Thus, use [0] to indicate you want the first body element returned in the collection:

    document.getElementsByTagName("body")[0].
        addEventListener('mousedown', 
            function(e) { 
                e.preventDefault(); 
            }, false);

This will of course prevent text from being selected, so that solves your problem.

UPDATE:

I just now realized you didn't need to disable clicking on anchor tags, but I'll leave this here for people that want to disable those clicks as well.

However, to prevent links from being clicked, you must use another approach:

// bind click event to parent elements of anchor tags,
 // or it won't work properly
$('a').parent().each(function() {
    $(this).attr("href","#");
    $(this).unbind();
    $(this).click(function() {
        event.preventDefault();
        return false;
    });
});
jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
0
$(document).ready ( function () {
    $(document).on('mousedown', function(e) { 
        e.preventDefault(); 
    });
});​

Another answer on SO.

Community
  • 1
  • 1
The Alpha
  • 143,660
  • 29
  • 287
  • 307
0

Found that I could also do this with CSS with this.

<style>
*:not(input) {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;      
}
</style>
user823527
  • 3,644
  • 17
  • 66
  • 110