CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

23 February, 2022

How to make Sidebar sticky in Magento 2

 Programing Coderfunda     February 23, 2022     Magento 2, MAGENTO TUTORIALS     No comments   

 

How to make Sidebar sticky in Magento 2

In today’s post, I will talk about how to make Sidebar sticky in Magento 2.

Sticky sidebar, just similar to a sticky header, the sidebar element will always be displayed in the viewport or will be displayed when several conditions are met. This can be considered as an ideal location to move the product options, add to cart button, or element which is important for your product.

As a result, your customer can freely browse all your product’s content, as well as the add to cart button, which is always ready to be clicked on once the purchase decision has been made.

Before making any changes in the code to the activate sticky sidebar, you need to create a custom theme. In here, I named it as Mageplaza/StickySidebar.

5 Steps to make Sidebar sticky in Magento 2:

  • Step 1: Change LESS code
  • Step 2: Change XML code
  • Step 3: Change PHTML code
  • Step 4: Change RequireJS code
  • Step 5: Change jQuery code

Step 1: Change LESS code

You can make changes in this code by going to app/design/frontend/Mageplaza/StickySidebar/web/css/source/ and create _extend.less file inside it. Then copy/paste the below code:

.media-width(@extremum, @break) when (@extremum = 'min') and (@break = @screen__m) {
  .box-tocart .action.tocart {
    width: 100%;
    margin-right: 0;
  }
 
  .sidebar {
    &.fixed {
      position: fixed;
    }
  }
}

To symlink and compile this code, remember to run Grunt commands. On the desktop, the sidebar will be position as a fixed element and the add to cart button is made full width.

Step 2: Change Change XML code

Inside of app/design/frontend/Mageplaza/StickySidebar/Magento_Catalog/layout/, you can create catalog_product_view.xml. Then copy/paste the below snippet:

<page layout="2columns-right" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceBlock remove="true" name="catalog.compare.sidebar" />
    <referenceBlock remove="true" name="wishlist_sidebar" />
 
    <move element="product.info" destination="sidebar.additional" />
 
    <referenceContainer name="sidebar.additional">
        <block class="Magento\Framework\View\Element\Template"
               name="sticky.sidebar.wrapper"
               template="Magento_Catalog::sticky-sidebar-js.phtml"
               after="-" />
    </referenceContainer>
</page>

Using the above snippet, you can:

  • Change the number of columns in the page layout from one to two which the sidebar on the right side.
  • Remove the compare and the wishlist block when the layout of this page is being used.
  • Change block’s position which contains product options and adds to cart button to the sidebar
  • Add template file which will be used to invoke the AMD component for handling the sticky sidebar logic and calculation

Step 3: Change PHTML code

You can create sticky-sidebar-js.phtml in app/design/frontend/Mageplaza/StickySidebar/Magento_Catalog/templates/. The following snippet need to be copied/pasted:

<script type="text/javascript" data-mage-init='{"stickySidebar":{}}'></script>

Step 4: Change RequireJS code

Inside of app/design/frontend/Mageplaza/StickySidebar/, you can create requirejs-config.js. Then copy/paste the below snippet:

var config = {
    map: {
        "*": {
            stickySidebar: "js/sticky-sidebar",
        }
    }
};

Step 5: Change jQuery code

Inside of ` app/design/frontend/Mageplaza/StickySidebar/web/js/sticky-sidebar.js, you can create sticky-sidebar.js`. Then copy/paste the below snippet:

