Magento – Open header cart when product added to cart

cartjavascriptmagento-1.7mini-carttemplate

I'd like to know how I can automatically open the header mini cart when a product is added to the shopping cart.

At present if you add a product to the cart the default Magento message appears which is fine but I would also like the header cart to expand to show more details.

Cart expanded on hover

The header cart has a hover action and the code looks like this

<div class="block-cart header-cart pull-right" id="ajaxcart">

I just need to know how to trigger it when an item is added to the cart and if possible how to close it again within perhaps 15 seconds of it opening.

Thanks

Update

I've added this code to my templates header file

<?php if (Mage::getSingleton('checkout/session')->getCartWasUpdated()) {

echo '<script>';
echo 'jQuery(document).ready(function(){';
echo 'cart_autoopen();';
echo '});';

echo 'function cart_autoopen(){';
echo '$(\'.add-to-cart\').click(function(){';
echo '$(\'.header-cart\').trigger(\'click\'); // this will open the cart if it was already closed';
echo 'setTimeout(function(){$(\'.header-cart\').trigger(\'click\');},15000);   // this will close the cart after 15 seconds. ';
echo '});';
echo '}';
echo"</script>";

};

?>

At the moment it isn't working but I think this is because the javascript is using a click trigger instead of mouse over.
If someone cleverer than I am edit my code so that it triggers an onmouseover instead I think this could work.

Best Answer

The cart controller sets a flag in the checkout session after you have added a product to the cart, with setCartWasUpdated(true).

You can check this flag in your template and either change the CSS classes accordingly or trigger a click on the mini cart using JavaScript, if the flag is set:

if (Mage::getSingleton('checkout/session')->getCartWasUpdated()) {
    // open mini cart
}
Related Topic