Luke Jones

intervle - resources/js/app.js

import './bootstrap'; function initialiseDifficultySelector() { const selector = document.getElementById('difficulty-selector'); const options = selector.querySelectorAll('option'); const currentGame = (window.location.pathname).split('/'); const difficulty = currentGame[1]; const date = currentGame[2]; options.forEach(option => { if (option.getAttribute('value') === difficulty) { option.selected = true; } }); selector.addEventListener('change', () => { window.location = '/' + selector.value + '/' + date; }); } document.addEventListener('DOMContentLoaded', () => { if (/^\/(easy|medium|hard)\/(today|\d{8})\/?$/.test(window.location.pathname)) { const currentDate = window.location.pathname; const eventsContainer = document.getElementById('events-container'); const eventContainers = eventsContainer.querySelectorAll('.event-container'); initialiseDifficultySelector(); function reorderItem(item, direction) { const parent = item.parentNode; if (direction === -1) { // move up const prev = item.previousElementSibling; if (prev) { parent.insertBefore(item, prev); } } if (direction === 1) { // move down const next = item.nextElementSibling; if (next) { parent.insertBefore(next, item); } } } eventContainers.forEach(eventContainer => { eventContainer.querySelector('.reorder-up-btn').addEventListener('click', () => { reorderItem(eventContainer, -1); }); eventContainer.querySelector('.reorder-down-btn').addEventListener('click', () => { reorderItem(eventContainer, 1); }); }); const submitOrderBtn = document.getElementById('submit-order-button'); if (submitOrderBtn) { const token = document.querySelector('meta[name="csrf-token"]')?.content; submitOrderBtn.addEventListener('click', () => { const order = [...document.querySelectorAll('.event-container')] .map(e => parseInt(e.dataset.event)); fetch(`${currentDate}/submit`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': token }, body: JSON.stringify({order}) }) .then(res => res.json()) .then(data => { displayResults(data) }); document.querySelectorAll('.reorder-controls').forEach(control => { control.remove() }); submitOrderBtn.remove(); }); } function displayResults(results) { let score = 0; eventsContainer.querySelectorAll('.event-container').forEach(function (eventContainer, index) { const enteredEvent = eventContainer.getAttribute('data-event'); if (results.correct_order[index] === +enteredEvent) { score++; eventContainer.className += ' event-correct'; } else { eventContainer.className += ' event-incorrect'; } }); const scoreDisplay = document.getElementById('score-display') scoreDisplay.innerHTML = ('Final Score: ' + score); scoreDisplay.className = ''; } } });