How can I automatically add the appropriate suffix ("st", "nd", "rd", "th") to numbers with JavaScript in Webflow?

Published on
September 22, 2023

To automatically add the appropriate suffix ("st", "nd", "rd", "th") to numbers with JavaScript in Webflow, you can follow these steps:

  1. Create a Custom Code Embed: In the Webflow Designer, select the element where you want to display the number with the suffix. Go to the Settings panel on the right-hand side, scroll down to the Custom Code section, and click on the </> sign to add a new code embed.

  2. Add JavaScript code: In the code embed, add the following JavaScript code:

<script>  var addSuffix = function(num) {    var suffix = "";    var lastDigit = num % 10;        if (num === 11 || num === 12 || num === 13) {      suffix = "th";    } else {      switch (lastDigit) {        case 1:          suffix = "st";          break;        case 2:          suffix = "nd";          break;        case 3:          suffix = "rd";          break;        default:          suffix = "th";          break;      }    }        return num + suffix;  };  // Replace 'yourElementID' with the actual ID of the element where you want to display the number  var element = document.getElementById('yourElementID');  var number = parseInt(element.innerHTML);  element.innerHTML = addSuffix(number);</script>
  1. Replace 'yourElementID': Replace the 'yourElementID' string in the code with the actual ID of the element where you want to display the number. You can find the element's ID by selecting it in the Webflow Designer and going to the Settings panel on the right-hand side.

  2. Test and refine: Preview your Webflow project or publish it to see the JavaScript code in action. It will automatically add the appropriate suffix to the number displayed in the specified element.

This JavaScript code checks the last digit of the number and adds the appropriate suffix based on standard English suffix rules. The code also includes a special case for numbers 11, 12, and 13, as they have irregular suffixes.

Example Usage:
If you have an element with the ID "myNumber", you can automatically add the appropriate suffix to the number using the following code:

var element = document.getElementById('myNumber');var number = parseInt(element.innerHTML);element.innerHTML = addSuffix(number);

Remember to replace 'myNumber' with the actual ID of your element.

With this solution, you can dynamically display numbers with the correct ordinal suffixes in your Webflow project.

Additional Questions:

  1. How do I add custom JavaScript code in Webflow?
  2. Can I use JavaScript to manipulate elements in Webflow?
  3. How can I update the content of an element using JavaScript in Webflow?