/**
* filterCourses
*
* Filters table rows on the page based on the 'filter' parameter in the URL query string.
* - Hides all table rows by default, then shows only rows whose text content matches any of the filter terms.
* - Adds a heading and a "clear filter" link above the page's course listing heading to indicate filtering is active.
* - Intended for use on pages with a heading containing 'Classes with Scheduled Trainings'.
*
* How it works:
* 1. Parses the URL for a 'filter' parameter.
* 2. Hides all
elements.
* 3. Shows only rows containing one or more of the filter terms.
* 4. Annotates the page with filtering information and a way to clear the filter.
*
* Usage:
* - Call this function after the DOM has loaded on pages where filtering should be enabled.
* - Designed to work in conjunction with WordPress and the `CTF_FILTERABLE_COURSE` body class.
*/
function filterCourses(){
//Get the URL query and create object
let urlString = window.location.href;
let paramString = urlString.split('?')[1];
let queryString = new URLSearchParams(paramString);
let params = {};
for (let pair of queryString.entries()) {
//console.log("Key is: " + pair[0]);
//console.log("Value is: " + pair[1]);
params[pair[0]] = pair[1].split(' ');
}
//console.log(params);
if(params.filter === undefined){
return;
}
//Find rows containing search term(s)
let tableRows = document.getElementsByTagName('tr');
let stack = [];
for(let row of tableRows){
stack.push(row)
row.style = "display:none;";
}
let matches = [];
while(stack.length > 0){
let elem = stack.pop();
//console.log(elem.textContent);
for(let term of params.filter){
if(elem.textContent.toLowerCase().includes(term.toLowerCase())){
//textContent includes text in all children of node btw
matches.push(elem);
}
}
for(let child of elem.children){
stack.push(child);
}
}
//console.log(matches);
for(let m of matches){
//Unhide rows matching search criteria
m.style ="";
}
//Get the page heading
let pageHeading = undefined;
for (const h2 of document.querySelectorAll('h2')) {
if (h2.textContent.includes('Classes with Scheduled Trainings')) {
pageHeading = h2;
//console.log(pageHeading);
}
}
//Create a heading on the page to indicate courses list is filtered.
let filterLabel = document.createElement('h3');
filterLabel.textContent = 'Filter: '+params.filter;
let clearFilterButton = document.createElement('a');
clearFilterButton.textContent = 'Click here to clear filter.';
clearFilterButton.href = '.';
pageHeading.before(filterLabel);
pageHeading.before(clearFilterButton);
pageHeading.before(document.createElement('hr'));
}
document.addEventListener('DOMContentLoaded',function(){
if(document.body.classList.contains('page-id-79')){
filterCourses();
}
});