A better “Add to Cart” animation for Prestashop (Updated)

Let’s face it: Prestashop’s default “Add to cart” animation sucks a bit. In this tutorial, I’ll show you how to change it to something more appealing and useful.

Introduction

In this short tutorial we will add a fancy popup box that notifies the customer when a product is adedd to the cart. Something similar to the one I have in my Prestashop Addons store.

First of all, the shop must be configured to use ajax animation. This option is activated by default, but in case you disabled it, be sure it’s turned on by going to the back office, Modules -> Cart Block in Front office features, and set Ajax Cart to on.

Step 1 – Introduction to the Add to cart animation

Now that we’re sure ajax is on, let’s go to our root Prestashop folder, then modules/blockcart. The file where the evil code is stored is ajax-cart.js. As always, it’s not good practice to edit core files directly, as any update can destroy our changes, therefore copy ajax-cart.js in your theme’s folder, then js/modules/blockcart/. Create any necessary folder, of course. The structure is pretty much redundant, but needed by the system. We can now start editing our file.

What we’re interested in is the add function of th cart object. It’s located at about line 176. What we really want to mess with, anyway, is the actual animation, not the whole Add to Cart process. Therefore, we will be editing this piece of code only, from line 208 to 232:


	// add the picture to the cart
	var $element = $(callerElement).parent().parent().find('a.product_image img,a.product_img_link img');
	if (!$element.length)
		$element = $('#bigpic');
	var $picture = $element.clone();
	var pictureOffsetOriginal = $element.offset();

	if ($picture.size())
		$picture.css({'position': 'absolute', 'top': pictureOffsetOriginal.top, 'left': pictureOffsetOriginal.left});

	var pictureOffset = $picture.offset();
	if ($('#cart_block').offset().top && $('#cart_block').offset().left)
		var cartBlockOffset = $('#cart_block').offset();
	else
		var cartBlockOffset = $('#shopping_cart').offset();

	// Check if the block cart is activated for the animation
	if (cartBlockOffset != undefined && $picture.size())
	{
		$picture.appendTo('body');
		$picture.css({ 'position': 'absolute', 'top': $picture.css('top'), 'left': $picture.css('left'), 'z-index': 4242 })
		.animate({ 'width': $element.attr('width')*0.66, 'height': $element.attr('height')*0.66, 'opacity': 0.2, 'top': cartBlockOffset.top + 30, 'left': cartBlockOffset.left + 15 }, 1000)
		.fadeOut(100, function() {
			ajaxCart.updateCartInformation(jsonData, addedFromProductPage);
		});
	}
	else

We don’t want all this junk: get rid of everything, so that the ajax call’s success function looks like this:


success: function(jsonData,textStatus,jqXHR)
	{
		// add appliance to whishlist module
		if (whishlist && !jsonData.errors)
			WishlistAddProductCart(whishlist[0], idProduct, idCombination, whishlist[1]);
		ajaxCart.updateCartInformation(jsonData, addedFromProductPage);
	},

If you now refresh the page, you’ll notice the product is being added to the cart without animation. Already feels better!

Step 2 – Adding the floating box

Let’s add some valuable information to let our customers know they just added a product to the cart. We will first create the box with javascript, and in a second stage move some styling to the css file. Add the following just before ajaxCart.updateCartInformation(jsonData, addedFromProductPage);:

EDIT: There was a small mistake here, Marius pointed out in the comments: all of the following code MUST be enclosed within

if(!jsonData.errors)
{
}

Otherwise, the box will trigger even if customers add quantities exceeding products’ stocks! Thanks Marius!


				/* Creating the dark overlay */

				var overlay = $('<div></div>')
								.addClass('dark-overlay')
								.css({
									position: 'fixed',
									backgroundColor: 'black',
									'z-index': 99,
									display: 'none',
									opacity: .5,
									width: '100%',
									height: '100%',
									left: 0,
									top: 0
								});

				overlay.appendTo($('body')).fadeIn();

Explanation: basically, every time we now click on add to cart, a dark overlay will fade in the screen, preparing the field to give our popup more prominence. We also need to take it away once we are done though! Let’s add the following code after the previous one:

				$('.dark-overlay').click(function(){
					$(this).fadeOut(function(){
						$(this).remove()
					});
				})



And we can now toggle the dark overlay by clicking on it. Finally, let’s create our floating box:



				/* Creating the floating box */

				var floating_box = $('<div></div>')
									.addClass('add-to-cart-popup')
									.css({
										position: 'fixed',
										left: '50%',
										top: '30%',
										display: 'none',
										width: '450px',
										height: '160px',
										'margin-left': '-225px',
										backgroundColor : 'white',
										'z-index' : 100
									})

				floating_box.appendTo($('body')).fadeIn();

