Ray
Ray

Reputation: 685

Javascript/Jquery Syntax to Disable Text Selection on a Div AND all Child Elements?

What is the syntax to disable text selection on a div and all of it's sub elements. I'm using $("#MyContent).disableSelection() to disable all of the text in the below code and it works in firefox and disable all three lines at once.

In IE explorer 9 it doesn't work on child elements so to disable all of the text I'd have to do $("#text1).disableSelection(), $("#text2).disableSelection(), $("#text3).disableSelection(). What is the syntax to disable or apply this to all children at once?

<div id="MyContent">
  <div id="text1">Hello World</div>
  <div id="text2">Goodbye</div>
  <div id="text3">Asdf</div>
</div>

Upvotes: 1

Views: 1282

Answers (2)

Jignesh Rajput
Jignesh Rajput

Reputation: 3558

This works for me:

$('#MyContent').children().each(function(i, c) {
    disableSelection(c);
});

function disableSelection(target) {
    console.debug(target);

    if (typeof target.onselectstart != "undefined")             // For IE
        target.onselectstart = function() { return false };
    else if (typeof target.style.MozUserSelect != "undefined")  // For Firefox
        target.style.MozUserSelect = "none";
    else                                                        // All other routes (Opera, etc.).
        target.onmousedown = function() { return false };

    target.style.cursor = "default";
}

Demo : http://jsfiddle.net/9vLFD/4/

Upvotes: 1

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

You could try

$('#MyContent').children().each(function(i,c){
    $(c).disableSelection();
});

Upvotes: 0

Related Questions