Skip to content Skip to sidebar Skip to footer

This.offset Is Not A Function Within A Click Function

The error is that _this.offset is not a function. I logged this to the console and it was the
  • element I clicked on, so I am confused why this would not work. I also wan
  • Solution 1:

    this (and hence _this) inside your event handler refers to a DOMElement which doesn't have the offset() method as that's part of jQuery. To fix this you can create a jQuery object using $(this):

    $('.item').click(function(e) {
        var $this = $(this);
        var topx = $this.offset().top;
        var leftx = $this.offset().left;
        var moveArea = $('#replace').offset().top;
        var moveLeft = $('#replace').offset().left;
        var moveUp = topx - moveArea - 50;
    
        $this.css({
            'position': 'absolute',
            'top': moveUp,
            'zIndex': 50,
            'left': leftx
        }).animate({
            top: -50,
            left: moveLeft
        }, 300)
    });
    

    Also note the use of the object provided to a single css() call over multiple calls to the same method.

    Solution 2:

    Replace these two lines:

    var topx = _this.offset().top;
    var leftx = _this.offset().left;
    

    with:

    var topx = _this.offsetTop;
    var leftx = _this.offsetLeft;
    

    As .offset() is a jquery function and _this is a DOM element.


    Also for your .css line you have to wrap _this in $(...) again because _this is a DOM element and **not a jQuery object.

    Post a Comment for "This.offset Is Not A Function Within A Click Function"