ws = new WebSocket("ws://localhost:8080"); const div = document.querySelector("#shiritori"); const input = document.querySelector("#shiritori-input"); const players = document.querySelector("#shiritori-players"); let id = null; ws.onmessage = e => { const { event, data } = JSON.parse(e.data); switch (event) { case "greeting": id = data.id; break; case "word": let waiting = data.author === id; p = document.createElement("p"); p.innerHTML = data.reading || data.word === data.reading ? (data.word === "" ? data.reading : `${data.word}(${data.reading})`) : data.word; div.appendChild(p); div.scrollTop = div.offsetHeight; input.placeholder = waiting ? "Waiting for other players..." : `${data.next_char}…`; input.disabled = waiting; if (!waiting) input.focus(); break; case "playerCount": let otherPlayers = data.players - 1; players.innerHTML = `${otherPlayers === 0 ? "No" : otherPlayers} other player${otherPlayers === 1 ? "" : "s"} online.`; break; case "error": alert(data.message); break; } } input.addEventListener('keypress', e => { if (e.key === 'Enter') { ws.send(input.value); input.value = ""; } });