Easily load and reset Cloudflare Turnstile when an element (div/span) appears. For example, when success element is shown, reset Cloudflare Turnstile.
The purpose of this script is to handle the situation where you want to reset Cloudflare Turnstile after a contact form was submitted, so that someone could submit the form again without having to reload the page.
- Loads Cloudflare Turnstile dynamically (only import this
turnstile.jsscript in your main HTML) without the need to import it on a separate line - Waits until the
triggerWhenVisibleSelectorbecomes visible - Resets Cloudflare Turnstile so it can be used again
- Change the
widgetSelectorto the ID (or class) of the container that will hold the Turnstile widget that will by dynamically rendered. In the following example you would use#turnstile-container:
<div id="turnstile-container">
<!-- When rendered, Turnstile will appear here -->
</div>- Change the
siteKeyto your site key provided by Cloudflare - Change the
triggerWhenVisibleSelectorto the query selector of the element that, when becoming visible, should trigger the reset of Turnstile. In the following example you would use.u-form-send-success:
<div class="u-form-send-success">
Thank you! Your message has been sent.
</div>- Save
turnstile.jsand place in the appropriate directory - Import
turnstile.jsin your script before the</body>tag:
<!-- Cloudflare Turnstile -->
<script src="turnstile.js" defer></script>