Skip to main content

How to use custom triggers with JavaScript

Guide for Asklayer users to trigger surveys via custom JavaScript, with code for clicks and scroll position events.

Custom triggers let you display a survey using your own JavaScript. You can fire it on any event you like — link clicks, button clicks, scroll position, and more.


Steps

  1. In the survey editor's "Delivery" section, select "Custom trigger". A dedicated JavaScript snippet and the survey ID will be displayed.

  2. Combine this snippet with your own JavaScript to build the custom trigger. This requires the ability to edit your website's HTML — if you don't have that access, please ask your webmaster or developer.

  3. When adapting the examples below to your own site, be sure to change the element class names and the triggerSurvey code to match your site and survey.


Example: Displaying a survey when clicking a link

<a href="javascript:asklayer.triggerSurvey('tpJ3q30jOmnUoNtucrtZ')">MyLink</a>

Example: Displaying a survey when clicking a button (class name my-button)

<script>
document.addEventListener('DOMContentLoaded', () => {
const button = document.querySelector('.my-button');
button.onclick = function(e){
e.preventDefault();
// Replace the following with your own custom trigger code copied from the editor
asklayer.triggerSurvey('kBbharRQbmM2rDKw2wUA');
};
});
</script>

Example: Displaying a survey when scrolling to a specific image (class name my-image)

The survey is displayed once the top edge of the image reaches the center of the window.

<script>
document.addEventListener('DOMContentLoaded', () => {
const element = document.querySelector('.my-image');
const offset = window.innerHeight / 2;

let fired = false, ticking = false;

document.addEventListener('scroll',()=>{
if(ticking || fired || !element || typeof asklayer === 'undefined') return;

window.requestAnimationFrame(() => {
const top = element.getBoundingClientRect().top;
if(top < offset){
// Replace the following with your own custom trigger code copied from the editor
asklayer.triggerSurvey('kBbharRQbmM2rDKw2wUA');
fired = true;
}
ticking = false;
});
ticking = true;
});
});
</script>

Did this answer your question?