Skip to content

Instantly share code, notes, and snippets.

@iampatgrady
Last active November 26, 2021 22:41
Show Gist options
  • Save iampatgrady/dfb4b3877551ed977dc9ab210f93345d to your computer and use it in GitHub Desktop.
Save iampatgrady/dfb4b3877551ed977dc9ab210f93345d to your computer and use it in GitHub Desktop.
The script tracks search experiences that update automatically as you type. Known as Incremental Search in software and As-You-Type in web applications. This solution offers a way to track the value as a timeout expires after keypress. There is logic to prevent redundant events from firing.
/*
* Based on example at https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout
* Usage: edit config variables, copy+paste into JS console, type in search field and wait for dataLayer push
*/
(function(dL) {
/*
* Application Functions
*/
var delay = 2000, // 2 second timeout
selector = "input[type=search]", // CSS selector for search field
verb = "keyup", // event listener, reference: https://developer.mozilla.org/en-US/docs/Web/Events
searchTimer = {
sendData: function(query) { // 'query' is result of the CSS selector
this.timeoutID = undefined;
dL.push({"event": "search-term", "search-value": query}) // dataLayer object push
},
setup: function(query) {
if (typeof this.timeoutID === 'number') {
this.cancel(); // clearout existing timer, prevents multiple events from being pushed
}
this.timeoutID = window.setTimeout(function(query) {
this.sendData(query); // we hit the delay timeout, send data!
}.bind(this), delay, query);
},
cancel: function() { // used to prevent multiple dataLayer pushes per delay period
window.clearTimeout(this.timeoutID);
this.timeoutID = undefined;
}
};
/*
* Measurement Logic
*/
document.querySelectorAll(selector).forEach(function(input) { // loop through all matching search fields
input.addEventListener(verb, function(element) { // attach the event listener to each element
searchTimer.setup(element.target.value); // setup begins or resets the timer, input search term
});
});
})(window.dataLayer = window.dataLayer || []) // init dataLayer to prevent collisions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment