← All Scripts

#17 - Populate Link From Custom Field v0.2

Use custom fields to populate link targets with one attribute!

View demo

<!-- 💙 MEMBERSCRIPT #17 v0.2 💙 ADD CUSTOM FIELD AS A LINK -->
<script>
  document.addEventListener("DOMContentLoaded", function() {
    // Parse member data from local storage
    const memberData = JSON.parse(localStorage.getItem('_ms-mem') || '{}');

    // Check if the user is logged in
    if (memberData && memberData.id) {
      // Get custom fields
      const customFields = memberData.customFields;

      // Select all elements with 'ms-code-field-link' attribute
      const elements = document.querySelectorAll('[ms-code-field-link]');

      // Iterate over all selected elements
      elements.forEach(element => {
        // Get custom field key from 'ms-code-field-link' attribute
        const fieldKey = element.getAttribute('ms-code-field-link');

        // If key exists in custom fields
        if (customFields.hasOwnProperty(fieldKey)) {
          // Get the custom field value
          const fieldValue = customFields[fieldKey];

          // Check if the custom field value is empty
          if (fieldValue.trim() === '') {
            // Set the element to display none
            element.style.display = 'none';
          } else {
            // Check if the link has a protocol, if not, add http://
            let link = fieldValue;
            if (!/^https?:\/\//i.test(link)) {
              link = 'http://' + link;
            }

            // Set the element href to the corresponding value
            element.setAttribute('href', link);
          }
        } else {
          // Set the element to display none if the custom field key doesn't exist
          element.style.display = 'none';
        }
      });
    }
  });
</script>
Description
Attribute
Member | Links
Populate a link using an URL stored in a custom field.
href, custom link, url, dynamic
ms-code-field-link
Your_Field_ID
Your_Field_ID

v0.2 - Hide link if empty

If the value of the custom field is empty, the element with the ms-code-field-link attribute will be set to display: none.

Button Text