Refresh control htmx
A quick-settings button for live parts of a page: 5, 10, 30 s or Off, kept per account and page in a cookie; here it drives an htmx poll.
Options
| Option | Meaning |
|---|---|
_class('refresh_control')->render($key, $opt) | options (seconds, 0 = off), default (10), title, class; $key names the page. |
->value($key) | The chosen seconds (0 = off), for the server to render the page with. |
yf-refresh-change | Event bubbling from the control, detail = {key, seconds}: restart your timer or poll. |
Example
Updated at 02:11:30
Code
$hx = _class('htmx');
if ($hx->_wants_fragment() && ($_GET['hx'] ?? '') === 'tick') {
return $hx->_result('Updated at ' . date('H:i:s'));
}
asset('htmx');
$rc = _class('refresh_control');
$seconds = $rc->value('docs_ref_poll', 10);
// the poll follows the control without a reload: a copy of the element with the new hx-trigger replaces it
js('document.addEventListener("yf-refresh-change", function (e) {
var el = document.getElementById("docs-ref-poll");
if ( ! el || e.detail.key !== "docs_ref_poll") { return; }
var copy = el.cloneNode(true);
if (e.detail.seconds > 0) { copy.setAttribute("hx-trigger", "every " + e.detail.seconds + "s"); } else { copy.removeAttribute("hx-trigger"); }
el.replaceWith(copy);
window.htmx && window.htmx.process(copy);
});');
return $rc->render('docs_ref_poll', ['options' => [5, 10, 30, 0], 'default' => 10])
. ' <span id="docs-ref-poll" hx-get="' . _prepare_html(url('/@object/htmx/refresh_control')) . '" hx-vals=\'{"hx": "tick"}\''
. ($seconds > 0 ? ' hx-trigger="every ' . $seconds . 's"' : '') . '>Updated at ' . date('H:i:s') . '</span>';Notes
- Asset
yf_refresh_control, no jQuery; the menu is a.dropdown-menu, so Bootstrap 3 / 5, the themes and dark mode colour it; keyboard: arrows, Escape, Tab. - The admin uses it on the live log view and the OPcache page.
See also: htmx/fragment, misc:log_stream, misc:opcache