Skip to content

Instantly share code, notes, and snippets.

@djmunro
Last active July 9, 2020 20:00
Show Gist options
  • Save djmunro/1c3e1f9dc0f888129cbe9d9d79a113b2 to your computer and use it in GitHub Desktop.
Save djmunro/1c3e1f9dc0f888129cbe9d9d79a113b2 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script
src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous"
></script>
</head>
<body>
<h1 class="title">Wait for element demo</h1>
<button class="button">Click Me!</button>
</body>
<script>
const handleClick = () => {
const title = document.querySelector(".title");
title.classList.add("foo");
};
const button = document.querySelector(".button");
button.onclick = handleClick;
const waitForEl = (selector, callback, attempts = 20) => {
if ($(selector).length) {
callback();
} else {
if (attempts > 0) {
attempts--;
setTimeout(function () {
waitForEl(selector, callback, attempts);
}, 1000);
}
}
console.log(`Unable to find selector: ${selector}`);
};
waitForEl(".foo", () => {
console.log("It worked");
});
</script>
</html>
@andrewbiddinger
Copy link

The second version is giving me a "Uncaught SyntaxError: await is only valid in async function" error in the console...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment