Created
November 21, 2023 21:31
-
-
Save interactiveRob/a8e23ca975b79a038954cd6af399d83d to your computer and use it in GitHub Desktop.
flexible URL QueryString show hide div script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.addEventListener("DOMContentLoaded", () => { | |
let state = { | |
url: window.location.href, | |
}; | |
let module = { | |
showHideElements(allElements) { | |
Array.from(allElements).map((element) => { | |
let key = element.dataset.qKey; | |
let identifier = element.dataset.q; | |
if (!identifier) return; | |
/*don't show/hide if there is no | |
truthy 'qKey' parameter set in the url */ | |
let query = this.getQueryParameterValue(key, state.url); | |
if (!query) return; | |
//don't hide the selected one | |
if (query == identifier) return; | |
//don't hide anything if there are no matches | |
let matches = document.querySelector(`[data-q-key="${key}"][data-q="${query}"]`); | |
if (!matches) return; | |
//otherwise hide 'em | |
element.style.display = "none"; | |
}); | |
}, | |
init() { | |
let allElements = document.querySelectorAll(`[data-q-key]`); | |
if (!allElements.length) return; | |
this.showHideElements(allElements); | |
}, | |
//utils | |
getQueryParameterValue(field, url) { | |
let href = url; | |
let reg = new RegExp("[?&]" + field + "=([^&#]*)", "i"); | |
let string = reg.exec(href); | |
return string ? string[1] : null; | |
}, | |
}; | |
module.init(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment