Add Sticky Cart Footer Magento 2

Today I will show you how to add sticky cart footer Magento 2. This will help your customers add products to the cart more easily. You can do this through a few steps.

 

Step 1:

Create Stickycart.php under /app/code/Magepow/Custom/Block/Product/

 

File: /app/code/Magepow/Custom/Block/Product/Stickycart.php

<?php

namespace Magepow\Custom\Block\Product;

use Magento\Framework\View\Element\Template;

class Stickycart extends Template
{
    protected $_registry;

    protected $stockRegistry;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
        array $data = []
    ) {
        $this->_registry = $registry;
        $this->stockRegistry = $stockRegistry;
        parent::__construct($context, $data);
    }


    public function getCurrentProduct()
    {        
        return $this->_registry->registry('current_product');
    }

    public function getStockItem($productId)
    {
        return $this->stockRegistry->getStockItem($productId);
    } 
}


Step 2:

Create catalog_product_view.xml under /app/code/Magepow/Custom/view/frontend/layout/

 

File: /app/code/Magepow/Custom/view/frontend/layout/catalog_product_view.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="before.body.end">
            <block class="Magepow\Custom\Block\Product\Stickycart"  name="stickycart"
                   template="Magepow_Custom::stickycart.phtml" group="detailed_info">
            </block>
        </referenceBlock>
    </body>
</page>

Step 3:

Create stickycart.phtml under /app/code/Magepow/Custom/view/frontend/templates/

 

File: /app/code/Magepow/Custom/view/frontend/templates/stickycart.phtml

<?php

  $helper = $this->helper('Magepow\Custom\Helper\Data');
  $heightScroll = $helper->getHeightScroll();
  $currentProduct = $block->getCurrentProduct();
  $id = $currentProduct->getId();
  $_productStock = $block->getStockItem($id);
  $timer = $helper->getTimer($currentProduct);
  $imageUrl = $this->helper('Magento\Catalog\Helper\Image')
                    ->init($currentProduct, 'product_base_image')
                    ->constrainOnly(TRUE)
                    ->keepAspectRatio(TRUE)
                    ->keepTransparency(TRUE)
                    ->keepFrame(FALSE)
                    ->resize(80, 80)->getUrl();
?>
<?php if($_productStock->getIsInStock()): ?>
  <div class="stickyCart">
    <div class="stickyChild">
    <div class="contentHide">
    <div class="clSticky" id="timerSticky">
      <?php if($timer): ?>
      <?php echo $timer; ?>
      <?php else: ?>
      <div class="stickyProductName"><?php echo $block->escapeHtml(__($currentProduct->getName())) ?></div>
      <?php endif; ?>
      </div>
    </div>
    <div class="contentHide">
    <div class="clSticky"><div class="imgBorder"><div class="stickyImg" style="background-image: url(<?php echo $imageUrl ?>);"></div></div></div></div>
    <div class="contentHide">
    <div class="clSticky" id="parentQtySticky">
      <?php if ($currentProduct->getTypeId() == 'grouped'): ?>
      <div class="field qty">
        <div class="product-qty">
        <div class="control custom-qty">
          <input type="number"
               name="qty"
               id="qtyGrouped"
               maxlength="12"
               value="1"
               title="<?php /* @escapeNotVerified */ echo __('Qty') ?>" class="input-text qty"
               />
           <div class="btn-plus">
              <button  type="button" class="increase items" onclick="var result = document.getElementById('qtyGrouped'); var qtyGrouped = result.value; if( !isNaN( qtyGrouped )) result.value++;return false;">
            <i class="fa fa-angle-up"></i>
          </button> 
           <button  type="button" class="reduced items" onclick="var result = document.getElementById('qtyGrouped'); var qtyGrouped = result.value; if( !isNaN( qtyGrouped ) && qtyGrouped > 1 ) result.value--;return false;">
              <i class="fa fa-angle-down"></i>
          </button>  
          </div>  
        </div>
      </div>
        </div>
      <?php else: ?>
        <div class="field qty">
        <div class="product-qty">
        <div class="control custom-qty">
          <input type="number"
               name="qty"
               id="qtySticky"
               maxlength="12"
               value="1"
               title="<?php /* @escapeNotVerified */ echo __('Qty') ?>" class="input-text qty"
               />
          <div class="btn-plus">
            <button  type="button" class="increase items" onclick="var result = document.getElementById('qtySticky'); var qtySticky = result.value; if( !isNaN( qtySticky )) result.value++;return false;">
              <i class="fa fa-angle-up"></i>
            </button>
            <button  type="button" class="reduced items" onclick="var result = document.getElementById('qtySticky'); var qtySticky = result.value; if( !isNaN( qtySticky ) && qtySticky > 1 ) result.value--;return false;">
              <i class="fa fa-angle-down"></i>
            </button>  
          </div>  
        </div>
      </div>
        </div>
        <?php endif; ?>
      </div>
    </div>
    <?php if ($currentProduct->getTypeId() == 'bundle'): ?>
    <div class="contentHide contentShow"><div class="clSticky"><button class="btn-cart-bottom btnCustom">Customize</button></div></div>
      <?php else: ?>
    <div class="contentHide contentShow"><div class="clSticky"><button id="btnSticky" class="btn-cart-bottom">Add To Cart</button>
    </div></div>
  <?php endif; ?>
  </div>
  </div>
