Examples
Complete widgets to start from. Each has the five files; save them and use Import in the code editor (select all five at once), or copy them into the tabs.
| Example | Shows how to use |
|---|---|
| Tip goal | session data, the tip variables, onSessionUpdate |
| Counter | a variable, bot:counter |
| Chat box | chat messages, emotes, badges, deletions |
| Latest events | recents, alerts of every kind |
| Persistent tally | the store, kvstore:update, button fields |
| Alert card | alerts, the event queue, sounds and images |
Tip goal
A progress bar of tips towards a goal. The goal is the tip_goal variable (set it on the dashboard's Variables page) unless the Goal field is set.
widget.html
<div class="goal">
<div class="goal__top">
<span class="goal__title">{{title}}</span>
<span class="goal__numbers"><span id="raised">0</span> / <span id="target">0</span></span>
</div>
<div class="goal__track">
<div class="goal__bar" id="bar"></div>
</div>
</div>widget.css
* { box-sizing: border-box; }
body {
font-family: '{{fontName}}', sans-serif;
color: {{textColor}};
}
.goal {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
justify-content: center;
gap: 8px;
padding: 0 16px;
}
.goal__top {
display: flex;
justify-content: space-between;
font-size: {{fontSize}}px;
font-weight: 700;
text-shadow: 0 2px 6px rgba(0, 0, 0, 0.6);
}
.goal__track {
height: {{barHeight}}px;
border-radius: 999px;
background: {{trackColor}};
overflow: hidden;
}
.goal__bar {
width: 0;
height: 100%;
border-radius: inherit;
background: {{barColor}};
transition: width 0.8s ease;
}widget.js
/*
* Tip goal: a progress bar of tips towards a goal.
*
* The raised amount is a tip value of the session data ("tip-session",
* "tip-month", ...), the goal is the "tip_goal" variable of the dashboard
* unless the "Goal" field is set. Both are kept up to date by onSessionUpdate.
*/
let fields = {};
window.addEventListener('onWidgetLoad', (obj) => {
fields = obj.detail.fieldData;
render(obj.detail.session.data);
});
window.addEventListener('onSessionUpdate', (obj) => {
render(obj.detail.session);
});
function render(session) {
const raised = session['tip-' + fields.period].amount;
const goal = Number(fields.goalAmount) > 0 ? Number(fields.goalAmount) : session['tip-goal'].amount;
const percent = goal > 0 ? Math.min(100, (raised / goal) * 100) : 0;
document.getElementById('raised').textContent = money(raised);
document.getElementById('target').textContent = money(goal);
document.getElementById('bar').style.width = percent + '%';
}
function money(amount) {
const number = amount.toLocaleString(undefined, { maximumFractionDigits: 2 });
return fields.symbolAfter ? number + ' ' + fields.currencySymbol : fields.currencySymbol + number;
}fields.json
{
"title": { "type": "text", "label": "Title", "value": "Tip goal", "group": "Goal" },
"period": {
"type": "dropdown",
"label": "Count the tips of",
"value": "month",
"options": { "session": "This stream", "week": "This week", "month": "This month", "total": "All time" },
"group": "Goal"
},
"goalAmount": { "type": "number", "label": "Goal (0: the tip_goal variable)", "value": 0, "min": 0, "group": "Goal" },
"currencySymbol": { "type": "text", "label": "Currency symbol", "value": "€", "group": "Goal" },
"symbolAfter": { "type": "checkbox", "label": "Symbol after the amount", "value": false, "group": "Goal" },
"fontName": { "type": "googleFont", "label": "Font", "value": "Poppins", "group": "Style" },
"fontSize": { "type": "slider", "label": "Font size (px)", "value": 28, "min": 12, "max": 72, "step": 1, "group": "Style" },
"barHeight": { "type": "slider", "label": "Bar height (px)", "value": 24, "min": 4, "max": 80, "step": 1, "group": "Style" },
"textColor": { "type": "colorpicker", "label": "Text color", "value": "#ffffff", "group": "Style" },
"barColor": { "type": "colorpicker", "label": "Bar color", "value": "#ff5e5b", "group": "Style" },
"trackColor": { "type": "colorpicker", "label": "Track color", "value": "rgba(0, 0, 0, 0.45)", "group": "Style" }
}data.json
{
"title": "Tip goal",
"period": "month",
"goalAmount": 0,
"currencySymbol": "€",
"symbolAfter": false,
"fontName": "Poppins",
"fontSize": 28,
"barHeight": 24,
"textColor": "#ffffff",
"barColor": "#ff5e5b",
"trackColor": "rgba(0, 0, 0, 0.45)"
}Counter
Shows a variable, such as a death counter you change on the dashboard's Variables page, and updates the moment it changes. Create the variable first (deaths by default).
widget.html
<div class="counter">
<span class="counter__label" id="label"></span>
<span class="counter__value" id="value">0</span>
</div>widget.css
body {
font-family: '{{fontName}}', sans-serif;
}
.counter {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
gap: 0.4em;
color: {{textColor}};
font-size: {{fontSize}}px;
font-weight: 800;
text-shadow: 0 3px 8px rgba(0, 0, 0, 0.6);
}
.counter__value {
color: {{accentColor}};
font-variant-numeric: tabular-nums;
}
.counter__value.is-bumped {
animation: bump 0.4s ease-out;
}
@keyframes bump {
40% { transform: scale(1.35); }
}widget.js
/*
* Counter: shows a variable of the dashboard's Variables page, e.g. a death
* counter, and updates the moment it changes there.
*
* Variables are read with SE_API.counters.get(); every change arrives as a
* "bot:counter" event. Widgets can read variables but not change them.
*/
let fields = {};
let variableName = '';
window.addEventListener('onWidgetLoad', (obj) => {
fields = obj.detail.fieldData;
variableName = String(fields.variable || '').trim().toLowerCase();
document.getElementById('label').textContent = fields.label;
SE_API.counters.get(variableName).then((counter) => show(counter.value, false));
});
window.addEventListener('onEventReceived', (obj) => {
const { listener, event } = obj.detail;
if (listener === 'bot:counter' && event.counter === variableName) show(event.value, true);
});
function show(value, animate) {
const el = document.getElementById('value');
el.textContent = value;
if (!animate) return;
el.classList.remove('is-bumped');
void el.offsetWidth; // restart the animation
el.classList.add('is-bumped');
}fields.json
{
"variable": { "type": "text", "label": "Variable name", "value": "deaths", "group": "Counter" },
"label": { "type": "text", "label": "Label", "value": "Deaths:", "group": "Counter" },
"fontName": { "type": "googleFont", "label": "Font", "value": "Bebas Neue", "group": "Style" },
"fontSize": { "type": "slider", "label": "Font size (px)", "value": 64, "min": 16, "max": 160, "step": 1, "group": "Style" },
"textColor": { "type": "colorpicker", "label": "Label color", "value": "#ffffff", "group": "Style" },
"accentColor": { "type": "colorpicker", "label": "Number color", "value": "#ff4d6d", "group": "Style" }
}data.json
{
"variable": "deaths",
"label": "Deaths:",
"fontName": "Bebas Neue",
"fontSize": 64,
"textColor": "#ffffff",
"accentColor": "#ff4d6d"
}Chat box
Twitch and YouTube chat with badges and emotes. Messages that moderators delete disappear, and so do those of timed out or banned viewers.
widget.html
<div id="chat" class="chat"></div>widget.css
* { box-sizing: border-box; }
body {
font-family: '{{fontName}}', sans-serif;
}
/* Newest at the bottom; old messages scroll out at the top */
.chat {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
justify-content: flex-end;
gap: 6px;
padding: 12px;
overflow: hidden;
font-size: {{fontSize}}px;
}
.chat__row {
padding: 6px 10px;
border-radius: 8px;
background: {{rowColor}};
color: {{textColor}};
line-height: 1.35;
overflow-wrap: anywhere;
animation: row-in 0.25s ease-out;
}
.chat__row.is-leaving {
opacity: 0;
transition: opacity 0.4s;
}
.chat__badge {
height: 1em;
margin-right: 4px;
vertical-align: -0.12em;
}
.chat__name {
font-weight: 700;
}
.chat__text .emote {
height: 1.6em;
vertical-align: middle;
}
@keyframes row-in {
from { opacity: 0; transform: translateY(8px); }
}widget.js
/*
* Chat box: chat messages of Twitch and YouTube, with badges and emotes.
* Messages deleted by moderators, and those of timed out or banned viewers,
* are removed.
*
* Names and texts are written by viewers: names are inserted as text, the
* message as event.renderedText, which Streamed has escaped (safe as HTML).
*/
let fields = {};
let ignored = [];
window.addEventListener('onWidgetLoad', (obj) => {
fields = obj.detail.fieldData;
ignored = String(fields.ignoreNames || '')
.split(',')
.map((name) => name.trim().toLowerCase())
.filter(Boolean);
if (obj.detail.overlay.isEditorMode) {
addMessage(sampleMessage('StreamFan', 'Messages show up here.'));
addMessage(sampleMessage('ModeratorMia', 'Try a test chat message with the ▶ button.'));
}
});
window.addEventListener('onEventReceived', (obj) => {
const { listener, event } = obj.detail;
if (listener === 'message') {
const nick = event.data.nick;
if (ignored.includes(nick) || ignored.includes(event.data.displayName.toLowerCase())) return;
if (fields.hideCommands && event.data.text.startsWith('!')) return;
addMessage(event);
} else if (listener === 'delete-message') {
removeRows('[data-msg-id="' + CSS.escape(event.msgId) + '"]');
} else if (listener === 'delete-messages') {
removeRows('[data-user-id="' + CSS.escape(event.userId) + '"]');
}
});
function addMessage(event) {
const chat = document.getElementById('chat');
const row = document.createElement('div');
row.className = 'chat__row';
row.dataset.msgId = event.data.msgId;
row.dataset.userId = event.data.userId;
if (fields.showBadges) {
event.data.badges
.filter((badge) => badge.url)
.forEach((badge) => {
const img = document.createElement('img');
img.className = 'chat__badge';
img.src = badge.url;
img.alt = badge.description;
row.appendChild(img);
});
}
const name = document.createElement('span');
name.className = 'chat__name';
name.textContent = event.data.displayName;
name.style.color = event.data.displayColor || fields.nameColor;
const text = document.createElement('span');
text.className = 'chat__text';
text.innerHTML = event.renderedText; // escaped by Streamed
row.append(name, document.createTextNode(event.data.isAction ? ' ' : ': '), text);
if (event.data.isAction) text.style.fontStyle = 'italic';
chat.appendChild(row);
// Keep at most maxMessages rows
while (chat.children.length > Number(fields.maxMessages)) chat.firstElementChild.remove();
const hideAfter = Number(fields.hideAfter) * 1000;
if (hideAfter > 0) setTimeout(() => fadeOut(row), hideAfter);
}
function removeRows(selector) {
document.querySelectorAll(selector).forEach(fadeOut);
}
function fadeOut(row) {
row.classList.add('is-leaving');
setTimeout(() => row.remove(), 400);
}
function sampleMessage(displayName, text) {
return {
data: { msgId: '', userId: '', displayName, displayColor: '', badges: [], text, isAction: false, nick: displayName.toLowerCase() },
renderedText: text.replace(/[&<>"']/g, (c) => '&#' + c.charCodeAt(0) + ';'),
};
}fields.json
{
"maxMessages": { "type": "number", "label": "Messages shown at most", "value": 12, "min": 1, "max": 100, "step": 1, "group": "Messages" },
"hideAfter": { "type": "number", "label": "Hide after (seconds, 0: never)", "value": 0, "min": 0, "max": 600, "step": 1, "group": "Messages" },
"showBadges": { "type": "checkbox", "label": "Show badges", "value": true, "group": "Messages" },
"hideCommands": { "type": "checkbox", "label": "Hide !commands", "value": true, "group": "Messages" },
"ignoreNames": { "type": "textarea", "label": "Ignore these names (comma separated, e.g. bots)", "value": "streamelements, nightbot", "group": "Messages" },
"fontName": { "type": "googleFont", "label": "Font", "value": "Inter", "group": "Style" },
"fontSize": { "type": "slider", "label": "Font size (px)", "value": 20, "min": 10, "max": 48, "step": 1, "group": "Style" },
"textColor": { "type": "colorpicker", "label": "Text color", "value": "#ffffff", "group": "Style" },
"nameColor": { "type": "colorpicker", "label": "Name color (when the viewer has none)", "value": "#bf94ff", "group": "Style" },
"rowColor": { "type": "colorpicker", "label": "Message background", "value": "rgba(0, 0, 0, 0.55)", "group": "Style" }
}data.json
{
"maxMessages": 12,
"hideAfter": 0,
"showBadges": true,
"hideCommands": true,
"ignoreNames": "streamelements, nightbot",
"fontName": "Inter",
"fontSize": 20,
"textColor": "#ffffff",
"nameColor": "#bf94ff",
"rowColor": "rgba(0, 0, 0, 0.55)"
}Latest events
The newest follows, subscriptions, cheers, raids, tips, memberships and Super Chats: the recent ones when it loads, new ones as they come.
widget.html
<ul id="list" class="events"></ul>widget.css
* { box-sizing: border-box; }
body {
font-family: '{{fontName}}', sans-serif;
}
.events {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
gap: 6px;
margin: 0;
padding: 12px;
list-style: none;
overflow: hidden;
font-size: {{fontSize}}px;
}
.events__item {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 8px 12px;
border-left: 4px solid {{accentColor}};
border-radius: 6px;
background: {{rowColor}};
color: {{textColor}};
}
.events__item.is-new {
animation: item-in 0.5s ease-out;
}
.events__name {
overflow: hidden;
font-weight: 700;
text-overflow: ellipsis;
white-space: nowrap;
}
.events__what {
flex-shrink: 0;
opacity: 0.8;
}
@keyframes item-in {
from { opacity: 0; transform: translateX(-24px); }
}widget.js
/*
* Latest events: a list of the newest follows, subscriptions, cheers, raids,
* tips, memberships and Super Chats. It starts with the recent events of
* onWidgetLoad and adds new ones as they come in.
*/
let fields = {};
// Event type → its checkbox field
const SHOWN = {
follower: 'showFollows',
subscriber: 'showSubs',
sponsor: 'showSubs',
cheer: 'showCheers',
raid: 'showRaids',
tip: 'showTips',
superchat: 'showTips',
};
window.addEventListener('onWidgetLoad', (obj) => {
fields = obj.detail.fieldData;
// recents: newest first, so add them from the oldest on
obj.detail.recents
.filter(isShown)
.slice(0, Number(fields.maxItems))
.reverse()
.forEach((event) => add(event, false));
});
window.addEventListener('onEventReceived', (obj) => {
const { listener, event } = obj.detail;
if (listener.endsWith('-latest') && isShown(event)) add(event, true);
});
function isShown(event) {
return Boolean(fields[SHOWN[event.type]]);
}
function add(event, isNew) {
const list = document.getElementById('list');
const item = document.createElement('li');
item.className = 'events__item' + (isNew ? ' is-new' : '');
const name = document.createElement('span');
name.className = 'events__name';
name.textContent = event.name; // written by a viewer: text only
const what = document.createElement('span');
what.className = 'events__what';
what.textContent = describe(event);
item.append(name, what);
list.prepend(item);
while (list.children.length > Number(fields.maxItems)) list.lastElementChild.remove();
}
function describe(event) {
const amount = Number(event.amount) || 0;
switch (event.type) {
case 'follower':
return 'follow';
case 'subscriber':
if (event.platform === 'youtube') return 'subscriber';
if (event.bulkGifted) return amount + ' gifted subs';
return amount > 1 ? amount + ' months' : 'sub';
case 'sponsor':
return amount > 1 ? 'member, ' + amount + ' months' : 'member';
case 'cheer':
return amount + ' bits';
case 'raid':
return amount + ' raiders';
case 'tip':
case 'superchat':
// recents have no currency, live events do
return (event.currency ? event.currency + ' ' : '') + amount.toLocaleString(undefined, { maximumFractionDigits: 2 });
default:
return event.type;
}
}fields.json
{
"maxItems": { "type": "number", "label": "Events shown", "value": 5, "min": 1, "max": 25, "step": 1, "group": "Events" },
"showFollows": { "type": "checkbox", "label": "Follows", "value": true, "group": "Events" },
"showSubs": { "type": "checkbox", "label": "Subscriptions and memberships", "value": true, "group": "Events" },
"showCheers": { "type": "checkbox", "label": "Cheers", "value": true, "group": "Events" },
"showRaids": { "type": "checkbox", "label": "Raids", "value": true, "group": "Events" },
"showTips": { "type": "checkbox", "label": "Tips and Super Chats", "value": true, "group": "Events" },
"fontName": { "type": "googleFont", "label": "Font", "value": "Poppins", "group": "Style" },
"fontSize": { "type": "slider", "label": "Font size (px)", "value": 20, "min": 10, "max": 48, "step": 1, "group": "Style" },
"textColor": { "type": "colorpicker", "label": "Text color", "value": "#ffffff", "group": "Style" },
"accentColor": { "type": "colorpicker", "label": "Accent color", "value": "#9147ff", "group": "Style" },
"rowColor": { "type": "colorpicker", "label": "Row background", "value": "rgba(14, 14, 16, 0.8)", "group": "Style" }
}data.json
{
"maxItems": 5,
"showFollows": true,
"showSubs": true,
"showCheers": true,
"showRaids": true,
"showTips": true,
"fontName": "Poppins",
"fontSize": 20,
"textColor": "#ffffff",
"accentColor": "#9147ff",
"rowColor": "rgba(14, 14, 16, 0.8)"
}Persistent tally
A number you change with buttons in the widget's settings (+1, −1, reset). It is kept in the store, so it survives reloads, and every copy of the widget shows the same number.
widget.html
<div class="tally">
<span class="tally__label">{{label}}</span>
<span class="tally__count" id="count">0</span>
</div>widget.css
body {
font-family: '{{fontName}}', sans-serif;
}
.tally {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
gap: 0.4em;
color: {{textColor}};
font-size: {{fontSize}}px;
font-weight: 800;
text-shadow: 0 3px 8px rgba(0, 0, 0, 0.6);
}
.tally__count {
color: {{accentColor}};
font-variant-numeric: tabular-nums;
}widget.js
/*
* Persistent tally: a number you change with the buttons in the widget's
* settings (+1, -1, reset). It is kept in the store, so it survives reloads,
* and every open copy of the widget shows the same number.
*
* A button click reaches every open copy of the widget (the editor's preview
* and OBS). Only the preview saves, so one click counts once; the other
* copies take the new number from the "kvstore:update" event.
*/
let fields = {};
let isEditor = false;
let count = 0;
window.addEventListener('onWidgetLoad', (obj) => {
fields = obj.detail.fieldData;
isEditor = obj.detail.overlay.isEditorMode;
SE_API.store.get(storeKey()).then((value) => show(Number(value) || 0));
});
window.addEventListener('onEventReceived', (obj) => {
const { listener, event } = obj.detail;
if (listener === 'widget-button' && isEditor) {
if (event.field === 'plusOne') save(count + 1);
if (event.field === 'minusOne') save(Math.max(0, count - 1));
if (event.field === 'reset') save(0);
}
// Saved by this or another widget: the store's keys arrive with "customWidget."
if (listener === 'kvstore:update' && event.data.key === 'customWidget.' + storeKey()) {
show(Number(event.data.value) || 0);
}
});
function storeKey() {
// 1-64 letters, digits, "_" or "-"
return String(fields.storeKey || 'tally').replace(/[^A-Za-z0-9_-]/g, '').slice(0, 64) || 'tally';
}
function save(value) {
show(value);
SE_API.store.set(storeKey(), value);
}
function show(value) {
count = value;
document.getElementById('count').textContent = value;
}fields.json
{
"plusOne": { "type": "button", "label": "+1", "value": "plus" },
"minusOne": { "type": "button", "label": "−1", "value": "minus" },
"reset": { "type": "button", "label": "Reset to 0", "value": "reset" },
"label": { "type": "text", "label": "Label", "value": "Wins:", "group": "Tally" },
"storeKey": { "type": "text", "label": "Store key (widgets with the same key share the number)", "value": "wins", "group": "Tally" },
"fontName": { "type": "googleFont", "label": "Font", "value": "Bebas Neue", "group": "Style" },
"fontSize": { "type": "slider", "label": "Font size (px)", "value": 64, "min": 16, "max": 160, "step": 1, "group": "Style" },
"textColor": { "type": "colorpicker", "label": "Label color", "value": "#ffffff", "group": "Style" },
"accentColor": { "type": "colorpicker", "label": "Number color", "value": "#37d67a", "group": "Style" }
}data.json
{
"label": "Wins:",
"storeKey": "wins",
"fontName": "Bebas Neue",
"fontSize": 64,
"textColor": "#ffffff",
"accentColor": "#37d67a"
}Alert card
The example every new custom widget starts with: an alert card for follows, subscriptions, cheers and raids, with an optional image and sound. It uses the event queue (widgetDuration) to show alerts one at a time.
widget.html
<!--
Event Alert Card: an example custom widget.
Field values from the Fields / Data tabs can be used anywhere in HTML, CSS
and JS as {{fieldName}}. Here the "animation" dropdown picks a CSS class.
-->
<div id="alert" class="alert alert--{{animation}}" hidden>
<img id="alert-image" class="alert__image" alt="" hidden>
<div class="alert__body">
<div id="alert-title" class="alert__title"></div>
<div id="alert-name" class="alert__name"></div>
<div id="alert-message" class="alert__message"></div>
</div>
</div>widget.css
/*
* {{fieldName}} placeholders are replaced with the field values before the
* widget loads. Fonts chosen in a "googleFont" field are loaded automatically.
*/
* {
box-sizing: border-box;
}
body {
font-family: '{{fontName}}', sans-serif;
}
.alert {
position: absolute;
top: 40px;
left: 50%;
display: flex;
align-items: center;
gap: 20px;
min-width: 420px;
max-width: 90vw;
padding: 20px 28px;
border-left: 8px solid {{accentColor}};
border-radius: 18px;
background: {{cardColor}};
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.35);
color: {{textColor}};
font-size: {{fontSize}}px;
transform: translateX(-50%);
}
.alert[hidden] {
display: none;
}
.alert__image {
width: 96px;
height: 96px;
object-fit: contain;
}
.alert__title {
color: {{accentColor}};
font-size: 0.6em;
font-weight: 600;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.alert__name {
font-weight: 700;
}
.alert__message {
margin-top: 4px;
font-size: 0.55em;
opacity: 0.85;
}
.alert__message:empty {
display: none;
}
/* ── Animations, picked with the "animation" dropdown ───────────────────── */
.alert--slide.is-visible { animation: slide-in 0.6s cubic-bezier(0.2, 0.9, 0.3, 1.2) both; }
.alert--slide.is-leaving { animation: slide-out 0.5s ease-in both; }
.alert--pop.is-visible { animation: pop-in 0.5s cubic-bezier(0.2, 0.9, 0.3, 1.4) both; }
.alert--pop.is-leaving { animation: pop-out 0.4s ease-in both; }
.alert--fade.is-visible { animation: fade-in 0.6s ease-out both; }
.alert--fade.is-leaving { animation: fade-out 0.5s ease-in both; }
@keyframes slide-in { from { opacity: 0; transform: translate(-50%, -120%); } to { opacity: 1; transform: translate(-50%, 0); } }
@keyframes slide-out { from { opacity: 1; transform: translate(-50%, 0); } to { opacity: 0; transform: translate(-50%, -120%); } }
@keyframes pop-in { from { opacity: 0; transform: translateX(-50%) scale(0.6); } to { opacity: 1; transform: translateX(-50%) scale(1); } }
@keyframes pop-out { from { opacity: 1; transform: translateX(-50%) scale(1); } to { opacity: 0; transform: translateX(-50%) scale(0.6); } }
@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
@keyframes fade-out { from { opacity: 1; } to { opacity: 0; } }widget.js
/*
* Event Alert Card: an example custom widget.
*
* Custom widgets use the same API as StreamElements custom widgets:
* onWidgetLoad fired once, with fieldData (your settings), session data
* and recent events
* onEventReceived fired for every event: follows, subs, cheers, raids,
* button fields clicked in the editor, ...
* SE_API store, resumeQueue and other helpers
* jQuery is available as $ if you prefer it.
*/
let fields = {};
// Which text field holds the title for each event type
const TITLE_FIELDS = {
follower: 'titleFollower',
subscriber: 'titleSubscriber',
cheer: 'titleCheer',
raid: 'titleRaid',
};
window.addEventListener('onWidgetLoad', (obj) => {
fields = obj.detail.fieldData;
const image = document.getElementById('alert-image');
if (fields.alertImage) {
image.src = fields.alertImage;
image.hidden = false;
}
});
window.addEventListener('onEventReceived', (obj) => {
const { listener, event } = obj.detail;
// The "Send test alert" button in the widget settings
if (listener === 'widget-button' && event.field === 'testAlert') {
showAlert({ type: 'follower', name: 'TestUser' });
return;
}
// Alerts arrive as "<type>-latest" listeners (follower-latest, ...)
if (!listener.endsWith('-latest')) return;
// A gift bundle arrives as one event for the whole bundle (bulkGifted),
// then one per recipient (isCommunityGift). Show the bundle only.
if (!TITLE_FIELDS[event.type] || event.isCommunityGift) {
// Not an event this widget shows: let the next queued event play
SE_API.resumeQueue();
return;
}
showAlert(event);
});
function showAlert(event) {
const alert = document.getElementById('alert');
// Names and messages are written by viewers. Always insert them as text
// (textContent), never as HTML (innerHTML).
document.getElementById('alert-title').textContent = fields[TITLE_FIELDS[event.type]] || '';
document.getElementById('alert-name').textContent = describe(event);
document.getElementById('alert-message').textContent = fields.showMessage ? event.message || '' : '';
playSound();
alert.hidden = false;
alert.classList.remove('is-leaving');
void alert.offsetWidth; // restart the CSS animation
alert.classList.add('is-visible');
const displayMs = (Number(fields.displaySeconds) || 5) * 1000;
setTimeout(() => {
alert.classList.replace('is-visible', 'is-leaving');
setTimeout(() => {
alert.hidden = true;
alert.classList.remove('is-leaving');
// Done: play the next queued event right away instead of waiting
// for the full "widgetDuration"
SE_API.resumeQueue();
}, 600);
}, displayMs);
}
function describe(event) {
switch (event.type) {
case 'subscriber':
// A bundle: amount is the number of gifts, not months
if (event.bulkGifted) return `${event.name} gifted ${event.amount} subs`;
// A single gift: name is the recipient, sender the gifter
if (event.gifted && event.sender) return `${event.name} (gift from ${event.sender})`;
return event.amount > 1 ? `${event.name} (${event.amount} months)` : event.name;
case 'cheer':
return `${event.name}: ${event.amount} bits`;
case 'raid':
return `${event.name} with ${event.amount} viewers`;
default:
return event.name;
}
}
function playSound() {
if (!fields.alertSound) return;
const audio = new Audio(fields.alertSound);
audio.volume = Number(fields.soundVolume) || 0.5;
audio.play().catch(() => {});
}fields.json
{
"titleFollower": {
"type": "text",
"label": "Follower title",
"value": "New follower!",
"group": "Texts"
},
"titleSubscriber": {
"type": "text",
"label": "Subscriber title",
"value": "New subscriber!",
"group": "Texts"
},
"titleCheer": {
"type": "text",
"label": "Cheer title",
"value": "Cheer!",
"group": "Texts"
},
"titleRaid": {
"type": "text",
"label": "Raid title",
"value": "Incoming raid!",
"group": "Texts"
},
"showMessage": {
"type": "checkbox",
"label": "Show the viewer's message",
"value": true,
"group": "Texts"
},
"fontName": {
"type": "googleFont",
"label": "Font",
"value": "Poppins",
"group": "Style"
},
"fontSize": {
"type": "slider",
"label": "Font size (px)",
"value": 32,
"min": 16,
"max": 72,
"step": 1,
"group": "Style"
},
"textColor": {
"type": "colorpicker",
"label": "Text color",
"value": "#ffffff",
"group": "Style"
},
"accentColor": {
"type": "colorpicker",
"label": "Accent color",
"value": "#9147ff",
"group": "Style"
},
"cardColor": {
"type": "colorpicker",
"label": "Card background",
"value": "rgba(20, 20, 28, 0.85)",
"group": "Style"
},
"animation": {
"type": "dropdown",
"label": "Animation",
"value": "slide",
"options": {
"slide": "Slide in",
"pop": "Pop",
"fade": "Fade"
},
"group": "Style"
},
"alertImage": {
"type": "image-input",
"label": "Image (optional)",
"value": "",
"group": "Media"
},
"alertSound": {
"type": "sound-input",
"label": "Sound (optional)",
"value": "",
"group": "Media"
},
"soundVolume": {
"type": "slider",
"label": "Volume",
"value": 0.5,
"min": 0,
"max": 1,
"step": 0.05,
"group": "Media"
},
"displaySeconds": {
"type": "number",
"label": "Display time (seconds)",
"value": 5,
"min": 1,
"max": 30,
"step": 1,
"group": "Timing"
},
"testAlert": {
"type": "button",
"label": "Send test alert",
"value": "test"
},
"widgetName": {
"type": "hidden",
"value": "Event Alert Card"
},
"widgetAuthor": {
"type": "hidden",
"value": "Streamed"
},
"widgetDuration": {
"type": "hidden",
"value": 30
}
}data.json
{
"titleFollower": "New follower!",
"titleSubscriber": "New subscriber!",
"titleCheer": "Cheer!",
"titleRaid": "Incoming raid!",
"showMessage": true,
"fontName": "Poppins",
"fontSize": 32,
"textColor": "#ffffff",
"accentColor": "#9147ff",
"cardColor": "rgba(20, 20, 28, 0.85)",
"animation": "slide",
"alertImage": "",
"alertSound": "",
"soundVolume": 0.5,
"displaySeconds": 5
}