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.js
script in your main HTML) without the need to import it on a separate line - Waits until the
triggerWhenVisibleSelector
becomes visible - Resets Cloudflare Turnstile so it can be used again
- Change the
widgetSelector
to 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
siteKey
to your site key provided by Cloudflare - Change the
triggerWhenVisibleSelector
to 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.js
and place in the appropriate directory - Import
turnstile.js
in your script before the</body>
tag:
<!-- Cloudflare Turnstile -->
<script src="turnstile.js" defer></script>