Advanced JavaScript code snippets for gates
These code snippets help JavaScript developers implement advanced functionality with Formulayt gates using our JS API. Familiarity with our JS API is recommended before using these techniques.
Refreshing gates after dynamic content changes
Force Formulayt to process new gates
Use this code when you've dynamically added gate embed code to a page. This command instructs the Formulayt script to scan the page again and process any new gates it finds.
gcdc("loadGates");
Triggering gates programmatically
Dynamically inject and trigger a page gate
This function creates and triggers any type of gate using only the gate ID. It's particularly useful for showing page gates in response to specific user actions.
function triggerPageGate(gateId) {
let gateDiv = document.createElement('div');
gateDiv.classList.add('gate-' + gateId);
document.body.appendChild(gateDiv);
window.gcdc("loadGates");
}To use this function, simply call it with the ID of the gate you want to display:
// Example: Trigger gate with ID 12345 triggerPageGate("12345");
Working with gates
Using our JS API you can work with gates on the current webpage to read and modify field values. You can adapt the snippets below to include your specific gate ID and field key. These snippets must be run after the Formulayt script has finished loading.
Extracting a field value from a gate
// Get a specific gate by ID AFTER it has finished loading
gcdc('getGateByID', 'a123a-a123a-a123a-a123',
function(gateInstance){
// Request a field by its Formulayt key.
// Field keys are listed in the admin area.
const emailField = gateInstance.form.getFieldById("email");
// Check that the field exists on the gate before proceeding
if (emailField) {
// Get the field value.
// You could assign this to variable for further processing.
emailField.getValue();
}
});
Changing a field value on a gate
// Get a specific gate by ID AFTER it has finished loading
gcdc('getGateByID', 'a123a-a123a-a123a-a123',
function(gateInstance){
// Request a field by its Formulayt key.
// Field keys are listed in the admin area.
const emailField = gateInstance.form.getFieldById("email");
// Check that the field exists on the gate before proceeding
if (emailField) {
// Set the field value.
// The second argument should be set to true to trigger
// rules and other watchers to fire on change.
emailField.setValue("test@test.com", true);
}
});
