Skip to content

Instantly share code, notes, and snippets.

@jeremypage
Created January 31, 2019 12:10
Show Gist options
  • Save jeremypage/b300ddf77780850946c2d1e6b053e25f to your computer and use it in GitHub Desktop.
Save jeremypage/b300ddf77780850946c2d1e6b053e25f to your computer and use it in GitHub Desktop.
JavaScript: Dynamic filtering of page content using search box. Optionally send search term to analytics.
// Dynamic filtering of page content
// Wrap content to be filtered in #contentToFilterContainer element
// Add data-filter attributes with keywords for each (child) item to be filtered
var contentToFilterContainer = jQuery('#contentToFilterContainer');
var keyupTimer;
var filterCaption = (!!contentToFilterContainer.data('filtercaption') ? contentToFilterContainer.data('filtercaption') : 'Search page');
contentToFilterContainer.before('<label for="filterText">' +
filterCaption +
'</label><input type="text" id="filterText" class="content-filter" title="start typing here to filter content on the page" data-tooltip />'
);
// Don't let 'enter' keypress submit any in-page forms
jQuery('#filterText').on('keypress', function (e) {
if (e.keyCode === 10 || e.keyCode === 13) {
e.preventDefault();
}
});
// Get text entered into field (ignoring 'enter' keypress)
jQuery('#filterText').on('keyup', (function (e) {
if (e.keyCode === 10 || e.keyCode === 13) {
return false;
}
var input = jQuery('#filterText').val();
if (input.length != 1) {
// Optional: send search text to page analytics
trackSearch(input);
// Now only show container items that have matching data attributes (e.g. 'data-help')
contentToFilterContainer.children().each(function () {
if (jQuery(this).data('filter').toUpperCase().indexOf(input.toUpperCase()) > -1) {
jQuery(this).show();
} else {
jQuery(this).hide();
}
});
}
}));
// Send in-page content searches to analytics
function trackSearch(input) {
window.clearTimeout(keyupTimer);
// Wait 1 second before sending text to analytics
keyupTimer = window.setTimeout(function () {
if (!!input) {
// Push data to Google Tag Manager dataLayer
// (see https://www.analyticsmania.com/post/google-tag-manager-custom-event-trigger/)
// (see https://www.simoahava.com/analytics/create-a-generic-event-tag/)
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'GAEvent',
'eventCategory': 'In-page content filter',
'eventAction': 'Filter text: ' + input,
'eventLabel': undefined
});
}
}, 1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment