A Better “Add to Cart” Animation for Prestashop

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 added 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 the 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);:


				/* 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>');

				$('.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 process 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

Looking for quality PrestaShop Web Hosting? Look no further than Arvixe Web Hosting!

Tags: , , | Posted under PrestaShop | RSS 2.0

Author Spotlight

Fabio Porta

Fabio Porta

Fabio has been involved in web development and design since 2005, when launched his first website at the age of 16. He’s now highly skilled in both client and server side development, along with design, and since August 2012 runs a successful website about PrestaShop tutorials and Prestashop Modules called Nemo’s Post Scriptum, at http://nemops.com

3 Comments on A Better “Add to Cart” Animation for Prestashop

  1. Rambabu says:

    HI

    It is not working with 1.5.6.2 latest version. In fact the line numbers and the functions you mentioned are varied in latest 1.5.62 version. is possible can you update ?

  2. Mauro says:

    Hello could you send me the files for this functionality?

Leave a Reply

Your email address will not be published. Required fields are marked *


9 + = 18

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>