JavaScript only being called once in Squarespace

丶灬走出姿态 提交于 2019-11-28 02:18:59

The source of your problem is that your template has AJAX loading enabled. There are currently a couple generally-accepted ways to deal with this as a Squarespace developer:

  1. Disable AJAX loading
  2. Write your javascript functions in a manner that will run on initial site load and whenever an "AJAX load" takes place.

Option 1 - Disable AJAX:

  1. In the Home Menu, click Design, and then click Site Styles.
  2. Scroll down to Site: Loading.
  3. Uncheck Enable Ajax Loading.


Option 2 - There are a number of ways that developers approach this, including:

<script>
window.Squarespace.onInitialize(Y, function() {
  // do stuff
});
</script>

or

<script>
(function() {
  // Establish a function that does stuff.
  var myFunction = function() {
    // Do stuff here.
  };

  // Initialize the fn on site load.
  myFunction();
  // myFunction2(); , etc...

  // Reinit. the fn on each new AJAX-loaded page.
  window.addEventListener("mercury:load", myFunction);
})();
</script>

or

<script>
(function() {
  // Establish a function that does stuff.
  var myFunction = function() {
    // Do stuff here.
  };

  // Initialize the fn on site load.
  myFunction();

  // Reinit. the fn on each new AJAX-loaded page.
  new MutationObserver(function() {
    myFunction();
    // myFunction2(); , etc...
  }).observe(document.body, {attributes:true, attributeFilter:["id"]});
})();
</script>

Each of those works for most of the latest (at time of writing) templates most of the time. Each of those have their advantages and disadvantages, and contexts where they do not work as one might expect (for example, on the /cart/ page or other "system" pages). By adding your code within the context of one of the methods above, and ensuring that the code is of course working in the desired contexts and without its own bugs/issues, you will have your code run on initial site load and on each AJAX page load (with some exceptions, depending on the method you use).

Your problem is the page does not reload when clicking a button on the left, just some elements are removed, added and replaced. The changed elements will not be restyled. You will need to re-run your JavaScript after one of those buttons is clicked. Perhaps something like this:

document.querySelectorAll(
    ".ProductList-filter-list-item"
).forEach(
    i=>i.addEventListener(
        "click", ()=>console.log("hello")
    )
)

where you replace console.log("hello") with whatever resets your formatting.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!