jQuery
$('.add-to-cart2').on('click', function () {
var cart = $('.cart');
var imgtodrag = $(this).parent('.item').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');
setTimeout(function () {
cart.effect("shake", {
times: 2
}, 200);
}, 1500);
imgclone.animate({
'width': 0,
'height': 0
}, function () {
$(this).detach()
});
}
});
HTML
<li>
<div class="polaroid item">
<p>
<button class="add-to-cart2" type="button">
Add to cart
</button>
</p>
<img src="/img/rawr.png" alt="item">
</div>
</li>
Error
Uncaught TypeError: Cannot read property 'top' of undefined
Hey,
I found a tutorial on how to create a fly animation for items into the cart section, but at the moment I get a error that tells me the offset.top are undefined. I have tried to solve it and the reason this happens what I think is that it can't find the image so the variable "imgtodrag" does not have anything to drag.
I would be happy if someone could see the fault in the code! :)
element. using parents() or closest() will solve your problem. parents() will be a more optimal solution since in this case you can be pretty sure "this" does not refer to item var imgtodrag = $(this).closest('.item').find("img").eq(0); or var imgtodrag = $(this).parents('.item').find("img").eq(0); parents() is better
– wallop May 04 '15 at 11:22