We're moving the community! Starting July 7, the current community will be read-only for approx. 2 weeks. You can browse content, but posting will be temporarily unavailable. Learn more

Help! "Add to Cart" Button Not Working in My Theme

Solved

Help! "Add to Cart" Button Not Working in My Theme

Faxree
Excursionist
12 0 2

Hi everyone,

I'm having an issue with the "Add to Cart" button in my theme, and I can't figure out what's wrong. The button works fine in other themes, but in my current theme, nothing happens when I click it.

Here's what I've tried so far:

  • Checked the code in featured-product.liquid and other relevant files.
  • Switched to another theme, where the button works as expected.

Has anyone experienced something similar or have any tips on what I should check next? I would greatly appreciate any help!

Thank you in advance!

Accepted Solution (1)
Laza_Binaery
Shopify Partner
545 87 152

This is an accepted solution.

Well, at least some progress 🙂 Have fun.

Kind regards
Laza
www.binaery.com

View solution in original post

Replies 12 (12)

Laza_Binaery
Shopify Partner
545 87 152

Hi @Faxree 

 

You seem to have a Javascript error 

 

Uncaught SyntaxError: Unexpected token '{' (at cart-drawer.js?v=64791997275614475541739979208:84:36)

 

And by looking at cart-drawer.js  looks like you have an extra } at 

// Define CartDrawer
class CartDrawer extends HTMLElement {
  constructor() {
    super(); // Call the parent class constructor
    this.addEventListener('keyup', (evt) => evt.code === 'Escape' && this.close());
    const overlay = this.querySelector('#CartDrawer-Overlay');
    if (overlay) overlay.addEventListener('click', this.close.bind(this));

    this.setHeaderCartIconAccessibility();
  }
}

  setHeaderCartIconAccessibility() {

 

one before "setHeaderCartIconAccessibility()" function as that should be inside a class. As this code on GitHub shows

 

https://github.com/Shopify/dawn/blob/main/assets/cart-drawer.js#L10

 

So try to delete that } and see what is going on. As you know, you have a bit older Dawn version so the code on GitHub looks slightly different in the rest of the file.

Kind regards
Laza
www.binaery.com
Faxree
Excursionist
12 0 2

Hello Laza, so kind o you to help me. But I dont see the same as you when I am in cart-drawer.js

Faxree
Excursionist
12 0 2
Laza_Binaery
Shopify Partner
545 87 152

Hi @Faxree 

 

Yes, figured out your site 🙂  But now I do not see that error either.

But something is still wrong, in browser I see :

 

 

/** Shopify CDN: Minification failed

Line 9:4 Transforming const to the configured target environment ("es5") is not supported yet
Line 16:12 Expected ")" but found ":"

**/

 

 

And code is from 

 

https://faxree.com/cdn/shop/t/3/assets/cart-drawer.js?v=62806416649478877051739997506

 

 

 

document.querySelectorAll('.cart-item-remove').forEach(button => {
  button.addEventListener('click', function() {
    const lineItemId = this.getAttribute('data-line-item-id');
    
    // Disable the button to prevent multiple clicks
    this.disabled = true;
    this.textContent = 'Removing...';

    fetch('/cart/change.js', 
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ id: lineItemId, quantity: 0 })
    })

 

 

Last line   })  should not have  }.

 

But this also can be a minification error that could be caused by missing } or extra { somewhere in your code. And not sure if it is in cart.js but depends. Did you make some code changes in the theme recently?  A new app installed maybe?

 

Sorry for not being that great help.

Kind regards
Laza
www.binaery.com
Faxree
Excursionist
12 0 2

Ahh okay, thanks for trying. This problem started earlier when I changed the code to make it possible for me to delete products from the shopping cart. But now it's not possible to add items to the cart, which I think is even worse haha.

Laza_Binaery
Shopify Partner
545 87 152

Well, there you go 🙂 

 

Check that code for removing products from the cart. That fetch function looks like having extra }.

You can paste the code here from your file if you want to share.

 

Kind regards
Laza
www.binaery.com
Faxree
Excursionist
12 0 2

document.querySelectorAll('.cart-item-remove').forEach(button => {
button.addEventListener('click', function() {
const lineItemId = this.getAttribute('data-line-item-id');

// Disable the button to prevent multiple clicks
this.disabled = true;
this.textContent = 'Removing...';

fetch('/cart/change.js',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: lineItemId, quantity: 0 })
)
.then(response => {
if (!response.ok) {
throw new Error('Failed to remove item');
}
return response.json();
})
.then(() => {
location.reload(); // Reload the page to update the cart
})
.catch(error => {
console.error('Error:', error);
this.disabled = false; // Re-enable the button if there's an error
this.textContent = 'Remove'; // Reset the button text
alert('Failed to remove item. Please try again.');
});
});
});

// Ensure CartItems is defined before extending it
if (typeof window.CartItems === 'undefined') {
class CartItems {
constructor() {
this.items = [];
}
}
window.CartItems = CartItems; // Make it global
}
javascript
const removeButtons = document.querySelectorAll('.cart-item-remove');
if (removeButtons.length > 0) {
removeButtons.forEach(button => {
button.addEventListener('click', function() {
// Your existing code here
});
});
}
// Define CartDrawerItems after CartItems is guaranteed to exist
class CartDrawerItems extends window.CartItems {
constructor() {
super(); // Call the parent class constructor
console.log("CartDrawerItems opprettet!");
}
}