Explanation: We basically do what we did for the overlay, but with one difference: we want this box to have specific dimensions, and to be centered. To achieve this, we’ve got to add half on the width of the box as a negative left margin, while keeping the left positioning at 50%. This way, the box will be perfectly centered.

Step 3 – Populating the box

We have our not-so-informative box; it’s now time to make it useful. We’ve got a problem though! If we write our informative text inside the javascript file itself, it won’t be multilanguage by any mean. This is okay for single-language stores, but for all the others it will cause big troubles. How to deal with it? We will use a trick: we will add the translatable variables inside our template.

In your theme folder, navigate to modules/blockcart/blockcart.tpl and open it. If you can’t find that, because it’s not present, copy in this very same location the original one that you find in the module’s folder. At about line 35, there should be a javascript block with the following content:


<script type="text/javascript">
var customizationIdMessage = '{l s='Customization #' mod='blockcart' js=1}';
var removingLinkText = '{l s='remove this product from my cart' mod='blockcart' js=1}';
var freeShippingTranslation = '{l s='Free shipping!' mod='blockcart' js=1}';
var freeProductTranslation = '{l s='Free!' mod='blockcart' js=1}';
var delete_txt = '{l s='Delete' mod='blockcart' js=1}';
</script>

At the end of this, so right after delete_txt, add the following variables:


var added_txt = '{l s='Product added to the cart' mod='blockcart' js=1}';
var checkout_txt = '{l s='Proceed to checkout' mod='blockcart' js=1}';
var continue_txt = '{l s='Continue shopping' mod='blockcart' js=1}';

Now we can reference these in the javascript file. Basically, we assigned to those variables texts that change when the language changes, thus offering us a nice way to implement multiple languages in our box. Let’s deal with the actual box content. Go back to ajax.cart.js and add the following at the end of our last modifications, but before appending the floating box to the body:

				/* getting the checkout link */

				var checkout_link = $('#button_order_cart').attr('href');

				/* Populating the box */

				floating_box.append('<p>'+ added_txt+'</p>');
				floating_box.append('<a href="'+checkout_link+'" class="exclusive">'+ checkout_txt+'</a>');
				floating_box.append('<a class="close-popup button">'+ continue_txt+'</a>');



Then, after appending it


				$('.close-popup').click(function(){
					$(this).parent().fadeOut(function(){
						$(this).remove()
					});
					$('.dark-overlay').fadeOut(function(){
						$(this).remove()
					});
				})	

Explanation: First of all, we need to know where to direct users once they want to procees to the checkout. Instead of creating a new link, we can make use of the existing one in the cart. Therefore, we first assign that link to a variable (checkout_link).
Then, in this order, we append the text that informs an item has been added to the cart, the checkout link, and the link to continue shopping. This last one needs to close the current dialog, therefore, in the end we register its clicks: we remove both the dialog and the overlay.

As a last step in the javascript file, we need to amend the previous overlay click to be sure we also remove the new dialog:

				$('.dark-overlay').click(function(){
					$(this).fadeOut(function(){
						$(this).remove()
					});
					$('.add-to-cart-popup').fadeOut(function(){
						$(this).remove()
					});					
				})

And we are basically done with javascript. Test it out, you’ll notice it behaves as it should…but it looks ugly. In the next step, we will style it nicely to make it a bit more appealing.

Step 4 – Styling our new Add to cart dialog

First of all, since we added classes to our overlay and floating box, we can get rid of those javascript styling. We will override blockcart.css, therefore go to your module’s folder, blockcart/ and copy blockcart.css. reach your theme’s folder, then create this folder structure, if not present: css/modules/blockcart/. If that blockcart folder is already there, the stylesheet is likely to be found inside, and you can add to that directly. If not, paste in the one we just copied, and open it up in a code editor.

At the very end of the file, add the following:

/* Floating box modification */

.dark-overlay {
	position: fixed;
	background-color: black;
	z-index: 99;
	display: none;
	opacity: .5;
	width: 100%;
	height: 100%;
	left: 0;
	top: 0;
}

.add-to-cart-popup {
	position: fixed;
	left: 50%;
	top: 30%;
	display: none;
	width: 450px;
	height: 160px;
	margin-left: -225px;
	background-color : white;
	z-index : 100;
}

It’s just a copy/paste of those rules we previously applied. We can now remove them from the javascript, so that our previous objects now look like this:

/* this the overlay*/
	var overlay = $('<div>').addClass('dark-overlay');