<?php endif; ?>
<?php
$formData = [
    'stickyCart'                =>  '.stickyCart',
    'qtySticky'                 =>    '#qtySticky',
    'btnCustom'                 =>  '#btnCustom',
    'quantity'                  =>  '.quantity',
    'qtyGrouped'                =>  '#qtyGrouped',
    'btnSticky'                 =>  '#btnSticky'
];
$stickyData = $this->helper('Magento\Framework\Json\Helper\Data')->jsonEncode($formData);
?>
<script type="text/x-magento-init">
    {
        "*": {
            "magepowStickycart": {
            "jsonData":<?php /* @noEscape */ echo $stickyData; ?>,
            "ScrollHeight": <?php   echo $heightScroll; ?>
            }
        }
    }
</script>

Step 4:

Create requirejs-config.js under /app/code/Magepow/Custom/view/frontend/

 

File: /app/code/Magepow/Custom/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            magepowStickycart: 'Magepow_Custom/js/stickycart'
        }
    }
};

Step 5:

Create stickycart.js under /app/code/Magepow/Custom/view/frontend/web/js

 

File: /app/code/Magepow/Custom/view/frontend/web/js/stickycart.js

define([
  "jquery",
  "jquery/ui",
  ], function ($) {
    'use strict';
    $.widget('mage.magepowStickycart', {
        options: {
            ScrollHeight:0
        },
      _create: function () {
        var options = this.options;

        if ($('body').hasClass('cookie-message'))
          $('body').removeClass('cookie-message')

        $(document).scroll(function() {
          var y = $(this).scrollTop();
          if (y > options.ScrollHeight) {
            $(".stickyCart").fadeIn("fast");

            $('body').addClass('show-add-cart-bottom')
          } else {
            $(".stickyCart").fadeOut("fast");

            if ($('body').hasClass('show-add-cart-bottom')){
              $('body').removeClass('show-add-cart-bottom')
            }
          }
        });

        $('#qtySticky').change(function(){
          $('#qty').val(this.value);
        });
        $('#qty').change(function(){
          $('#qtySticky').val(this.value);
        });

        $('#qtyGrouped').change(function(){
          $('form .data.grouped tr:first-child .qty').val(this.value);
        });

        $( "input[type='number']" ).change(function() {
          $('#qtyGrouped').val(this.value);
        });

        $('#btnSticky').click(function() {
          var $this = $(this)
          $this.attr("disabled", "disabled");
          setTimeout(function() {
            $this.removeAttr("disabled");
          }, 1500);
            $('#product-addtocart-button').click();
        });

        var clicks = 0;
        $('.btnCustom').click(function() {
          if (clicks == 0){
              $('#bundle-slide').click(); 
              $(this).text("Add To Cart");
              } else{
              $('#product-addtocart-button').click();
            }
          ++clicks;
        });


        $('.custom-qty').each(function() {
          var spinner = $(this),
          input = spinner.find('input[type="number"]'),
          btnUp = spinner.find('.increase'),
          btnDown = spinner.find('.reduced');
          btnUp.click(function() {
            spinner.find("input").trigger("change");
          });

          btnDown.click(function() {
            spinner.find("input").trigger("change");
          });
        });
      }
    });
  return $.mage.magepowStickycart;
});

Step 6:

Now install the custom module and refresh Magento cache

 

php bin/magento setup:upgrade

php bin/magento setup:di:compile

php bin/magento cache:flush

 

Done. Hope this article will help you in some way.