Google has two major analytics implementations: analytics.js & gtag.js - depending on which you're using, there's a different syntax for each to log page views. You could also probably log an event as well.
ga('send', 'pageview', [page], [fieldsObject]);
gtag('config', 'GA_MEASUREMENT_ID', {
'page_title' : 'homepage',
'page_path': '/home'
});
Your use case will determine which events you'd like to use to trigger logging. Handling the blur
event is fine for most use cases, but you also might want to handle text change and then debounce
Here's a discussion and vanilla js implementation of debouncing based off underscore:
function debounce(func, wait) {
var timeoutId;
return function() {
var context = this,
args = arguments;
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
func.apply(context, args);
}, wait);
};
};
// generate a debounced version with a min time between calls of 2 seconds
let sendPageView = debounce(function() {
gtag('config', 'GA_MEASUREMENT_ID', {
'page_title' : 'homepage',
'page_path': '/home?searchText=' + encodeURI(filter.value)
});
console.log("Text: " + filter.value)
}, 2000)
// attach event listener
let filter = document.getElementById("filter")
filter.addEventListener('input', sendPageView)
function debounce(func, wait) {
var timeoutId;
return function() {
var context = this,
args = arguments;
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
func.apply(context, args);
}, wait);
};
};
// fake gtag for demo
gtag = function() {}
<!-- language: lang-html -->
<input type="text" id="filter" />
<!-- end snippet -->