# カートに追加ボタンが動かない

**URL:** <https://community.shopify.com/t/topic/72616>\
**Category:** 技術的なQ＆A\
**Created:** [October 18, 2021, 10:48am UTC](https://community.shopify.com/t/topic/72616 "2021-10-18T10:48:37Z")\
**Posts on this page:** 5\
**Page:** 1

## AI-generated summary

写真ページで「カートに追加」ボタンが動作しない問題が発生。

**エラーの原因:**
- `product-form.js`の`onSubmitHandler()`内で`this.cartNotification.setActiveElement(document.activeElement)`がエラーを起こしていた
- `this.cartNotification`が`null`を返すため、`setActiveElement`プロパティを読み取れない状態
- `document.querySelector('cart-notification')`が要素を見つけられていない

**解決方法:**
- teratailで質問し、解決策を得た
- 問題はJavaScriptファイルの読み込み順序にあった
- `cart-notification.js`を先に読み込んでから`product-form.js`を読み込む必要がある
- CDNの読み込み順番を変更することで解決

**使用環境:**
ShopifyのDawnテーマをベースにカスタマイズ中

**残された質問:**
別のユーザーがCDNの読み込み順番の変更方法について追加質問している

<div class="post-metadata">

**Author:** ![izawa](https://avatars.discourse-cdn.com/v4/letter/i/e9bcb4/32.png) [@izawa](https://community.shopify.com/u/izawa)\
**Post date:** [October 18, 2021, 10:48am UTC](https://community.shopify.com/t/topic/72616/1 "2021-10-18T10:48:37Z")

</div>

写真のページを構築中です。カートに追加するというボタンが動かないのですが、動かすにはどうすればよいでしょうか？

 ![スクリーンショット 2021-10-18 19.26.32.png](https://canada1.discourse-cdn.com/shopifyforum/original/3X/4/4/441d68e59404b31a6674e4821dfc2d8526c2f97a.png)

また、検証ツールで見ると以下の様になるのですが、action="/cart/add"は、どこにあるのでしょうか？cart.jsでしょうか？

```markup

```

実際に記述しているコードは以下です。

```javascript
{%- form 'product', product, id: product_form_id, class: 'form', novalidate: 'novalidate', data-type: 'add-to-cart-form' -%}
                  
                  

                    
                    {%- if block.settings.show_dynamic_checkout -%}
                      {{ form | payment_button }}
                    {%- endif -%}
                  

                {%- endform -%}

```

---

<div class="post-metadata">

**Author:** ![izawa](https://avatars.discourse-cdn.com/v4/letter/i/e9bcb4/32.png) [@izawa](https://community.shopify.com/u/izawa)\
**Post date:** [October 19, 2021, 7:32am UTC](https://community.shopify.com/t/topic/72616/2 "2021-10-19T07:32:48Z")

</div>

product-form.jsファイルの.onSubmitHandler(evt)にあるthis.cartNotification.setActiveElement(document.activeElement);という記述がエラーの原因でした。

これはnullのプロパティを読み取ることができないみたいです。

ここからどこをどう変更すればいいかはまだ分かりません。

ちなみに、これはDawnテーマを元にしています。

```javascript
if (!customElements.get('product-form')) {
  customElements.define('product-form', class ProductForm extends HTMLElement {
    constructor() {
      super();

      this.form = this.querySelector('form');
      this.form.addEventListener('submit', this.onSubmitHandler.bind(this));
      this.cartNotification = document.querySelector('cart-notification');
    }

    onSubmitHandler(evt) {
      evt.preventDefault();
      const submitButton = this.querySelector('[type="submit"]');
      if (submitButton.classList.contains('loading')) return; 

      this.handleErrorMessage();
      this.cartNotification.setActiveElement(document.activeElement);

      submitButton.setAttribute('aria-disabled', true);
      submitButton.classList.add('loading');

      const config = fetchConfig('javascript');
      config.headers['X-Requested-With'] = 'XMLHttpRequest';
      config.body = JSON.stringify({
        ...JSON.parse(serializeForm(this.form)),
        sections: this.cartNotification.getSectionsToRender().map((section) => section.id),
        sections_url: window.location.pathname
      });

      fetch(`${routes.cart_add_url}`, config)
        .then((response) => response.json())
        .then((response) => {
          if (response.status) {
            this.handleErrorMessage(response.description);
            return;
          }

          this.cartNotification.renderContents(response);
        })
        .catch((e) => {
          console.error(e);
        })
        .finally(() => {
          submitButton.classList.remove('loading');
          submitButton.removeAttribute('aria-disabled');
        });
    }

    handleErrorMessage(errorMessage = false) {
      this.errorMessageWrapper = this.errorMessageWrapper || this.querySelector('.product-form__error-message-wrapper');
      this.errorMessage = this.errorMessage || this.errorMessageWrapper.querySelector('.product-form__error-message');

      this.errorMessageWrapper.toggleAttribute('hidden', !errorMessage);

      if (errorMessage) {
        this.errorMessage.textContent = errorMessage;
      }
    }
  });
}

```

---

<div class="post-metadata">

**Author:** ![izawa](https://avatars.discourse-cdn.com/v4/letter/i/e9bcb4/32.png) [@izawa](https://community.shopify.com/u/izawa)\
**Post date:** [October 21, 2021, 5:43am UTC](https://community.shopify.com/t/topic/72616/3 "2021-10-21T05:43:29Z")

</div>

```javascript
this.cartNotification.setActiveElement(document.activeElement);

```

この行の this.cartNotification が null なので、setActiveElement というプロパティが読めない。

```javascript
this.cartNotification = document.querySelector('cart-notification');

```

ここで document.querySelector() が null を返していた。

()内の記述が間違っているのか、と思って色々調べて試してみましたが問題なかったようでした…。  
()内が反応していないことは確かなので、とりあえずこのproduct-form.jsを読み込ませるのをやめたらボタンは機能しました。  
なぜnullが返ってくるのかは未だに分からないが、とりあえずの応急処置で読み込ませるのをやめました。

---

<div class="post-metadata">

**Author:** ![izawa](https://avatars.discourse-cdn.com/v4/letter/i/e9bcb4/32.png) [@izawa](https://community.shopify.com/u/izawa)\
**Post date:** [October 25, 2021, 2:39am UTC](https://community.shopify.com/t/topic/72616/4 "2021-10-25T02:39:34Z")

</div>

teratailで質問したら、教えていただけました。  
[https://teratail.com/questions/365988#](https://teratail.com/questions/365988#)

原因は、setActiveを定義しているcartNotification.jsのファイルの読み込む順でした。  
cartNotification.jsを読み込んでからproduct-form.jsを読み込ませないといけないようです。

---

<div class="post-metadata">

**Author:** ![mongorian346](https://yyz1.discourse-cdn.com/shopifyforum/user_avatar/community.shopify.com/mongorian346/32/111736_2.png) [@mongorian346](https://community.shopify.com/u/mongorian346)\
**Post date:** [April 13, 2023, 1:50am UTC](https://community.shopify.com/t/topic/72616/5 "2023-04-13T01:50:42Z")

</div>

すいません。このCDNの読み込みの順番を変更するのはどうやるのでしょうか？