// Define CartDrawer
class CartDrawer extends HTMLElement {
constructor() {
super(); // Call the parent class constructor
this.addEventListener('keyup', (evt) => evt.code === 'Escape' && this.close());
const overlay = this.querySelector('#CartDrawer-Overlay');
if (overlay) overlay.addEventListener('click', this.close.bind(this));

this.setHeaderCartIconAccessibility();
}


setHeaderCartIconAccessibility() {
const cartLink = document.querySelector('#cart-icon-bubble');
if (!cartLink) return;

cartLink.setAttribute('role', 'button');
cartLink.setAttribute('aria-haspopup', 'dialog');

cartLink.addEventListener('click', (event) => {
event.preventDefault();
this.open(cartLink);
});

cartLink.addEventListener('keydown', (event) => {
if (event.code.toUpperCase() === 'SPACE') {
event.preventDefault();
this.open(cartLink);
}
});
}

open(triggeredBy) {
if (triggeredBy) this.setActiveElement(triggeredBy);
const cartDrawerNote = this.querySelector('[id^="Details-"] summary');

if (cartDrawerNote && !cartDrawerNote.hasAttribute('role')) {
this.setSummaryAccessibility(cartDrawerNote);
}

setTimeout(() => {
this.classList.add('animate', 'active');
});

this.addEventListener(
'transitionend',
() => {
const containerToTrapFocusOn = this.classList.contains('is-empty')
? this.querySelector('.drawer__inner-empty')
: document.getElementById('CartDrawer');

const focusElement = this.querySelector('.drawer__inner') || this.querySelector('.drawer__close');
trapFocus(containerToTrapFocusOn, focusElement);
},
{ once: true }
);

document.body.classList.add('overflow-hidden');
}

close() {
this.classList.remove('active');
if (this.activeElement) removeTrapFocus(this.activeElement);
document.body.classList.remove('overflow-hidden');
}

setSummaryAccessibility(cartDrawerNote) {
cartDrawerNote.setAttribute('role', 'button');
cartDrawerNote.setAttribute('aria-expanded', 'false');

if (cartDrawerNote.nextElementSibling?.getAttribute('id')) {
cartDrawerNote.setAttribute('aria-controls', cartDrawerNote.nextElementSibling.id);
}

cartDrawerNote.addEventListener('click', (event) => {
event.currentTarget.setAttribute(
'aria-expanded',
!event.currentTarget.closest('details').hasAttribute('open')
);
});

cartDrawerNote.parentElement.addEventListener('keyup', onKeyUpEscape);
}

renderContents(parsedState) {
const drawerInner = this.querySelector('.drawer__inner');
if (drawerInner?.classList.contains('is-empty')) {
drawerInner.classList.remove('is-empty');
}

this.productId = parsedState.id;

this.getSectionsToRender().forEach((section) => {
const sectionElement = section.selector
? document.querySelector(section.selector)
: document.getElementById(section.id);

if (sectionElement) {
sectionElement.innerHTML = this.getSectionInnerHTML(parsedState.sections[section.id], section.selector);
}
});

setTimeout(() => {
this.querySelector('#CartDrawer-Overlay')?.addEventListener('click', this.close.bind(this));
this.open();
});
}

getSectionInnerHTML(html, selector = '.shopify-section') {
return new DOMParser().parseFromString(html, 'text/html').querySelector(selector)?.innerHTML || '';
}

getSectionsToRender() {
return [
{
id: 'cart-drawer',
selector: '#CartDrawer',
},
{
id: 'cart-icon-bubble',
},
];
}

setActiveElement(element) {
this.activeElement = element;
}
}

customElements.define('cart-drawer', CartDrawer);
customElements.define('cart-drawer-items', CartDrawerItems);

Do  you see where this goes badly?

 

Laza_Binaery
Shopify Partner
545 87 152

Maybe here:

 

javascript
const removeButtons = document.querySelectorAll('.cart-item-remove');
if (removeButtons.length > 0) {
    removeButtons.forEach(button => {
        button.addEventListener('click', function() {
            // Your existing code here
        });
    });
}

 

You have "javascript" there.

Kind regards
Laza
www.binaery.com
Faxree
Excursionist
12 0 2

There, I had hope for a second 🙂 Unfortunately, that wasn’t the cause either:(

Laza_Binaery
Shopify Partner
545 87 152

Last try 🙂 

 

I had to copy it to VS code editor, but looks like it is in the fetch function. Options should be an object so :

        fetch('/cart/change.js',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    id: lineItemId,
                    quantity: 0
                })
            })

 

Hope that is it. 

Kind regards
Laza
www.binaery.com
Faxree
Excursionist
12 0 2

It works but now its laggy, and I cant remove items fro cart. Really strange!! Ai just makes it worse also.. HAHA

 

Laza_Binaery
Shopify Partner
545 87 152

This is an accepted solution.

Well, at least some progress 🙂 Have fun.

Kind regards
Laza
www.binaery.com