Search code examples
javascriptjqueryscrollparents

jQuery parents() with object reference selector


I am trying to detect whether a target element is either a child element, or the same element, that I have as an object reference.

I am using the following logic:

$("html").on("mousewheel.scroll DOMMouseScroll.scroll",function(e){
   e.preventDefault();

   var $scrollableElement = $(".foo").eq(0);
   var $target = $(e.target);

   if ($target == $scrollableElement
       || $target.parents($scrollableElement).length) {                
        alert("scroll");                    
   }

});  

However "scroll" is alerted even when scrolling over an element which is neither .foo or a child of .foo.

In my JsFiddle example, scroll over the .bar element, and "scroll" is still alerted:

http://jsfiddle.net/Lf3d2/

Why is this? Is it possible to use jQuery object references as the selector of .parents()?


Solution

  • Try .closest() instead of .parents()

    $(function () {
    
        var $scrollableElement = $(".foo").eq(0);
        $("html").on("mousewheel.scroll DOMMouseScroll.scroll", function (e) {
            e.preventDefault();
    
            var $target = $(e.target);
    
            if ($target.closest($scrollableElement).length) {
                console.log("scroll");
            }
    
        });
    
    });
    

    Demo: Fiddle

    If you have a look at the syntax of .parents(), it does not take a jQuery object as a parameter. The only allowed syntax is .parents( [selector ] )


    As @A.Wolff asked why don't bind the event to .foo instead

    Demo: Fiddle