define(["jquery", "matchMedia", "domReady!"], function ($, mediaCheck) {
    "use strict";
 
    var sidebar = {};
    var a2c = $(".product-add-form");
    var a2c_mobile_target = $(".product-info-main > .price-box");
    // nodes required to calculate sidebar params: width, left, padding-left
    var page_main = $(".page-main");
    var page_main_w;
    var main = $(".main");
    var main_w;
    // nodes required to calculate sidebar params: top
    var header = $(".page-header");
    var nav = $(".nav-sections");
    var breadcrumbs = $(".breadcrumbs");
    // luma specific css values
    var a2c_mb = parseInt($("#product-addtocart-button").css("margin-bottom"));
    var main_pb = parseInt(main.css("padding-bottom"));
    var tabs_mb = parseInt($(".product.info.detailed").css("margin-bottom"));
 
    sidebar.el = $(".sidebar");
    sidebar.padding_ratio = parseFloat(sidebar.el.css("padding-left")) / page_main.width();
    sidebar.updateHorizontalParams = function () {
        if (sidebar.el.hasClass("fixed")) {
            page_main_w = parseFloat(page_main.width());
            main_w = parseFloat(main.width());
 
            sidebar.width = page_main_w - main_w;
            sidebar.left = ($(window).width() - page_main_w) / 2 + main_w;
            sidebar.p_left = parseInt(page_main_w * sidebar.padding_ratio);
 
            sidebar.el.css({
                "width": sidebar.width + "px",
                "left": sidebar.left + "px",
                "padding-left": sidebar.p_left + "px"
            });
        }
    };
    sidebar.updateVerticalParams = function () {
        sidebar.height = sidebar.el.height();
 
        var scrolled_from_top = $(window).scrollTop();
        var header_h = header.outerHeight(true) || 0;
        var nav_h = nav.outerHeight(true) || 0;
        var breadcrumbs_h = breadcrumbs.outerHeight(true) || 0;
        var content_h = main.outerHeight(true) || 0;
        var sidebar_limit_top = header_h + nav_h + breadcrumbs_h;
        var sidebar_limit_bottom = sidebar_limit_top + content_h;
        var sidebar_limit_bottom_criteria = scrolled_from_top + sidebar.height + main_pb + a2c_mb - tabs_mb;
 
        if (sidebar_limit_bottom < sidebar_limit_bottom_criteria) {
            // sidebar should start drifting out of viewport on the top
            sidebar.top = sidebar_limit_bottom - sidebar_limit_bottom_criteria;
 
            sidebar.el.css({"top": sidebar.top + "px"});
        } else if (scrolled_from_top > sidebar_limit_top) {
            // header and breadcrumbs are now above viewport
            if (!sidebar.el.hasClass("fixed")) {
                sidebar.el.addClass("fixed");
                sidebar.updateHorizontalParams();
            }
            sidebar.top = 0;
 
            sidebar.el.css({"top": sidebar.top + "px"});
        } else {
            sidebar.el.removeClass("fixed").removeAttr("style");
        }
    };
 
    var onResize = function () {
        $(window).on("resize", function () {
            sidebar.updateHorizontalParams();
        });
    }, onScroll = function () {
        $(window).on("scroll", function () {
            sidebar.updateVerticalParams();
        });
    }, onInit = function () {
        mediaCheck({
            media: "(min-width: 768px)",
            entry: function () {
                sidebar.el
                    .addClass("fixed")
                    .prepend(a2c.detach());
 
                sidebar.updateHorizontalParams();
                sidebar.updateVerticalParams();
 
                onResize();
                onScroll();
            },
            exit: function () {
                a2c.detach().insertAfter(a2c_mobile_target);
 
                sidebar.el
                    .removeClass("fixed")
                    .removeAttr("style");
            }
        });
    };
 
    onInit();

Following are some information about this code

  • The logic is initialized using the onInit() method
  • The product options positions can be change between mobile and desktop layout by utilizing the matchMedia library. Besides, you can also add/remove a CSS class named fixed using this matchMedia library.
  • On the desktop, the values of four CSS properties and load event listeners will be calculated by JS.
  • The sidebar display can be divided into three states:
    • State 1: The sidebar is positioned relatively as long as breadcrumbs are in visible in the viewport.
    • State 2: The sidebar is positioned as a fixed element and will be remained in the viewport when breadcrumbs are scrolled outside of the viewport.

How to make Sidebar sticky

  • State 3: The sidebar will slide outside of viewport once the sidebar bottom side is aligned with the content bottom side.

How to make Sidebar sticky

The above code has been optimized in order to work well with Luma theme, therefore some of the code stated here might have to be added or cleaned up.

Conclusion

In conclusion, the sticky sidebar is a useful element which could help you improve your conversion rate. I hope through the above information; you will be able to make Sidebar sticky with ease. If you have any questions about this topic or face any issues while following this tutorial, feel free to let me know. Thanks for reading!


  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • How to add a custom Zipcode validator in checkout page Magento 2 How to add a custom Zipcode validator in checkout page Magento 2In Magento 2, it’s not difficult to customize zip code validation and or add a c… Read More
  • Magento 2 Module Development - Simple Hello World Module Magento 2 Module development or Magento 2 Hello World trends is increase rapidly while Magento release official version. That why… Read More
  • How to Create Controller in Magento 2 Controller specially is one of the important thing in Module development series, and PHP MVC Framework in general. It functionarity is… Read More
  • CRUD Models in Magento 2 Magento 2 get collection can manage data in database easily, you don’t need to write many line of code to create a CRUDCRUD Models in Magento 2&… Read More
  • Magento 2 Create View: Block, Layouts, Templates Magento 2 Create View: Block, Layouts, TemplatesIn this topic Magento 2 Create: Block, Layouts, Templates we will learn about Vie… Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Vue3 :style backgroundImage not working with require
    I'm trying to migrate a Vue 2 project to Vue 3. In Vue 2 I used v-bind style as follow: In Vue 3 this doesn't work... I tried a...
  • SQL ORDER BY Keyword
      The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts ...
  • Enabling authentication in swagger
    I created a asp.net core empty project running on .net6. I am coming across an issue when I am trying to enable authentication in swagger. S...
  • failed to load storage framework cache laravel excel
       User the export file and controller function  ..         libxml_use_internal_errors ( true ); ..Good To Go   public function view () : ...
  • AdminJS not overriding default dashboard with custom React component
    So, I just started with adminjs and have been trying to override the default dashboard with my own custom component. I read the documentatio...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh - 9/21/2024
  • pyspark XPath Query Returns Lists Omitting Missing Values Instead of Including None - 9/20/2024
  • SQL REPL from within Python/Sqlalchemy/Psychopg2 - 9/20/2024
  • MySql Explain with Tobias Petry - 9/20/2024
  • How to combine information from different devices into one common abstract virtual disk? [closed] - 9/20/2024

Laravel News

  • Efficiently remove expired cache data with Laravel Cache Evict - 6/3/2025
  • Test Job Failures Precisely with Laravel's assertFailedWith Method - 5/31/2025
  • Prism Relay - 6/2/2025
  • Enhance Collection Validation with containsOneItem() Closure Support - 5/31/2025
  • Filament Is Now Running Natively on Mobile - 5/31/2025

Copyright © 2025 CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda