Start building

Guides

A sticky add to cart bar for Shopify, without an app

The version you'll find in most snippets buys the wrong variant sooner or later. The fix is to stop building a second cart and press the theme's real button.

The Klorr teamUpdated 8 min read

  • Product page
  • Add to cart
  • JavaScript
  • No app

Key takeaways

  • Submit the theme's own product form with requestSubmit. Variant, quantity, subscription plan and custom fields all come along, and the theme's cart drawer opens as usual.
  • Show the bar only once the real button has scrolled above the screen, using an IntersectionObserver, so the bar and the button are never on screen together.
  • Read the variant from the form's name="id" input. Dawn dispatches a change event on it, but other themes may differ, so test yours.
  • Pick the form with care. Dawn's product section has a second /cart/add form for installments, and that one has no submit button.

Here's the common version, more or less as it gets pasted into themes. It looks fine in a quick test. Read it for what it does when a shopper picks a color:

markup.html
<!-- The version to avoid -->
<div id="sticky" style="display:none;position:fixed;bottom:0">
  <button onclick="addIt()">Add to cart</button>
</div>
<script>
  window.addEventListener('scroll', function () {
    document.getElementById('sticky').style.display = window.scrollY > 600 ? 'block' : 'none';
  });
  function addIt() {
    fetch('/cart/add.js', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id: FIRST_VARIANT_ID, quantity: 1 })
    });
  }
</script>

What's wrong with it, and what changes

Problem in the common versionWhat the shopper getsThis post's section
Adds a fixed variantSelects Large, gets SmallSubmits the real form, so the selection is whatever the page shows
Sends only id and quantityLoses the subscription plan, engraving text, gift note and chosen quantityAll of those are fields in the form, so they travel with it
Its own fetch, with nothing after itCart drawer doesn't open, count doesn't change, no sign anything happenedThe theme's own submit handler runs
scrollY > 600Bar covers the buy button on a long gallery, or appears late on a short pageWatches the actual button
Hard-coded /cart/add.jsIgnores the language prefix on a translated storeUses the form's own action
Runs on every scroll eventExtra work on the main thread during scrollingIntersectionObserver fires only when visibility changes

The complete section

Add it to your product template below the main product section, following how to add a custom section. It has no effect until the shopper scrolls past the buy button.

sections/sticky-add-to-cart.liquid
{%- if product -%}
  {%- assign current = product.selected_or_first_available_variant -%}
  <sticky-atc
    class="satc-{{ section.id }}"
    role="region"
    aria-label="{{ section.settings.region_label | escape }}"
    data-section="{{ section.id }}"
    data-add="{{ section.settings.add_label | escape }}"
    data-soldout="{{ section.settings.soldout_label | escape }}"
    data-unavailable="{{ section.settings.unavailable_label | escape }}"
    hidden
  >
    {%- if product.featured_image -%}
      {{ product.featured_image | image_url: width: 112 | image_tag: width: 56, height: 56, loading: 'lazy', alt: '', class: 'satc-img' }}
    {%- endif -%}
    <div class="satc-info">
      <p class="satc-title">{{ product.title | escape }}</p>
      <p class="satc-meta">
        {%- unless product.has_only_default_variant -%}
          <span data-variant-title>{{ current.title | escape }}</span>
          <span aria-hidden="true"> · </span>
        {%- endunless -%}
        <span data-price>{{ current.price | money }}</span>
      </p>
    </div>
    <button type="button" class="satc-button" data-add-button>{{ section.settings.add_label | escape }}</button>
    <script type="application/json" data-variants>
      [
        {%- for variant in product.variants -%}
          { "id": {{ variant.id }}, "title": {{ variant.title | json }}, "price": {{ variant.price | money | json }}, "available": {{ variant.available | json }} }{% unless forloop.last %},{% endunless %}
        {%- endfor -%}
      ]
    </script>
  </sticky-atc>
{%- endif -%}

