Skip to content

Instantly share code, notes, and snippets.

@noahcoad
Last active November 9, 2021 09:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noahcoad/32aefee585901acecdd69617d1082462 to your computer and use it in GitHub Desktop.
Save noahcoad/32aefee585901acecdd69617d1082462 to your computer and use it in GitHub Desktop.
Utility function for Tampermonkey and Greasemonkey scripts to detect and handle AJAX elements and single page apps, waiting until elements exist and become visible
//
// Description
// whenVisible(): a utility function for Tampermonkey and Greasemonkey
// scripts to detect and handle AJAX elements and single
// page apps, waiting until elements exist and become visible
//
// Created
// 2021-10-01 by Noah Coad http://coad.net
//
// Usage Example
// whenVisible("button[type=username]", 0, x => x.value = "noahcoad")
//
// Credits
// thanks to BrockA for his waitForKeyElement() func which inspired this
// https://gist.github.com/BrockA/2625891
//
// Gist
// https://gist.github.com/noahcoad/32aefee585901acecdd69617d1082462
//
function whenVisible(sel, func, idx = 0) {
// sel = css selector, such as "button[type=username]"
// func = function to call, passes the element found
// idx = index of the element to find (if not the first element)
var intv = setInterval(function() {
var elems = document.querySelectorAll(sel);
// if (elems.length < 1) { return false; }
if (elems.length > idx) {
if (!(window.getComputedStyle(elems[idx]).display === 'none')) {
// when element is found, and visibile, clear the interval.
clearInterval(intv);
// call function
func(elems[idx]);
}
}
else return false;
}, 200);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment