Streaming live at 10am (PST)

Can we update live collection items using JS?

Hi, I wanna build a feature where a JS code counts the number of words in an article and puts the value in the relevant field in a live collection item. Is it doable? If yes, can somebody share a boilerplate code to get started?

You could target specific article class or id and update a span with javascript like so:

Codepen here

HTML

<p class="article">hello world</p>
<span class="counter"></span>

JavaScript

document.addEventListener("DOMContentLoaded", () => {
  // globals
  const log = console.log,
    article = document.getElementsByClassName("article")[0],
    counter = document.getElementsByClassName("counter")[0],
    string = String(article.innerHTML),
    words = string.split(" "),
    wordsNumbers = words.length;

  // inject value
  (function counting(words) {
    counter.textContent = wordsNumbers;
  })();
});

Hope that helps.

Yeah it helps, but I think this would only inject the values on the dynamic template page. I want global access, like in the collection lists outside of template page. That’s why I want to write in the live collection using Webflow’s CMS API. And access it anywhere. The API’s documentation is too complex for me to understand. I want a starting point.

@Hamza_Nasim - you don’t want to do this via JS as far as I’m aware as you will have to expose your API credentials on the client-side, which is obviously not secure. You could do this with Zapier most likely or write some sort of simple middleware app to do it.

@sam-g
Yeah I see. Becuse client-site code is exposed. And we have to request authentication using api-token in the code. Got it. But as far as Zapier is concerned, how can it be achieved? I need to perform certain calculations before doing the write operation?

@Hamza_Nasim you could probably send a webhook to Zapier:

https://developers.webflow.com/#create-new-webhook
https://developers.webflow.com/#model58

So you would create a new webhook (probably two, depending on your needs):

Probably these two triggers:

Then when the webhook runs you could use the Zapier formatter to count the characters:

image

And then update the item using the id from the webhook:

I don’t know exactly what you are trying to do, but this might get you close.

@Hamza_Nasim - any luck?

This sounds like a potential infinite loop.

  1. editor updates item
  2. collection_item_changed webhook is triggered
  3. zapier updates item
  4. collection_item_changed webhook is triggered
  5. zapier updates item
  6. Profits!

You’ll never get to profits. :frowning:

@JudoHacker - haha, I think you’re right. Might be able to avoid with using a filter, I.e only send webhook on create and changes to whatever property.