<style>
  .satc-{{ section.id }} {
    position: fixed;
    right: 0;
    bottom: 0;
    left: 0;
    /* Above page content, below cart drawers and modals. */
    z-index: 20;
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 10px 16px calc(10px + env(safe-area-inset-bottom));
    background: {{ section.settings.background }};
    color: {{ section.settings.ink }};
    box-shadow: 0 -2px 12px rgba(0, 0, 0, .12);
  }
  .satc-{{ section.id }}[hidden] { display: none; }
  .satc-{{ section.id }} .satc-img { flex-shrink: 0; width: 56px; height: 56px; border-radius: 6px; object-fit: cover; }
  .satc-{{ section.id }} .satc-info { flex: 1; min-width: 0; }
  .satc-{{ section.id }} .satc-title,
  .satc-{{ section.id }} .satc-meta { margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .satc-{{ section.id }} .satc-title { font-weight: 600; }
  .satc-{{ section.id }} .satc-meta { font-size: 14px; }
  .satc-{{ section.id }} .satc-button {
    flex-shrink: 0;
    min-height: 44px;
    padding: 0 20px;
    border: 0;
    border-radius: 6px;
    background: {{ section.settings.button }};
    color: {{ section.settings.button_ink }};
    font: inherit;
    font-weight: 600;
    cursor: pointer;
  }
  .satc-{{ section.id }} .satc-button:disabled { opacity: .5; cursor: not-allowed; }
  .satc-{{ section.id }} .satc-button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
  @media (max-width: 480px) {
    .satc-{{ section.id }} .satc-img { display: none; }
  }
  @media (prefers-reduced-motion: no-preference) {
    .satc-{{ section.id }}:not([hidden]) { animation: satc-rise .25s ease-out; }
  }
  @keyframes satc-rise {
    from { transform: translateY(100%); }
  }
</style>

<script>
  if (!customElements.get('sticky-atc')) {
    customElements.define('sticky-atc', class extends HTMLElement {
      connectedCallback() {
        var self = this;
        this.variants = JSON.parse(this.querySelector('[data-variants]').textContent);
        this.addButton = this.querySelector('[data-add-button]');
        this.addButton.addEventListener('click', function () { self.add(); });
        // Wait a moment: some themes update the id input just after the option changes.
        this.onChange = function () { setTimeout(function () { self.sync(); }, 60); };
        document.addEventListener('change', this.onChange);
        // In the theme editor, show the bar while its section is selected.
        this.onSelect = function (event) {
          if (event.detail.sectionId === self.dataset.section) self.show(true);
        };
        document.addEventListener('shopify:section:select', this.onSelect);
        this.sync();
      }
      disconnectedCallback() {
        document.removeEventListener('change', this.onChange);
        document.removeEventListener('shopify:section:select', this.onSelect);
        if (this.observer) this.observer.disconnect();
        document.body.style.paddingBottom = '';
      }
      // The form that sells this product: right variant id AND a real submit button.
      // Dawn also has an installments form with a cart action and no submit button.
      findForm() {
        var ids = this.variants.map(function (v) { return String(v.id); });
        var forms = document.querySelectorAll('form[action*="/cart/add"]');
        for (var i = 0; i < forms.length; i++) {
          var input = forms[i].querySelector('[name="id"]');
          if (input && forms[i].querySelector('[type="submit"]') && ids.indexOf(input.value) > -1) return forms[i];
        }
        return null;
      }
      attach() {
        var self = this;
        this.form = this.findForm();
        if (this.observer) this.observer.disconnect();
        if (!this.form) return;
        this.observer = new IntersectionObserver(function (entries) {
          var entry = entries[0];
          self.show(!entry.isIntersecting && entry.boundingClientRect.top < 0);
        });
        this.observer.observe(this.form.querySelector('[type="submit"]'));
      }
      sync() {
        if (!this.form || !this.form.isConnected) this.attach();
        if (!this.form) return;
        var id = this.form.querySelector('[name="id"]').value;
        var variant = this.variants.find(function (v) { return String(v.id) === id; });
        var main = this.form.querySelector('[type="submit"]');
        var label = this.dataset.add;
        if (!variant) label = this.dataset.unavailable;
        else if (!variant.available) label = this.dataset.soldout;
        this.addButton.textContent = label;
        this.addButton.disabled = !variant || !variant.available || main.disabled;
        if (variant) {
          var title = this.querySelector('[data-variant-title]');
          if (title) title.textContent = variant.title;
          this.querySelector('[data-price]').textContent = variant.price;
        }
      }
      show(on) {
        this.hidden = !on;
        document.body.style.paddingBottom = on ? this.offsetHeight + 'px' : '';
      }
      add() {
        if (!this.form) return;
        // A required engraving field, say: take the shopper back up to it.
        if (!this.form.checkValidity()) {
          this.form.scrollIntoView({ block: 'center' });
          this.form.reportValidity();
          return;
        }
        this.form.requestSubmit(this.form.querySelector('[type="submit"]'));
      }
    });
  }
</script>

{% schema %}
{
  "name": "Sticky add to cart",
  "tag": "aside",
  "limit": 1,
  "enabled_on": { "templates": ["product"] },
  "settings": [
    { "type": "text", "id": "add_label", "label": "Button", "default": "Add to cart" },
    { "type": "text", "id": "soldout_label", "label": "Sold out", "default": "Sold out" },
    { "type": "text", "id": "unavailable_label", "label": "No such combination", "default": "Unavailable" },
    { "type": "text", "id": "region_label", "label": "Label for screen readers", "default": "Quick add to cart" },
    { "type": "color", "id": "background", "label": "Background", "default": "#ffffff" },
    { "type": "color", "id": "ink", "label": "Text", "default": "#1a1a1a" },
    { "type": "color", "id": "button", "label": "Button", "default": "#1a1a1a" },
    { "type": "color", "id": "button_ink", "label": "Button text", "default": "#ffffff" }
  ],
  "presets": [ { "name": "Sticky add to cart" } ]
}
{% endschema %}

Why it presses the real button

form.requestSubmit(button) behaves as if the shopper clicked that button: it fires a submit event the theme can catch and includes the button's own name in the data. In Dawn, a product-form element listens for that event, posts the form data through fetch, and opens the cart drawer or notification. A plain form.submit() skips the event, so the theme's handler never runs and the shopper is sent to the cart page instead. If a theme has no handler, requestSubmit falls back to the normal form post, which also works.

All the fields come along because they're in the form or linked to it with a form attribute: id, quantity, selling_plan, gift card recipient fields and line item properties. You don't have to know which of them this store uses. That's the reason to prefer this over a separate cart call, and it means the bar can't drift out of line when an app adds a field later.

Finding the right form

A product page can hold several forms posting to /cart/add, and grabbing the first one is a real bug. Dawn's main product section renders a separate form for the installments text, and it has an id input and no submit button. Recommendation sliders and quick-add cards contain more, for other products. So findForm() requires both a submit button and a variant id belonging to this product. The action check uses *= because Shopify prefixes URLs on translated stores, such as /es/cart/add.

Keeping the variant in step

The section doesn't work out the variant from the option pickers. It reads the same name="id" input the form will send. Dawn sets that input and dispatches a bubbling change event on it, so the section listens on the document. Most other themes also fire change on the option inputs, and the 60ms wait lets the theme finish first.

This is the one part that depends on your theme. Some headless-style or heavily custom themes rebuild the buy box without any change event. To check, select a variant and see whether the bar's title follows. If it doesn't, the purchase is still correct, because the form sends the right id: only the label is stale. To fix it, find what your theme fires (search its JavaScript for variant) and listen for that as well. If the theme replaces the whole form on variant change, sync catches it with isConnected and attaches to the new one.

Staying out of the way

  • Because the bar shows only when the real button is above the screen, the bar can't cover Add to cart or the dynamic checkout button under it. The condition boundingClientRect.top < 0 matters: without it, the bar would also appear before the shopper reaches the button, when a long gallery pushes it below the screen.
  • z-index: 20 is deliberately modest, so the bar stays below cart drawers and modals. Check it against your theme, since a bar of 999999 sits on top of the drawer's checkout button. If yours overlaps, lower it.
  • The section adds matching padding-bottom to the body while it shows, so the footer's last lines can still be reached.
  • env(safe-area-inset-bottom) keeps the button clear of the home indicator, on themes whose viewport tag allows it.
  • Most chat widgets sit bottom right, where this button goes. Move the widget up in its own settings, or check for an option to hide it on product pages.
  • A cookie banner at the bottom will stack with the bar. Check that the banner's buttons stay reachable.

Test list

  1. On a phone, scroll past the button. The bar appears. Scroll back. It leaves at the moment the real button is on screen.
  2. Choose a different size, scroll down, and press the bar's button. Check the cart line is that size.
  3. Set quantity to 3 in the buy box, then use the bar. The cart should show 3.
  4. On a product with a subscription or a custom text field, confirm those arrive in the cart.
  5. Pick a sold-out variant. The bar's button should say so and be disabled.
  6. Tab through the page: the bar's button should only be reachable while it's visible, which hidden takes care of.
  7. Re-select the section in the theme editor, change a color, and see that the bar still responds. A custom element re-connects by itself when Shopify re-renders it, which covers the `shopify:section:load` case.

The bar is hidden with hidden until needed, and the slide-in sits behind a prefers-reduced-motion check, so people who ask for less motion get an instant appearance. A product with many hundreds of variants makes the JSON list heavier, so if yours has that many, check the page's weight or leave the list out and show only the price.

When you shouldn't add one, and what's next to it

Short product pages don't need this. If the buy button is on screen almost all the time, the bar has no moment to appear. It earns its space on long pages with lots of content below the buy box. And on products where the shopper has to make a real choice, such as a required personalization, a one-tap button mostly sends them back up the page. In that case a "Choose options" label that scrolls to the form is more honest.

Measure it rather than assume. There's no reliable uplift figure to quote for your store, and generic ones don't transfer well. Compare the add-to-cart rate of a similar period, or use your analytics to count clicks on this button, and remove the bar if it's not being used. An app can be worth it if you want built-in A/B testing, or a merchandising tool that combines the bar with upsells.

A grid of product cards where pressing a round add button sends the photo arcing into a bag counter in the header
Quick-Add Product Grid (€7, or €5 with a plan) isn't a sticky bar. It solves the neighboring problem: adding from a grid of products without opening each page. Notice how it sends products with options to their page, which is the same care about variants this post is about.

That grid doesn't replace a sticky bar, so for this job the code above is the answer. If your theme does something unusual, you can describe the bar and how your buy box behaves to the Shopify Liquid code generator.

Questions, answered

How do I add a sticky add to cart button to Shopify without an app?

Add a section to your product template that shows a fixed bar once the real button has scrolled away, and that submits the theme's product form when pressed. The section in this post does both, in any Online Store 2.0 theme whose form follows Shopify's standard markup.

Why does my sticky add to cart add the wrong variant?

It's probably posting a variant id fixed at page load. Read the current value of the form's id input instead, or better, submit the real form with requestSubmit so the theme's selected variant is used automatically.

Does a sticky add to cart work with my cart drawer?

Yes, if it fires the theme's submit event. requestSubmit does this, so the theme's own handler opens the drawer. A separate fetch to /cart/add.js won't update the drawer unless you write that part too.

Will a sticky add to cart cover my checkout buttons on mobile?

Not if it shows only while the real button is above the screen, as this one does. Do check it against your cart drawer, cookie banner and chat widget, and keep its z-index below the drawer's.

Does it keep subscription and custom fields when adding to cart?

Yes. Submitting the real form sends every field in it, including the selling plan, quantity and line item properties. If a required field is empty, this section scrolls back to it instead of adding.

Get the whole section written for you

Describe the section you want. Klorr writes the Liquid, the CSS, the schema and every theme-editor setting — code that lives in your theme and stays yours.