5

How can I detect if a user selection (highlighting with mouse) is within/a child of a certain element?

Example:

<div id="parent">
   sdfsdf
   <div id="container">
       some 
      <span>content</span>
   </div>
   sdfsd
</div>

pseudo code:

if window.getSelection().getRangeAt(0) is a child of #container
 return true;
else
 return false;
Sam
  • 123
  • 1
  • 9
  • 1
    This may throw some light http://stackoverflow.com/questions/6251937/how-to-get-selecteduser-highlighted-text-in-contenteditable-element-and-replac – Shyju May 30 '12 at 03:41
  • 1
    Since you're using jQuery, [Caret](http://www.jquery-plugin.buss.hk/my-plugins/jquery-caret-plugin) is pretty cool. – mayhewr May 30 '12 at 03:42

2 Answers2

2

Using jQuery on() event handler

$(function() {
     $("#container > * ").on("click", 
         function(event){
            return true;
         });
     });​

Edit: http://jsfiddle.net/9DMaG/1/

<div id="parent">outside
    <div id="container">
        outside
        <span>first_span_clickMe</span>
        <span>second_span_clickMe</span>
    </div>
 outside</div>


$(function() {
   $("#container > span").on("click", function(){
       $('body').append("<br/>child clicked");
   });
});​

Eric Fortis
  • 16,372
  • 6
  • 41
  • 62
0

Ok I managed to solve this in a "dirty" way. The code could use improvement but it did the job for me and I am lazy to change it now. Basically I loop through the object of the selection checking if at some point it reaches an element with the specified class.

    var inArticle = false;
    // The class you want to check:
    var parentClass = "g-body"; 

    function checkParent(e){
        if(e.parentElement && e.parentElement != $('body')){
            if ($(e).hasClass(parentClass)) {
                inArticle = true;
                return true;
            }else{
                checkParent(e.parentElement);
            }
        }else{
            return false;
        }
    }


    $(document).on('mouseup', function(){
        // Check if there is a selection
        if(window.getSelection().type != "None"){
            // Check if the selection is collapsed
            if (!window.getSelection().getRangeAt(0).collapsed) {
                inArticle = false;

                // Check if selection has parent
                if (window.getSelection().getRangeAt(0).commonAncestorContainer.parentElement) {
                    // Pass the parent for checking
                    checkParent(window.getSelection().getRangeAt(0).commonAncestorContainer.parentElement);
                };


                if (inArticle === true) {
                    // If in element do something
                    alert("You have selected something in the target element");
                }
            };
        }
    });

JSFiddle

bukka
  • 4,973
  • 3
  • 19
  • 21