Skip to content

Instantly share code, notes, and snippets.

@zjuul
Created March 20, 2019 08:02
Show Gist options
  • Save zjuul/c57658f19fafd067e3578f17be25d965 to your computer and use it in GitHub Desktop.
Save zjuul/c57658f19fafd067e3578f17be25d965 to your computer and use it in GitHub Desktop.
// GTM custom HTML tag for tracking incomplete searches
// logic: if user starts typing, start a timer. Stop the timer when user is idle 2.5 seconds
// then push the event on the DL
(function() {
var timer, firstResult, searchText;
var waiting = false;
var waitTime = 2500; // milliseconds
function waitForMoreKeys(msec) {
if (!waiting) {
waiting = true;
timer = setTimeout(function(){
// scrape your datalayer key/values here
searchText = $("#mapSearchInput").val().trim();
firstResult = $("#results > a:nth-child(1) > span").text().trim();
dataLayer.push( {
'event': 'mapSearchInput search',
'firstResult': typeof firstResult === "undefined" ? '(none)' : firstResult.toLowerCase(),
'searchInput': searchText ? searchText.toLowerCase() : '(none)'
});
waiting = false;
}, msec);
}
}
function stopWaiting() {
clearTimeout(timer);
waiting = false;
}
// replace this with your searchbox ID
$("#mapSearchInput").keydown(function() {
if (waiting)
stopWaiting();
waitForMoreKeys(waitTime);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment