Hide an Element If a Field is Set
This approach is used when you want to hide an element based on if the member has data in a custom field.
Example Use Case:
You are displaying custom fields on a profile page but do not want to have blank sections/elements. In the scenario below we will be hiding a "favorite color" custom field if the member has not entered any data.
window.$memberstackDom.getCurrentMember().then(({ data: member }) =>
{ if (member && member.customFields["favorite-color"] == null) {
const elem = document.getElementById('favoriteColor')
elem.style.display='none';
}
});
Usage:
Replace the placeholder entries with your own custom field id and the element id.
You can use this same code block to Show an element by changing 'none' to 'block' or 'inline-block' or 'flex' etc.
Show an Element if the Input is Equal To ___
💡 This approach works most reliably with checkboxes, select, fields, and radio buttons since they are true, false, or some other pre-determined value.
// paste in body of global site scripts
function conditionallyRenderElement({ key, value, id }) {
let element = document.getElementById(id)
element.style.display = key.includes(value) ? "block" : "none";
}
window.$memberstackDom.getCurrentMember().then(({ data: member }) => {
if (member && member.customFields) {
let key = member.customFields["your custom field id"] // EDIT THIS
// the value of the custom field you want to check for
let value = "true" // EDIT THIS
// id of the element you want to show or hide conditionally
let id = "conditional_wrapper" // EDIT THIS
conditionallyRenderElement({ key, value, id })
}
});
Usage:
Replace the placeholder entries for key
, value
and id
inside of the getCurrentMember
method.
- Key: The id of the custom field you want to check for.
- Value: The text value that the custom field should equal.
- Id: The ID of the element that you want to conditionally show or hide.
You can use this same code block to hide an element by swapping "block" and "none" in the 4th line.
Keywords: Show, hide, conditional, hidden, etc.
Similar Articles
Lock Pages & Folders with Gated Content →
Display an element based on Custom Fields →
Display an element based on Plans and Gated Content →
Display and element based on Metadata →
Display and element based on Free Trials →
Keywords: Gated content attributes, hidden content attributes, show/hide, show element, hide element, visibility
Comments
4 comments
Hi Duncan Hamra
There's a bug with your example here:
The null doesn't actually work, I had to replace it with "".
I let the team know 🤔 Will get this tested ASAP.
Hey Duncan,
I was wondering if you could also put an example of how to set this up here as well.
Best,
Nicholas
Great suggestion! Yes, I'll see what we can do 😁
Please sign in to leave a comment.