frenchbaguette
frenchbaguette

Reputation: 1339

Cannot read property 'top' of undefined jQuery

Can someone help me to fix the code so that this script would work?

This is my html:

        <div class="img-wrapper item">
            <a href="/product/{{$product->id}}/{{$product->slug}}">
                <a class="thumbnail" href="/product/{{$product->id}}/{{$product->slug}}" style="margin-bottom: 0px; border: none;"> 
                <img class="media-object indexImg" src="{{$product->image}}">
                </a>
            </a>
            <div class="tags">
            @if($product->discount > 0)
                <span class="label-tags"><span class="label label-danger">Išpardavimas</span></span>
            @endif    
                <span class="label-tags"><span class="label label-info">Nauja</span></span>
            </div>
            <div class="option">
                <button class="add-to-cart" type="button">Add to cart</button>
            </div>
        </div>

This is script:

$('.add-to-cart').on('click', function () {
        var cart = $('.shopping-cart');
        var imgtodrag = $(this).parent('.img-wrapper').find("img").eq(0);
        if (imgtodrag) {
            var imgclone = imgtodrag.clone()
                .offset({
                top: imgtodrag.offset().top,
                left: imgtodrag.offset().left
            })
                .css({
                'opacity': '0.5',
                    'position': 'absolute',
                    'height': '150px',
                    'width': '150px',
                    'z-index': '100'
            })
                .appendTo($('body'))
                .animate({
                'top': cart.offset().top + 10,
                    'left': cart.offset().left + 10,
                    'width': 75,
                    'height': 75
            }, 1000, 'easeInOutExpo');
    });

It works with the example so the script is good. I just need correctly fill this line:

var imgtodrag = $(this).parent('.img-wrapper').find("img").eq(0);

Upvotes: 1

Views: 114

Answers (1)

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10366

Your problem is because .img-wrapper is not a direct parent, but a "grandfather". With closest, you get the closest ascendent, which is the element you want in this case. Try this:

var imgtodrag = $(this).closest('.img-wrapper').find("img").first();

Upvotes: 1

Related Questions