/* And the box */
	var floating_box = $('<div>').addClass('add-to-cart-popup')

Refresh and check that it behaves as before.

Let’s now add a bit of spice to the box, by adding some other lines of css inside the popup’s class:

.add-to-cart-popup {
	position: fixed;
	left: 50%;
	top: 30%;
	display: none;
	width: 450px;
	height: 160px;
	margin-left: -225px;
	background-color : white;
	z-index : 100;
	border: 1px solid #f0f0f0;
	box-shadow:         0px 0px 10px rgba(50, 50, 50, 0.75);
	border-radius: 5px;
}

So, we’ve got some nice shadow and rounded corners, let’s space out those buttons, and give them some difference (we don’t want them to be the same, but rather the checkout one to be more prominent):


.add-to-cart-popup p {
	font-weight: bold;
	font-size: 18px;
	width: 100%;
	padding-top: 30px;
	text-align: center;
}

.add-to-cart-popup .exclusive {
	margin-left: 80px;
	margin-top: 20px;
}

.add-to-cart-popup .button {
	margin-left: 40px;
	color: #ccc;
	border: 1px solid black;
	background-image: -ms-linear-gradient(top, #404040 0%, #272727 100%);
	background-image: -moz-linear-gradient(top, #404040 0%, #272727 100%);
	background-image: -o-linear-gradient(top, #404040 0%, #272727 100%);
	background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #404040), color-stop(1, #272727));
	background-image: -webkit-linear-gradient(top, #404040 0%, #272727 100%);
	background-image: linear-gradient(to bottom, #404040 0%, #272727 100%);	

}

.add-to-cart-popup .button:hover {
	background:#272727;
}

And there it is! Of course, it can be even prettier, but this gives it a nice neutral style that can be further enhanced, and adapted to your needs. here is the final result:

Our new "add to cart" animation for Prestashop

Our new “add to cart” animation for Prestashop

You like the tuts and want to say "thank you"? Well, you can always feel free to donate:

  • Giovanna Mastrocola

    It works very well in 1.5..
    Greaaat, you just saved my ass!! Thank u so much Nemo

  • Rajeev Nair

    Hi Nemo,

    Can you tell me how to display a message ‘Not enough product in stock’ when quantities are exhausted. Slightly off-topic though, iam using 1.6.

    • NemoPS

      Weird, it should already do that by default, as that sentence is added to the json errors!

  • http://mdusamaansari.com/ Mohammed Usama

    Hi Fabio, Good day. I am into development of Prestashop module for collecting donations. How can I add custom amount to cart which can be donated to some charity.

  • Mick

    Thank you very much for this tutorial. I appreciate the step by step modifications. I will now try to add the product name and picture, but the biggest is already done thank to you!
    Regards

  • Zen

    I would like to know how to make the box (pop up disappear) after 1 or 2 sec just providing confirmation to customer product has been added to cart. I do not need button as my is daily need shop and would like customer to continue shopping

  • http://mecollectibles.com Ahmed

    Hello,
    The module seems to be very nice but I should say it is too complicated. I do not understand how to do it well as many before & after MODIFICATIONS in description while others who give modules out just say add this & that after or before a line & well understood.
    I am sorry but I do not know what the total way is due to many steps saying add but not clearly after what exactly.
    Best Regards,

  • javier

    I have a problem, everything goes perfect, but does not use css styles

    I see this error

    event.returnValue is deprecated. Please use the standard event.preventDefault () instead.

    Anyone know any solution?

  • Vivek

    Thank you very much for your tutorial.. Very nice article.. We would be very glad if you can also show how to show

    “Accessories” with a checkbox – so that customer can easily add accessories to cart and order.

    So please help us to achieve this. it will be very useful for many .

    Regards
    Vivek

  • Gary

    Great script thank you! Is there a way to add a small picture and description to the box? I have looked at a couple of the solutions mentioned but can’t seem to append them to the box.

  • zoom

    Wow ! Works great.

    Thanks a lot for sharing !

  • Hamadi

    Thanks , it is a good work,

    for me all work just the popup isn’t affiched, some suggetions please

  • Konrad

    Hmm.. im a little bit confused about this tutorial explanation…
    This should be shown like code “before” and code “after” all modifications in the tutorial summary at the end.

    Any ready made .js and .tpl .css files for this? Thanks in advance!

    PS 1.5.6

  • pascalVG

    Niyi,

    I noticed that the quotes you used for :

    floating_box.append(”+ added_txt+”);

    (i.e. 1 x double quote at the front (and the same at the back)) are not the same as the following two commands:

    floating_box.append(‘‘+ checkout_txt+’‘);
    floating_box.append(‘‘+ continue_txt+’‘);

    (2x a single quote at the front (and the same at the back)

    In the original code of Nemo,

    it was '' + added_txt+'' (Using all single quotes)

    So, change the first line to Nemo’s code as given in the tutorial

    Maybe that helps,
    pascal

    • pascalVG

      Oops, sorry, forgot to press REPLY at Niyi’s post… became a separate post now…

  • josias

    Superb!
    This is the most usefull tip I found for adapt my prestashop shop. My congratulations, and thank you very much!

  • Forevergrateful

    great!

  • Steno

    Hi nemo excellent guide!
    I have a problem, the css style does not work, they are not included!
    where am I wrong?
    thank you very much.

    • http://nemops.com Nemo

      Hi Steno!
      Well, it’s hard to tell what’s going on. Try adding the !important keyword for example, and see if it works. Also, check if you have any css override for blockcart.css if you’re adding rules to that file directly in the module’s directory!

  • http://www.freshsmoke.dk Davallen

    Hi,

    Looks really nice, I just wondered how it can be updated to have a checkbox which says “Do not show this message again” so it wont be annoying for returning customers who knows how it works ;-)

    Any help anyone?

  • http://distoko.com Ridwan

    Tried this, and works like a charm… Man, “Thank You” just isn’t enough to tell you my gratitude…
    Keep posting!

  • Niyi

    Thank you Nemo,
    I am only good with HTML and CSS and can only implement this tutorial if guided. I would howeve keep troubleshooting as best as I can. If you have any suggestion now or later, I would be glad to hear it.

  • Niyi

    Dear Nemo,

    I am ashamed I have to ask for help at this point. I use Prestashop 1.5.4.1.
    I have done everything you stated but I could only get the dark overlay to show and not the floating box and the content.
    The error throw up is this:

    ReferenceError: added_txt is not defined
    floating_box.append(”+ added_txt+”);

    I did everything as stated in the step 3 of the tutorial by editing blockcart.tpl file inside the theme folder like this:

    var delete_txt = ‘{l s=’Delete’ mod=’blockcart’ js=1}';
    var added_txt = ‘{l s=’Product added to the cart’ mod=’blockcart’ js=1}';
    var checkout_txt = ‘{l s=’Proceed to checkout’ mod=’blockcart’ js=1}';
    var continue_txt = ‘{l s=’Continue shopping’ mod=’blockcart’ js=1}';

    In the ajaxcart.js, I have made the following changes:

    success: function(jsonData,textStatus,jqXHR)
    {
    // add appliance to whishlist module
    if (whishlist && !jsonData.errors)
    WishlistAddProductCart(whishlist[0], idProduct, idCombination, whishlist[1]);
    if(!jsonData.errors)
    {
    /* Creating the dark overlay */
    var overlay = $(”).addClass(‘dark-overlay’);

    overlay.appendTo($(‘body’)).fadeIn();
    $(‘.dark-overlay’).click(function(){
    $(this).fadeOut(function(){
    $(this).remove()
    });
    })

    /* Creating the floating box */
    var floating_box = $(”).addClass(‘add-to-cart-popup’)

    /* getting the checkout link */
    var checkout_link = $(‘#button_order_cart’).attr(‘href’);

    /* Populating the box */
    floating_box.append(”+ added_txt+”);
    floating_box.append(‘‘+ checkout_txt+’‘);
    floating_box.append(‘‘+ continue_txt+’‘);

    floating_box.appendTo($(‘body’)).fadeIn();

    $(‘.close-popup’).click(function(){
    $(this).parent().fadeOut(function(){
    $(this).remove()
    });
    $(‘.dark-overlay’).fadeOut(function(){
    $(this).remove()
    });
    })

    $(‘.dark-overlay’).click(function(){
    $(this).fadeOut(function(){
    $(this).remove()
    });
    $(‘.add-to-cart-popup’).fadeOut(function(){
    $(this).remove()
    });
    })

    }
    ajaxCart.updateCartInformation(jsonData, addedFromProductPage);
    },

    Can you please give me any direction on what to check? Been running through these codes over and over since yesterday.

    Thank you for your help.

    • http://nemops.com Nemo

      Have you tried going to advanced parameters-> preferences and setting the compiling option to force compile?

      • Niyi

        Yes. Force compile is on and cache too is off. I have cleared my browser’s cache too repeatedly and I still keep getting the same error message. I tested on both Chrome and Firefox and the message is the same.

        • http://nemops.com Nemo

          Really weird, it must be something about using the jquery ready statement, for sure :)

Store Top Sales

You like the tuts and want to say "thank you"? Well, you can always feel free to donate: