I need to show in Google Analytics the values that the user enters in the fields. But I do not need to see the number of clicks on the field. Help me please.
Sending Data to Google Programmatically
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.
Analytics.js - page views
ga('send', 'pageview', [page], [fieldsObject]);
Gtag.js - pageviews
gtag('config', 'GA_MEASUREMENT_ID', {
'page_title' : 'homepage',
'page_path': '/home'
});
Handling the Event in Javascript
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
Debouncing
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);
};
};
Example in Stack Snippets
<!-- begin snippet: js hide: true console: true babel: false --> <!-- language: lang-js -->// 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 -->