HTML test site: https://www.tutorialrepublic.com/codelab.php validator.w3.org/#validate_by_input htmledit.squarefree.com Cheatsheet: https://pbs.twimg.com/media/FDTBjF5XEAkI6ZZ?format=jpg&name=large BlueGriffon (WYSIWYG Editor that doesn't break CSS) https://www.duplichecker.com/domain-age-checker.php [0HTML examples Backup: GDRIVE:/HTML/00_HTML ] =================== https://ry3yr.github.io/OSTR/release/other/Computerstuff/Commands/CSS_Examples.txt *html-unicodecharas *brk-nz *html-knowledge *host-website *java-scriptz Akkoma Post resolver ------------------ API Key Form


_______________________ Akkoma API Key Generator ------------------------- Akkoma API Key Generator

Akkoma API Key Generator











Generated API Key



    






Parceltrack 
-----------------


    
    
    Parceltrack
    

Parcel Track

________________ Song Duration changer (Nightcore-ify) ft.ffmpeg ------------------------------------------------ drag and drop song, enter new desired duration, press button, bam (oh and a lil chipmunk button, incase you wanna go full nightcore)

Audio Speed Adjuster
Drop your audio file here
__________________________________ Line Compare Tool (For File Safety Check) -------------------------------------- Line Checker

Line Cleaner

__________________________ mtd toot display ------------------------- Mastodon Toot Display
API URL: Loading...
Loading toot...
__________________ Mastodon API Poster (with emoji support and url gen on post) ---------------------------------------------------- Mastodon Post Privacy with Emoji Picker, Search, and URL Display

Emoji Picker

Create Mastodon Post

Enter your Mastodon instance URL and access token, then write your post and select the visibility.

_______________________________ Img-to-base64-html-embed ----------------------------- Image Upload and Download as HTML

Upload an Image and embed into *.html





_____________________ All images drawn chart (requires same server or cors) ----------------------------------------------------- Date Chart
php version <?php $url = "https://alcea-wisteria.de/artbackup/"; $html = file_get_contents($url); //$pattern = '/<tr>(.*?)<\/tr>/s'; //timestamp based $pattern = '/<td data-sort="([^"]*)"/'; //filename based preg_match_all($pattern, $html, $matches); $dates = array(); $urls = array(); foreach ($matches[0] as $match) { preg_match('/\d{4}-\d{2}-\d{2}/', $match, $date); if (!empty($date)) { $dates[] = $date[0]; $urls[] = $date[0]; // Append the date to the URL } } $newestIndex = array_search(max($dates), $dates); $newestUrl = $urls[$newestIndex]; // Weekly counts $weekCounts = array(); foreach ($dates as $date) { $weekYear = date('o-\WW', strtotime($date)); // Extract the year and week number if (isset($weekCounts[$weekYear])) { $weekCounts[$weekYear]++; } else { $weekCounts[$weekYear] = 1; } } $startDate = min(array_keys($weekCounts)); $endDate = date('o-\WW'); // Get the current year-week $currentDate = $startDate; while ($currentDate <= $endDate) { if (!isset($weekCounts[$currentDate])) { $weekCounts[$currentDate] = 0; } $currentDate = date('o-\WW', strtotime($currentDate . ' +1 week')); } ksort($weekCounts); $weekLabels = array_keys($weekCounts); $weekData = array_values($weekCounts); // Monthly counts $monthCounts = array(); foreach ($dates as $date) { $monthYear = date('Y-m', strtotime($date)); // Extract the year and month if (isset($monthCounts[$monthYear])) { $monthCounts[$monthYear]++; } else { $monthCounts[$monthYear] = 1; } } $startDate = min(array_keys($monthCounts)); $endDate = date('Y-m'); // Get the current year-month $currentDate = $startDate; while ($currentDate <= $endDate) { if (!isset($monthCounts[$currentDate])) { $monthCounts[$currentDate] = 0; } $currentDate = date('Y-m', strtotime($currentDate . ' +1 month')); } ksort($monthCounts); $monthLabels = array_keys($monthCounts); $monthData = array_values($monthCounts); ?> <!DOCTYPE html> <html> <head> <title>Date Chart</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <button onclick="switchView('week')">Weekly View</button> <button onclick="switchView('month')">Monthly View</button> <canvas id="myChart"></canvas> <script> var weekLabels = <?php echo json_encode($weekLabels); ?>; var weekData = <?php echo json_encode($weekData); ?>; var monthLabels = <?php echo json_encode($monthLabels); ?>; var monthData = <?php echo json_encode($monthData); ?>; var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: weekLabels, datasets: [{ label: 'Counts Per Week (Latest: <?php echo $newestUrl; ?>)', data: weekData, backgroundColor: 'rgba(75, 192, 192, 0.2)', borderColor: 'rgba(75, 192, 192, 1)', borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true, stepSize: 1 } }, plugins: { tooltip: { callbacks: { label: function(context) { var label = context.dataset.label || ''; var value = context.parsed.y; var tooltipLabel = 'Value: ' + value; // Customize the tooltip label here return tooltipLabel; } } } } } }); function switchView(view) { if (view === 'week') { myChart.data.labels = weekLabels; myChart.data.datasets[0].data = weekData; myChart.data.datasets[0].label = 'Counts Per Week (Latest: <?php echo $newestUrl; ?>)'; } else if (view === 'month') { myChart.data.labels = monthLabels; myChart.data.datasets[0].data = monthData; myChart.data.datasets[0].label = 'Counts Per Month (Latest: <?php echo $newestUrl; ?>)'; } myChart.update(); } </script> </body> </html> ______________________________ Unit 8 Array convert (from javascript) -------------------------------------- To convert unit8 and arrays of such nature from javascript console back into human readable form:<br> <!DOCTYPE html> <html> <head> <title>Unit8 Array Converter</title> <style> body { font-family: Arial, sans-serif; text-align: center; padding: 20px; } textarea { padding: 10px; font-size: 16px; width: 400px; height: 150px; } button { padding: 10px 20px; font-size: 16px; background-color: #4CAF50; color: white; border: none; cursor: pointer; } #output { margin-top: 20px; font-size: 18px; white-space: pre-wrap; } </style<!DOCTYPE html> <html> <head> <title>Unit8 Array Converter</title> <style> /* Same CSS as before */ </style> </head> <body> <h1>Unit8 Array Converter</h1> <textarea id="input-text" placeholder="Enter a unit8 array in one of the following formats: 1. Array of numbers: [60, 33, 68, 79, ...] 2. Typed Array: new Uint8Array([60, 33, 68, 79, ...]) 3. ArrayBuffer: new ArrayBuffer(16) with individual values set 4. DataView: new DataView(new ArrayBuffer(16)) with individual values set 5. JavaScript object with numeric keys: { '0': 60, '1': 33, '2': 68, '3': 79, ... }"></textarea> <button onclick="convertArray()">Convert</button> <div id="output"></div> <script> function convertArray() { const inputText = document.getElementById("input-text").value.trim(); try { let unit8Array; // Try parsing as a regular array of numbers try { unit8Array = JSON.parse(inputText); if (Array.isArray(unit8Array) && unit8Array.every(Number.isInteger) && unit8Array.every(value => value >= 0 && value <= 255)) { unit8Array = new Uint8Array(unit8Array); } else { unit8Array = null; } } catch (error) { unit8Array = null; } // Try parsing as a Uint8Array if (!unit8Array) { try { if (inputText.startsWith('new Uint8Array')) { unit8Array = eval(inputText); } else { unit8Array = null; } } catch (error) { unit8Array = null; } } // Try parsing as an ArrayBuffer if (!unit8Array) { try { if (inputText.startsWith('new ArrayBuffer')) { const buffer = eval(inputText); if (buffer instanceof ArrayBuffer) { unit8Array = new Uint8Array(buffer); } else { unit8Array = null; } } else { unit8Array = null; } } catch (error) { unit8Array = null; } } // Try parsing as a DataView if (!unit8Array) { try { if (inputText.startsWith('new DataView')) { const view = eval(inputText); if (view instanceof DataView) { const buffer = view.buffer; unit8Array = new Uint8Array(buffer); } else { unit8Array = null; } } else { unit8Array = null; } } catch (error) { unit8Array = null; } } // Try parsing as a JavaScript object with numeric keys if (!unit8Array) { try { const obj = JSON.parse(inputText); if (typeof obj === 'object' && obj !== null && Object.keys(obj).every(key => /^\d+$/.test(key) && obj[key] >= 0 && obj[key] <= 255)) { const values = Object.values(obj); unit8Array = new Uint8Array(values); } else { unit8Array = null; } } catch (error) { unit8Array = null; } } if (unit8Array) { const readableText = new TextDecoder().decode(unit8Array); document.getElementById("output").textContent = readableText; } else { document.getElementById("output").textContent = "Error: Invalid input. Please enter a valid unit8 array."; } } catch (error) { document.getElementById("output").textContent = "Error: Invalid input. Please enter a valid unit8 array."; } } </script> </body> </html> ________________________________________ Load website from Zip (Service woker approach) - https://codepen.io/ryedai1/pen/MWMWpNr (complex8) ----------------------------------------------- ==index.html== <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Intercept All Requests</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js"></script> <script> async function loadZipAndCreateFileMap() { const response = await fetch('https://alcea-wisteria.de/z_files/alceawis.de.zip'); const blob = await response.blob(); const zip = await JSZip.loadAsync(blob); const fileMap = {}; const filePromises = []; zip.forEach((relativePath, zipEntry) => { const filePromise = zipEntry.async('blob').then(blob => { fileMap['/' + relativePath] = blob; }); filePromises.push(filePromise); }); await Promise.all(filePromises); return fileMap; } if ('serviceWorker' in navigator) { loadZipAndCreateFileMap().then(fileMap => { navigator.serviceWorker.register('/service-worker.js').then(registration => { console.log('Service Worker registered with scope:', registration.scope); navigator.serviceWorker.ready.then(swRegistration => { const channel = new MessageChannel(); channel.port1.onmessage = event => { if (event.data === 'SW_READY') { swRegistration.active.postMessage({ type: 'FILE_MAP', fileMap: fileMap }); fetch('index.html').then(response => response.text()).then(html => { document.body.innerHTML = html; }); } }; swRegistration.active.postMessage('INIT', [channel.port2]); }); }).catch(error => { console.log('Service Worker registration failed:', error); }); }); } </script> </head> <body> <h1>Loading...</h1> </body> </html> === service-worker.js== let fileMap = {}; self.addEventListener('message', event => { if (event.data === 'INIT') { event.ports[0].postMessage('SW_READY'); } else if (event.data.type === 'FILE_MAP') { fileMap = event.data.fileMap; } }); self.addEventListener('fetch', event => { const url = new URL(event.request.url); console.log('Intercepted request:', event.request); if (fileMap[url.pathname]) { event.respondWith( Promise.resolve(fileMap[url.pathname]).then(blob => new Response(blob)) ); } else { event.respondWith(fetch(event.request)); } }); Load website from Zip (direct) - https://codepen.io/ryedai1/pen/jOjNjVR ----------------------------------------------- <a target="_blank" href="https://codepen.io/ryedai1/pen/abMraqm" style=color:blue>Take1</a><br> https://github.com/gkjohnson/client-side-zip-server https://github.com/Touffy/client-zip <!---https://stackoverflow.com/questions/27304992/how-to-extract-a-zip-file-and-render-the-contents-client-side--> <!DOCTYPE html> <html> <head> <title>JSZip Example</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js"></script> <script> // Check if JSZip is available, otherwise load local copy if (typeof JSZip === 'undefined') { document.write('<script src="jszip.min.js"><\/script>'); } document.addEventListener("DOMContentLoaded", async function () { const url = "https://alcea-wisteria.de/z_files/alceawis.de.zip"; const fileListElement = document.getElementById("file-list"); function sanitizeFileName(fileName) { return fileName.replace(/[^a-zA-Z0-9.-]/g, '_'); } async function getFileType(fileName) { const extension = fileName.split('.').pop().toLowerCase(); switch (extension) { case 'html': case 'htm': return 'text/html'; case 'css': return 'text/css'; case 'js': return 'application/javascript'; case 'json': return 'application/json'; case 'png': return 'image/png'; case 'jpg': case 'jpeg': return 'image/jpeg'; case 'gif': return 'image/gif'; case 'svg': return 'image/svg+xml'; default: return 'application/octet-stream'; } } async function processScriptContent(content, fileMap) { fileMap.forEach(({ relativePath, absolutePath }) => { const regex = new RegExp(relativePath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'); content = content.replace(regex, absolutePath); }); content = content.replace(/fetch\(['"]([^'"]+)['"]\)/g, (match, p1) => { const file = fileMap.find(entry => entry.relativePath === p1); if (file) { return `fetch('${file.absolutePath}')`; } else { return match; } }); content = content.replace(/['"]([^'"]+\.(json|xml|csv|txt|png|jpg|jpeg|gif|svg))['"]/g, (match, p1) => { const file = fileMap.find(entry => entry.relativePath === p1); if (file) { return `'${file.absolutePath}'`; } else { return match; } }); return content; } async function loadHtmlContent(content, fileMap) { let modifiedContent = content; fileMap.forEach(({ relativePath, absolutePath }) => { const regex = new RegExp(relativePath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'); modifiedContent = modifiedContent.replace(regex, absolutePath); }); const tempElement = document.createElement('div'); tempElement.innerHTML = modifiedContent; tempElement.querySelectorAll('iframe').forEach(iframe => { const src = iframe.getAttribute('src'); const file = fileMap.find(entry => entry.relativePath === src); if (file) { iframe.setAttribute('src', file.absolutePath); } }); tempElement.querySelectorAll('a').forEach(anchor => { const href = anchor.getAttribute('href'); if (href && !href.startsWith('http')) { const file = fileMap.find(entry => entry.relativePath === href); if (file) { anchor.setAttribute('href', file.absolutePath); anchor.setAttribute('target', '_self'); } } }); const scriptPromises = []; tempElement.querySelectorAll('script').forEach(script => { const src = script.getAttribute('src'); if (src) { const file = fileMap.find(entry => entry.relativePath === src); if (file) { const newScript = document.createElement('script'); newScript.src = file.absolutePath; newScript.type = 'application/javascript'; script.replaceWith(newScript); } } else { scriptPromises.push(new Promise(async (resolve) => { const scriptContent = await processScriptContent(script.textContent, fileMap); const newScript = document.createElement('script'); newScript.textContent = scriptContent; script.replaceWith(newScript); resolve(); })); } }); await Promise.all(scriptPromises); document.open(); document.write(tempElement.innerHTML); document.close(); } try { const response = await fetch(url); if (!response.ok) throw new Error("Failed to fetch the zip file."); const blob = await response.blob(); const zip = await JSZip.loadAsync(blob); const fileMap = []; for (const [relativePath, file] of Object.entries(zip.files)) { if (!file.dir) { const fileContent = await file.async("blob"); const fileType = await getFileType(relativePath); const objectUrl = URL.createObjectURL(new Blob([fileContent], { type: fileType })); fileMap.push({ relativePath, absolutePath: objectUrl }); } } fileListElement.textContent = fileMap.map(entry => entry.relativePath).join("\n"); const indexPath = "index.html"; const indexFile = fileMap.find(entry => entry.relativePath === indexPath); if (indexFile) { try { const response = await fetch(indexFile.absolutePath); const indexContent = await response.text(); await loadHtmlContent(indexContent, fileMap); } catch (error) { console.error(`Error loading ${indexPath} from object URL. Trying to load from zip blob.`); console.error(error); // Log individual filename refetched console.log(`Refetching ${indexFile.relativePath} from zip blob.`); const indexContent = await indexFile.blob(); const textContent = await new Response(indexContent).text(); await loadHtmlContent(textContent, fileMap); } } else { throw new Error(`${indexPath} not found in the zip file.`); } } catch (error) { fileListElement.textContent = "Error: " + error.message; } }); </script> </head> <body> <h1>JSZip Example</h1> <pre id="file-list"></pre> </body> </html> Console Log Visualizer: ------------------------- <!--https://github.com/gh-canon/stack-snippet-console-https://stackoverflow.com/questions/62422123/display-browser-console-in-html-page--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Console Output Display</title> <style> .console-output { position: fixed; bottom: 0; left: 0; width: 100%; max-height: 55%; overflow-y: auto; background-color: #333; color: #fff; padding: 10px; font-family: monospace; font-size: 14px; white-space: pre-wrap; /* Allows text to wrap and show entire log entry */ } .log { color: #fff; } .error { color: #f44336; } .warn { color: #ff9800; } .info { color: #2196f3; } .debug { color: #9e9e9e; } </style> </head> <body> <script> function dumpConsoleToDOM() { const consoleMethods = ['log', 'error', 'warn', 'info', 'debug']; consoleMethods.forEach(method => { const originalMethod = console[method]; console[method] = function(...args) { originalMethod.apply(console, args); const consoleOutput = Array.from(args || []) .map(item => { if (typeof item === 'object') { return `<div class="${method}">${serializeObject(item)}</div>`; } else { return `<div class="${method}">${item}</div>`; } }) .join(''); const consoleDiv = document.createElement('div'); consoleDiv.classList.add('console-output'); consoleDiv.innerHTML = consoleOutput; document.body.appendChild(consoleDiv); }; }); } function serializeObject(obj) { if (obj instanceof Error) { return `${obj.name}: ${obj.message}\n${obj.stack}`; } else if (obj instanceof ProgressEvent) { return `ProgressEvent: {\n isTrusted: ${obj.isTrusted},\n lengthComputable: ${obj.lengthComputable},\n loaded: ${obj.loaded},\n total: ${obj.total},\n type: '${obj.type}',\n target: ${obj.target ? obj.target.constructor.name : 'null'}\n}`; } else { return JSON.stringify(obj, null, 2); } } dumpConsoleToDOM(); </script> </body> </html> _____________________________________ Fetch mastodon hashtag counts ------------------------------ <meta charset="UTF-8"> <form id="searchForm"> <label for="apiUrl">Mastodon API URL:</label> <input type="text" id="apiUrl" name="apiUrl"> <br> <label for="tag1">Hashtag 1:</label> <input type="text" id="tag1" name="tag1"> <label for="tag2">Hashtag 2:</label> <input type="text" id="tag2" name="tag2"> <label for="tag3">Hashtag 3:</label> <input type="text" id="tag3" name="tag3"> <details> <label for="tag4">Hashtag 4:</label> <input type="text" id="tag4" name="tag4"> <label for="tag5">Hashtag 5:</label> <input type="text" id="tag5" name="tag5"> <label for="tag6">Hashtag 6:</label> <input type="text" id="tag6" name="tag6"> <label for="tag7">Hashtag 7:</label> <input type="text" id="tag7" name="tag7"> <label for="tag8">Hashtag 8:</label> <input type="text" id="tag8" name="tag8"> <label for="tag9">Hashtag 9:</label> <input type="text" id="tag9" name="tag9"> <label for="tag10">Hashtag 10:</label> <input type="text" id="tag10" name="tag10"> </details> <button type="submit">Count Statuses</button> </form> <div id="statusCounts"></div> <div id="errorMessage" style="color: red;"></div> <script> // Get the current URL const url = new URL(window.location.href); // Get the query parameters const apiUrl = url.searchParams.get('instance') || 'https://pb.todon.de/api/v1/timelines/tag/'; const tag1 = url.searchParams.get('hashtag01') || 'CurrListeningAlcea'; const tag2 = url.searchParams.get('hashtag02') || 'CodeAlcea'; const tag3 = url.searchParams.get('hashtag03') || 'DoodlesAlcea'; const tag4 = url.searchParams.get('hashtag04') || ''; const tag5 = url.searchParams.get('hashtag05') || ''; const tag6 = url.searchParams.get('hashtag06') || ''; const tag7 = url.searchParams.get('hashtag07') || ''; const tag8 = url.searchParams.get('hashtag08') || ''; const tag9 = url.searchParams.get('hashtag09') || ''; const tag10 = url.searchParams.get('hashtag10') || ''; // Prefill the form fields document.getElementById('apiUrl').value = apiUrl; document.getElementById('tag1').value = tag1; document.getElementById('tag2').value = tag2; document.getElementById('tag3').value = tag3; document.getElementById('tag4').value = tag4; document.getElementById('tag5').value = tag5; document.getElementById('tag6').value = tag6; document.getElementById('tag7').value = tag7; document.getElementById('tag8').value = tag8; document.getElementById('tag9').value = tag9; document.getElementById('tag10').value = tag10; const searchForm = document.getElementById('searchForm'); const statusCountsElement = document.getElementById('statusCounts'); const errorMessageElement = document.getElementById('errorMessage'); searchForm.addEventListener('submit', (event) => { event.preventDefault(); statusCountsElement.innerHTML = ''; errorMessageElement.textContent = ''; // Get the values of the filled-in hashtag fields const hashtags = [ document.getElementById('tag1').value, document.getElementById('tag2').value, document.getElementById('tag3').value, document.getElementById('tag4').value, document.getElementById('tag5').value, document.getElementById('tag6').value, document.getElementById('tag7').value, document.getElementById('tag8').value, document.getElementById('tag9').value, document.getElementById('tag10').value ].filter(tag => tag.trim() !== ''); // Process the filled-in hashtags hashtags.forEach(tag => countStatuses(apiUrl, tag, tag)); }); function countStatuses(apiUrl, tag, tagName) { const fullUrl = `${apiUrl}${tag}`; let totalCount = 0; let nextLink = null; function extractLinkUrl(linkHeader, rel) { if (!linkHeader) return null; let links = linkHeader.split(','); for (let i = 0; i < links.length; i++) { let link = links[i].trim(); if (link.indexOf(`rel="${rel}"`) !== -1) { let url = link.substring(link.indexOf('<') + 1, link.indexOf('>')); return url; } } return null; } function fetchEntities() { let url = nextLink || fullUrl; return fetch(url, { headers: { 'Authorization': 'Bearer token' } }) .then(response => { if (response.ok) { return response.json().then(data => { totalCount += data.length; let statusCountElement = document.getElementById(`status-count-${tagName}`); if (!statusCountElement) { statusCountElement = document.createElement('div'); statusCountElement.id = `status-count-${tagName}`; statusCountsElement.appendChild(statusCountElement); } statusCountElement.textContent = `*${tagName}: ${totalCount}`; let linkHeader = response.headers.get('Link'); nextLink = extractLinkUrl(linkHeader, 'next'); if (nextLink) { return fetchEntities(); } else { console.log(`Total status count for ${tag}: ${totalCount}`); } }); } else { console.error(`Error fetching data: ${response.status}`); errorMessageElement.textContent = `Error fetching data for hashtag "${tag}": ${response.status}`; throw new Error(`Error fetching data: ${response.status}`); } }) .catch(error => { console.error('Error fetching data:', error); errorMessageElement.textContent = `Error fetching data for hashtag "${tag}": ${error.message}`; }); } fetchEntities(); } </script> </body> </html> _______________________ WeatherInfo ------------------- <meta charset="utf-8"> <div id="weather-info">Loading weather information...</div> <div id="error-message" style="color: red;"></div> <script> const urlParams = new URLSearchParams(window.location.search); const latitude = urlParams.has('lat') ? parseFloat(urlParams.get('lat')) : 48.3667; const longitude = urlParams.has('long') ? parseFloat(urlParams.get('long')) : 10.9; const country = urlParams.has('country') ? urlParams.get('country') : 'Germany'; const weatherDescriptionLookup = [ 'Clear sky', 'Partly cloudy', 'Partly cloudy', 'Partly cloudy', 'Fog', 'Fog', 'Fog', 'Drizzle', 'Rain', 'Rain', 'Thunderstorm', 'Thunderstorm', 'Snow', 'Snow', 'Snow', 'Snow', 'Snow', 'Sleet', 'Dust', 'Dust', 'Dust', 'Dust', 'Strong wind', 'Strong wind', 'Unknown' ]; const openMeteoUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current_weather=true&timezone=Europe%2FBerlin`; const geoapifyUrl = `https://api.geoapify.com/v1/geocode/reverse?lat=${latitude}&lon=${longitude}&format=json&limit=1`; Promise.all([ fetch(geoapifyUrl).then(response => response.json()), fetch(openMeteoUrl).then(response => response.json()) ]) .then(([geoapifyData, openMeteoData]) => { const cityName = geoapifyData.results?.[0]?.city || 'Unknown'; const weatherCode = openMeteoData.current_weather.weathercode; const weatherDescriptionText = weatherDescriptionLookup[weatherCode] || 'Unknown'; const weatherInfo = document.getElementById('weather-info'); weatherInfo.textContent = `${country}: • ${openMeteoData.current_weather.temperature}°C •${weatherDescriptionText}`; }) .catch(error => { console.error('Error:', error); document.getElementById('error-message').textContent = 'Error retrieving weather information: ' + error.message; }); </script> __________________________ Mastodon-userpost-percentage-instance ------------------------------------ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Mastodon Account Statuses</title> </head> <body> <h1>Mastodon Account Statuses</h1> <div class="info-line"> <div id="userName"></div> <div id="userStatuses"></div> </div> <div id="instanceStatuses"></div> <div id="userPercentage"></div> <script> // Get the query parameters const urlParams = new URLSearchParams(window.location.search); const instanceUrl = urlParams.get('instanceUrl') || 'https://mastodon.animexx.de'; const userId = urlParams.get('userId') || '111676830721936824'; // Fetch user account information fetch(`${instanceUrl}/api/v1/accounts/${userId}`) .then(response => response.json()) .then(userData => { const {acct} = userData; const userNameDiv = document.getElementById('userName'); userNameDiv.textContent = `Username: @${acct}`; // Display the user's status count const userStatusesDiv = document.getElementById('userStatuses'); userStatusesDiv.textContent = `The user has ${userData.statuses_count} statuses.`; // Fetch instance information return fetch(`${instanceUrl}/api/v1/instance`); }) .then(response => response.json()) .then(instanceData => { const {status_count: instanceStatusesCount} = instanceData.stats; const instanceStatusesDiv = document.getElementById('instanceStatuses'); instanceStatusesDiv.textContent = `${instanceUrl} has ${instanceStatusesCount} total statuses.`; // Calculate and display the user's percentage of instance posts const userStatusesCount = parseInt(document.getElementById('userStatuses').textContent.match(/\d+/)[0]); const userPercentage = (userStatusesCount / instanceStatusesCount * 100).toFixed(2); const userPercentageDiv = document.getElementById('userPercentage'); userPercentageDiv.textContent = `${document.getElementById('userName').textContent.split(': ')[1]} is responsible for ${userPercentage}% of the posts on this instance.`; }) .catch(error => console.error(error)); </script> </body> </html> <!------> <br><br> <form id="inputForm"> <label for="userId">User ID:</label> <input type="text" id="userId" name="userId" required> <label for="instanceUrl">Instance URL:</label> <input type="text" id="instanceUrl" name="instanceUrl" required> <button type="submit">Submit</button> </form> <script> document.getElementById('inputForm').addEventListener('submit', (event) => { event.preventDefault(); const newInstanceUrl = document.getElementById('instanceUrl').value; const newUserId = document.getElementById('userId').value; const newUrl = `?instanceUrl=${newInstanceUrl}&userId=${newUserId}`; window.location.href = window.location.pathname + newUrl; }); </script> Extract final word from json field: ------------------------------------------------- <body> <script> fetch('https://alceawis.de/other/extra/scripts/fakesocialmedia/data_alcea.json') .then(response => response.json()) .then(data => { const finalElements = data.slice(0, 15).map(obj => { const values = Object.values(obj); const lastValue = values[values.length - 1].value; return lastValue.trim().split(/\s+/).pop(); }); const container = document.createElement('div'); finalElements.forEach(element => { const elementDiv = document.createElement('div'); elementDiv.textContent = element; container.appendChild(elementDiv); }); document.body.appendChild(container); }) .catch(error => console.error(error)); </script> </body> </html> ________________________________ WebDAV Webserver Access urlgen ---------------------------- <!--https://stackoverflow.com/questions/26545126/ithit-ajax-file-browser-active-directory-webdav-auto-login--> <h1>WebDAV Server Access</h1> <form> <label for="webDavServerPath">WebDAV Server Path:</label> <input type="text" id="webDavServerPath" value="webdav.hidrive.strato.com"><br> <label for="username">Username:</label> <input type="text" id="username"><br> <label for="password">Password:</label> <input type="password" id="password"><br> <button type="button" onclick="openWebDavLogin()">Access WebDAV Server</button> </form> <script> function openWebDavLogin() { var webDavServerPath = document.getElementById("webDavServerPath").value; var username = document.getElementById("username").value; var password = document.getElementById("password").value; // Construct the login URL with the username and password //var loginUrl = `${webDavServerPath}?mode=login&username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`; var loginUrl = `${encodeURIComponent(username)}:${encodeURIComponent(password)}@${webDavServerPath}`; // Open the WebDAV login in a new tab window.open(loginUrl, '_blank'); } </script> _________ Bluesky TL render (via feednami) --------------------- <script src="https://storage.googleapis.com/feednami-static/js/feednami-client-v1.0.1.js"></script> <script> function fetchRssFeed(feedUrl) { feednami.load(feedUrl, function(result) { if (result.error) { console.error('Error fetching RSS feed:', result.error); } else { const entries = result.feed.entries; displayBlueSkyEmbeds(entries); } }); } // Function to display BlueSkya embeds function displayBlueSkyEmbeds(feedItems) { feedItems.forEach(item => { const link = item.link; const lastSlashPos = link.lastIndexOf('/'); const postId = link.substring(lastSlashPos + 1); let guidValue = item.guid; let didPrefix = 'did:plc:'; if (!guidValue.startsWith('http')) { const startPos = guidValue.indexOf('plc:') + 4; const endPos = guidValue.indexOf('/app.bsky'); const guidPart = guidValue.substring(startPos, endPos); guidValue = `at://${didPrefix}${guidPart}/app.bsky.feed.post/${postId}`; } const embed = document.createElement('blockquote'); embed.classList.add('bluesky-embed'); embed.setAttribute('data-bluesky-uri', guidValue); embed.setAttribute('data-bluesky-cid', ''); document.body.appendChild(embed); }); // Load the BlueSkya embed script const embedScript = document.createElement('script'); embedScript.async = true; embedScript.src = 'https://embed.bsky.app/static/embed.js'; embedScript.charset = 'utf-8'; document.body.appendChild(embedScript); } // Example usage const feedUrl = new URL(window.location.href).searchParams.get('bskyurl') || 'https://bsky.app/profile/did:plc:nc45m3kcywjhyr4tgsbmea64/rss'; fetchRssFeed(feedUrl); </script> _____________________ Hiragana & Katakana to Romaji ----------------------------- <a target="_blank" href="https://j-talk.com/convert" style=color:blue>alt</a><br> <meta charset="utf-8"> <!DOCTYPE html> <html> <head> <title>Hiragana and Katakana to Romaji </title> </head> <body> <h1>Hiragana and Katakana to Romaji Converter</h1> Enter Hiraga or Kataka and it'll output romaji !<br> <input type="text" id="inputText" placeholder="Enter Hiragana or Katakana" oninput="convertToRomaji()"> <p>Romaji: <span id="romaji"></span></p> <script> function hiraganaKatakanaToRomaji(text) { const hiraganaToRomaji = { 'あ': 'a', 'い': 'i', 'う': 'u', 'え': 'e', 'お': 'o', 'か': 'ka', 'き': 'ki', 'く': 'ku', 'け': 'ke', 'こ': 'ko', 'さ': 'sa', 'し': 'shi', 'す': 'su', 'せ': 'se', 'そ': 'so', 'た': 'ta', 'ち': 'chi', 'つ': 'tsu', 'て': 'te', 'と': 'to', 'な': 'na', 'に': 'ni', 'ぬ': 'nu', 'ね': 'ne', 'の': 'no', 'は': 'ha', 'ひ': 'hi', 'ふ': 'fu', 'へ': 'he', 'ほ': 'ho', 'ま': 'ma', 'み': 'mi', 'む': 'mu', 'め': 'me', 'も': 'mo', 'や': 'ya', 'ゆ': 'yu', 'よ': 'yo', 'ら': 'ra', 'り': 'ri', 'る': 'ru', 'れ': 're', 'ろ': 'ro', 'わ': 'wa', 'を': 'wo', 'ん': 'n' }; const katakanaToRomaji = { 'ア': 'a', 'イ': 'i', 'ウ': 'u', 'エ': 'e', 'オ': 'o', 'カ': 'ka', 'キ': 'ki', 'ク': 'ku', 'ケ': 'ke', 'コ': 'ko', 'サ': 'sa', 'シ': 'shi', 'ス': 'su', 'セ': 'se', 'ソ': 'so', 'タ': 'ta', 'チ': 'chi', 'ツ': 'tsu', 'テ': 'te', 'ト': 'to', 'ナ': 'na', 'ニ': 'ni', 'ヌ': 'nu', 'ネ': 'ne', 'ノ': 'no', 'ハ': 'ha', 'ヒ': 'hi', 'フ': 'fu', 'ヘ': 'he', 'ホ': 'ho', 'マ': 'ma', 'ミ': 'mi', 'ム': 'mu', 'メ': 'me', 'モ': 'mo', 'ヤ': 'ya', 'ユ': 'yu', 'ヨ': 'yo', 'ラ': 'ra', 'リ': 'ri', 'ル': 'ru', 'レ': 're', 'ロ': 'ro', 'ワ': 'wa', 'ヲ': 'wo', 'ン': 'n' }; let romaji = ''; for (let i = 0; i < text.length; i++) { const char = text[i]; romaji += hiraganaToRomaji[char] || katakanaToRomaji[char] || char; } return romaji; } function convertToRomaji() { const inputText = document.getElementById('inputText').value; const romaji = hiraganaKatakanaToRomaji(inputText); document.getElementById('romaji').textContent = romaji; } </script> </body> </html> _______________________ Volumina in Box Calculator ------------------------- Bin Space: 74.400.000 mm³<br><hr> <script> // Function to calculate the volume of a bin function calculateBinVolume(length, width, height) { return length * width * height; } // Function to calculate the volume of an item function calculateItemVolume(length, width, height) { return length * width * height; } // Function to check if the items fit in the bin function checkItemsFitInBin() { // Get the bin dimensions const binLength = parseInt(document.getElementById('bin-length').value); const binWidth = parseInt(document.getElementById('bin-width').value); const binHeight = parseInt(document.getElementById('bin-height').value); // Get the item dimensions const itemLength = parseInt(document.getElementById('item-length').value); const itemWidth = parseInt(document.getElementById('item-width').value); const itemHeight = parseInt(document.getElementById('item-height').value); // Get the number of items const itemCount = parseInt(document.getElementById('item-count').value); // Check if the item dimensions exceed the bin height //if (itemHeight > binHeight) { if (itemHeight > binHeight || itemLength > binLength || itemWidth > binWidth) { // Display error message const resultElement = document.getElementById('result'); resultElement.innerHTML = "Item height exceeds bin height. Items do not fit in bin."; return; } // Calculate the volume of the bin const binVolume = calculateBinVolume(binLength, binWidth, binHeight); // Calculate the total volume of all items const totalItemVolume = calculateItemVolume(itemLength, itemWidth, itemHeight) * itemCount; // Calculate the remaining space in the bin const remainingSpace = binVolume - totalItemVolume; // Check if the items fit in the bin if (remainingSpace >= 0) { // Calculate the percentage of space used by the items const spaceUsedPercentage = (totalItemVolume / binVolume) * 100; // Display the result const resultElement = document.getElementById('result'); resultElement.innerHTML = "Items fit in bin.<br>" + "Total space occupied by items: " + totalItemVolume + "<br>" + "Remaining space in the bin: " + remainingSpace + "<br>" + "Space used by items in percentage: " + spaceUsedPercentage + "%"; } else { // Display the result const resultElement = document.getElementById('result'); resultElement.innerHTML = "Items do not fit in bin."; } } </script> </head> <body> <label for="bin-length">Bin Length:</label> <input type="number" id="bin-length" value="600"> <br> <label for="bin-width">Bin Width:</label> <input type="number" id="bin-width" value="400"> <br> <label for="bin-height">Bin Height:</label> <input type="number" id="bin-height" value="310"> <br> <label for="item-length">Item Length:</label> <input type="number" id="item-length"> <br> <label for="item-width">Item Width:</label> <input type="number" id="item-width"> <br> <label for="item-height">Item Height:</label> <input type="number" id="item-height"> <br> <label for="item-count">Number of Items:</label> <input type="number" id="item-count"> <br> <button onclick="checkItemsFitInBin()">Check</button> <p id="result"></p> </body> </html> __________________ Mail obfuscation (base64img) ------------------------- <script> function generateEmailImages() { var email = 'alceawisteria@proton.mailll'; var element = document.getElementById('email'); for (var i = 0; i < email.length; i++) { var letter = email.charAt(i); var imageElement = document.createElement('img'); imageElement.src = generateLetterImageBase64(letter); element.appendChild(imageElement);}} function generateLetterImageBase64(letter) { var canvas = document.createElement('canvas'); canvas.width = 24; canvas.height = 50; var ctx = canvas.getContext('2d'); ctx.fillStyle = '#000'; ctx.font = 'bold 15px Arial'; ctx.fillText(letter, 10, 30); return canvas.toDataURL(); } </script> <body onload="generateEmailImages()"> <p><span id="email"></span></p> </body ____________________ Wheel of Fortune (What do I draw today) -------------------- <style> #wheelOfFortune { display: inline-flex; position: relative; overflow: hidden; } #wheel {display: block;} #spin { font: 1.0rem/0 sans-serif; user-select: none; cursor: pointer; display: flex; justify-content: center; align-items: center; position: absolute; top: 50%; left: 50%; width: 30%; height: 30%; margin: -15%; background: #000; color: #fff; box-shadow: 0 0 0 8px currentColor, 0 0px 15px 5px rgba(0, 0, 0, 0.6); border-radius: 50%; transition: 0.8s;} #spin::after { content: ""; position: absolute; top: -17px; border: 10px solid transparent; border-bottom-color: currentColor; border-top: none; } </style> </head> <body> <div id="wheelOfFortune"> <canvas id="wheel" width="300" height="300"></canvas> <div id="spin">SPIN</div> </div> <script> const sectors = [ { color: "https://i.ibb.co/bzJzvBY/ishiseto.jpg", label: "イシズ・イシュタール" }, { color: "https://i.ibb.co/YpSBKpX/yunaoi.jpg", label: "ゆさあお" }, { color: "https://i.ibb.co/yB0jFVr/subnmis.jpg", label: "流星のロックマン" }, { color: "https://i.ibb.co/DfGxJGP/Screenshot-2024-04-14-16-01-48.jpg", label: "シオン(キングダムハーツ)" }, { color: "https://i.ibb.co/Yc3v4KS/Instruments.jpg", label: "instruments" } ]; const rand = (m, M) => Math.random() * (M - m) + m; const tot = sectors.length; const elSpin = document.querySelector("#spin"); const ctx = document.querySelector("#wheel").getContext("2d"); const dia = ctx.canvas.width; const rad = dia / 2; const PI = Math.PI; const TAU = 2 * PI; const arc = TAU / tot; const friction = 0.991; const angVelMin = 0.002; let angVelMax = 0; let angVel = 0; let ang = 0; let isSpinning = false; let isAccelerating = false; let animFrame = null; const getIndex = () => Math.floor(tot - ang / TAU * tot) % tot; const drawSector = (sector, i) => { const angle = arc * i; const img = new Image(); img.onload = function() { ctx.save(); ctx.beginPath(); ctx.moveTo(rad, rad); ctx.arc(rad, rad, rad, angle, angle + arc); ctx.closePath(); ctx.clip(); ctx.translate(rad, rad); ctx.rotate(angle + arc / 2); const scaleFactor = Math.min(dia / img.width, dia / img.height); const scaledWidth = img.width * scaleFactor; const scaledHeight = img.height * scaleFactor; ctx.drawImage(img, -scaledWidth / 5, -scaledHeight / 5, scaledWidth, scaledHeight); ctx.restore(); ctx.textAlign = "right"; ctx.fillStyle = "#000"; ctx.font = "bold 30px sans-serif"; ctx.fillText(sector.label, 0, rad - 10); }; img.src = sector.color; }; const rotate = () => { const sector = sectors[getIndex()]; ctx.canvas.style.transform = `rotate(${ang - PI / 2}rad)`; //elSpin.textContent = !angVel ? "SPIN" : sector.label; elSpin.textContent = sector.label; }; const frame = () => { if (!isSpinning) return; if (angVel >= angVelMax) isAccelerating = false; if (isAccelerating) { angVel ||= angVelMin; angVel *= 1.06; } else { isAccelerating = false; angVel *= friction; if (angVel < angVelMin) { isSpinning = false; angVel = 0; cancelAnimationFrame(animFrame); } } ang += angVel; ang %= TAU; rotate(); }; const engine = () => { frame(); animFrame = requestAnimationFrame(engine); }; elSpin.addEventListener("click", () => { if (isSpinning) return; isSpinning = true; isAccelerating = true; angVelMax = rand(0.25, 0.40); engine(); }); sectors.forEach(drawSector); rotate(); </script> </body> <!--SelfUpdatingLink--> <a id="link" href="#" target="_blank">Link</a> <script> const spinDiv = document.getElementById("spin"); const linkDiv = document.getElementById("link"); // Create a new MutationObserver instance const observer = new MutationObserver((mutationsList) => { for (let mutation of mutationsList) { if (mutation.type === "childList" && mutation.target === spinDiv) { const spinText = spinDiv.textContent; const linkURL = `https://www.pixiv.net/en/users/75406576/artworks/${spinText}`; linkDiv.href = linkURL; } } }); observer.observe(spinDiv, { childList: true }); setTimeout(() => { spinDiv.textContent = "New Spin Text"; }, 3000); </script> __________________________________________________________________ Megaman Zero Esque CSS: (with audio for buttons) ------------------------ <!----Audio---> <audio id="audio"><source src="https://a.tumblr.com/tumblr_ojrn7aGBii1w2e2oyo1.mp3" type="audio/mpeg"></audio> <script> var html5_audiotypes={"mp3":"audio/mpeg","mp4":"audio/mp4","ogg":"audio/ogg","wav":"audio/wav"};function createsoundbite(e){var t=document.createElement("audio");if(t.canPlayType)for(var n=0;n<arguments.length;n++){var r=document.createElement("source");r.setAttribute("src",arguments[n]),arguments[n].match(/\.(\w+)$/i)&&r.setAttribute("type",html5_audiotypes[RegExp.$1]),t.appendChild(r)}return t.load(),t.playclip=function(){t.pause(),t.currentTime=0,t.play()},t}var mouseoversound=createsoundbite("/other/music/sfx/megaman/mmz4_option.mp3");var clicksound=createsoundbite("/other/music/sfx/megaman/mmz4_ok.mp3"); document.getElementById("img").addEventListener("click", function(){ document.getElementById("audio").play(); }); </script> <!----MMZ_CSS--> <style> body { background-color: #010245; /* Add this line to set the background color to blue */ background-image: url(https://alceawis.de/other/music/sfx/megaman/mmz_t-n-b.gif), url(https://alceawis.de/other/music/sfx/megaman/mmz_l-n-r.gif); background-repeat: repeat-x, repeat-y; background-position: center top, right top; background-attachment: fixed; } body::before { content: ""; position: fixed; bottom: 0; left: 0; width: 100%; height: 100%; background-image: url(https://alceawis.de/other/music/sfx/megaman/mmz_l-n-r.gif); background-repeat: repeat-y; background-position: right bottom; transform: scaleX(-1); pointer-events: none; /* Add this line to allow interaction with elements behind */ } body::after { content: ""; position: fixed; bottom: 0; left: 0px; right: 0px; height: 100%; background-image: url(https://alceawis.de/other/music/sfx/megaman/mmz_t-n-b.gif); background-repeat: repeat-x; background-position: center top; transform: scaleY(-1); pointer-events: none; /* Add this line to allow interaction with elements behind */ } button { background-color: #18FFF7; opacity: 0.5; color: white !important; } * { color: white !important; } </style> _______________________________________ Add Border around ALL elements on page: ------------------------------------------------------------------ <style> * { border: 1px solid #18FFF7; } </style> ___________________ Link from base64 and array generator (musicshare / hidrive) --------------------------- <select id="rollPicker"> </select> <button onclick="generateLink()">Generate Link</button> <br> <div id="linkOutput"></div> <script> var encodedList = "MDAwIFs2NzUgTWJdIFRoZSBNZW50IFZlcnkgQmVzdAowIE5hbmEgT1NUCjAgUGFyYXN5dGUgT1NUCjBbblprXShIaXJveXVraVNhd2FubykKMEFwZXhfTGVnZW5kc19PU1QKMEFyY2FuYSBGYW1pZ2xpYSBPU1QKMEJsb29kc3RhaW5lZCBPU1QKMENhc3RsZXZhbmlhCjBDZWxlc3RlIE9TVAowQ2hhcmxvdHRlIE9TVAowQ2hpY29yeSBPU1QKMENocm9ubyBPU1RzCjBDaW5nCjBEYW5jZSB3aXRoIHRoZSBEZWFkCjBEQyBCZXN0IG9mIFsgTUJdCjBEZWFkbHkgUHJlbW9uaXRpb24gT1NUCjBEZWF0aCBOb3RlIFszNjVNQl0KMEUuWC4gVHJvb3BlcnMgT1NUCjBFc2NhcGUgdGhlIEZhdGUgW0Jlc3Qgb2ZdCjBGYWxsaW5nIGluIFJldmVyc2UKMEZGLUJlc3Qtb2YKMEZsb3dlciBTdW4gJiBSYWluIEJlc3RvZmYKMEZ1bGxfTW9vbl9Xb19TYWdhc2hpdGUKMEhhdmVuIE9yaWdpbmFsIFNvdW5kdHJhY2sKMEhpYmlrZSBFdXBob25pdW0gT3JpZ2luYWwgU291bmR0cmFjawowSG9zaGlOb1NhbWlkYXJlIE9TVAowSG9zaGlOb1NhbWlkYXJlT1NUCjBJbmF6dW1hIEVsZXZlbiBPU1QgQmVzdCBvZgowSm9zZWVfdG8gdG9yYV90b19zYWthbmFfdGFjaGkKMEthZ3V5YS1zYW1hIHdhIEtva3VyYXNldGFpIE9TVAowS2FpdG91IEpva2VyIE9TVAowS2FtaWthemUgS2FpdG91IEplYW5uZSBPU1QKMEthemUgZ2EgVHN1eW9rdSBGdWl0ZWlydQowS2lsbCBMYSBLaWxsIE9TVAowS2l6bmFpdmVyIE9TVAowS29lIG5vIEthdGFjaGkgT1NUCjBLdXJ6Z2VzYWd0CjBLdXp1IG5vIEhvbmthaSBPU1QKMExhemVyaGF3awowTGlua2luX1BhcmsKME1hY2hpbmUtRG9sbCB3YSBLaXp1dHN1a2FuYWkgT1NUCjBNYWRlIGluIEFieXNzIE9TVAowTWFnaWMgS2FpdG8gMTQxMiBPU1QKME1haG91a2EgS291a291IG5vIFJldHRvdXNlaSBPU1QKME1lZ2FtYW5fQmVzdF9PZmZzX1sxLjUgR0JdCjBNaXJhaSBOaWtraSBCZXN0IE9mIFs0MjNNQl0KME1pc2F0byBGdWt1ZW4KME11cmRlciBieSBOdW1iZXJzIE9TVAowTmFnaSBubyBBc3VrYXJhIE9TVAowTmFydXRvIE9TVAowTm9yYWdhbWlfT1NUCjBOb3JuOSBPU1QKMFJvY2ttYW5fRVhFCjBSeXUgZ2EgR290b2t1IE9TVAowUnl1dXNlaSBubyBSb2NrbWFuIE9TVAowU2FuZ2F0c3Ugbm8gTGlvbiBPU1QKMFNhdHN1cmlrdSBubyBUZW5zaGkgT3JpZ2luYWwgU291bmR0cmFjawowU2hpa2lfT1NUCjBTb21hIEJyaW5nZXIgT1NUCjBTcGVlZCBHcmFwaGVyIE9TVAowU3ViYXJhc2hpa2kgS29ubyBTZWthaQowU3dpdGNoZWQgT3JpZ2luYWwgU291bmR0cmFjawowVGV0c3V3YW4gQmlyZHkgT3JpZ2luYWwgU291bmR0cmFjawowVExvWgowVG9reW8gRVNQIE9yaWdpbmFsIFNvdW5kdHJhY2sKMFRvbW9rbyBLYXdhc2UKMFRyYWNlIC0gS2Fzb3VrZW4gbm8gT3Rva28gT1NUCjBUcmlja3N0ZXIgRWRvZ2F3YSBSYW5wbyBPU1QKMFVuZGVydGFsZSBPU1QKMFVzb3RzdWtpIEhpbWUgdG8gTW91bW9rdSBPdWppIE9TVAowVXRhZGEgSGlrYXJ1CjBWaW9sZXQgRXZlcmdhcmRlbiBPU1QKMFhlbm9fT1NUCjBab25lIG9mIHRoZSBFbmRlcnMgT1NUCkFqaW4gT1NUCkFydEF0dGFja19PU1QKQXp1cmUgU3RyaWtlciBHdW52b2x0Ckdob3N0IFRyaWNrIE9yaWdpbmFsIFNvdW5kdHJhY2sKR09EIEVBVEVSIE9TVApHeWFrdXRlbgpNaXNhdG8gRnVrdWVuIC0gQmVzdCBvZgpUb2t5byBHaG91bCBPU1QKWUdPX0Jlc3RfT2ZfWzE1MTBNQl0="; function generateLink() { var rollPicker = document.getElementById("rollPicker"); var selectedOption = rollPicker.options[rollPicker.selectedIndex].value; var link = "https://my.link.de/share/folder#$/"; var finalLink = link + selectedOption; var finalLink = '<a href="' + finalLink + '" target="_blank">' + finalLink + '</a>'; document.getElementById("linkOutput").innerHTML = finalLink;} var decodedList = atob(encodedList); var options = decodedList.split('\n'); var rollPicker = document.getElementById("rollPicker"); for (var i = 0; i < options.length; i++) { var option = document.createElement("option"); option.value = options[i]; option.text = options[i]; rollPicker.appendChild(option);} </script> ___________________________ HTML Class extractor (here: hidrive names) ------------------------------ <input type="text" id="classInput" placeholder="Enter class name" value="label-text display_name"><br> <textarea id="pasteInput" rows="5" placeholder="Paste HTML content here"></textarea> <button id="extractButton" onclick="extractText()">Extract</button> <div id="output"></div> <script> function extractText() { var classInput = document.getElementById('classInput'); var className = classInput.value.trim(); var pasteInput = document.getElementById('pasteInput'); var htmlContent = pasteInput.value; var parser = new DOMParser(); var doc = parser.parseFromString(htmlContent, "text/html"); var elements = doc.getElementsByClassName(className); var extractedText = ''; for (var i = 0; i < elements.length; i++) { extractedText += elements[i].textContent + '<br>'; } var outputDiv = document.getElementById('output'); outputDiv.innerHTML = extractedText; } </script> </body> </html> ____________________________ MMD Bone Renamer (MikuMikuDance) ---------------------------------- <details><summary>How2</summary> --PMXEditor v2.0--<br> 1) Edit -> BatchNameEditor<br> => Copy names to Clipboard<br> <a class="u-button-style u-nav-link u-white" href="https://i.ibb.co/745fFQt/Screenshot-2024-07-05-10-07-23.jpg#https://ibb.co/m8wj705" target="_blank">(click)</a><br> <br> then copy japanese back after conversion </details> <!DOCTYPE html> <html> <head> <style> table { border-collapse: collapse; width: 100%; } td, th { border: 1px solid #000; padding: 8px; text-align: left; } .copy-button { margin-top: 10px; } </style> </head> <body> <h1>MMD Bone Renamer Tool</h1> <form id="parse-form"> <label for="csv-url">CSV URL:</label> <input type="text" id="csv-url" value="https://ry3yr.github.io/mmdbonenames.csv"> <br><br> <label for="input-text">Input Text:</label> <br> <textarea id="input-text" placeholder="Paste non-Japanese bone names here"></textarea> <br> <input type="submit" value="Submit"> </form> <div class="fixed-div"> <button class="copy-button" onclick="copyColumnToClipboard(0)">Copy Old Names</button> <button class="copy-button" onclick="copyColumnToClipboard(1)">Copy New Names</button> </div> <div id="output"></div> <script> function parseCSV(csvData) { var lines = csvData.split("\n"); var result = []; for (var i = 0; i < lines.length; i++) { var currentLine = lines[i].split(","); if (currentLine.length >= 2) { var key = currentLine[0].replace(/"/g, ""); var value = currentLine[1].replace(/"/g, ""); result.push({ key: key, value: value }); } } return result; } document.getElementById("parse-form").addEventListener("submit", function(event) { event.preventDefault(); var csvUrl = document.getElementById("csv-url").value.trim(); // Fetch CSV file from the provided URL fetch(csvUrl) .then(function(response) { return response.text(); }) .then(function(data) { var inputText = document.getElementById("input-text").value.trim(); var lines = inputText.split("\n"); // Parse the CSV data var parsedData = parseCSV(data); // Replace each line if a corresponding value exists var tableContent = "<table><tr><th>Old Name</th><th>New Name</th></tr>"; for (var i = 0; i < lines.length; i++) { var line = lines[i].trim(); var matchingValue = parsedData.find(function(item) { return item.key === line; }); var oldName = line; var newName = matchingValue ? matchingValue.value : ""; tableContent += "<tr><td>" + oldName + "</td><td>" + newName + "</td></tr>"; } tableContent += "</table>"; document.getElementById("output").innerHTML = tableContent; //$(".copy-button").remove(); //remove copy button before adding new one //var copyButton = '<button class="copy-button" onclick="copyColumnToClipboard(0)">Copy Old Names</button>'; //copyButton += '<button class="copy-button" onclick="copyColumnToClipboard(1)">Copy New Names</button>'; //document.getElementById("output").insertAdjacentHTML("beforebegin", copyButton); }); }); // Function to copy table column content to clipboard function copyColumnToClipboard(columnIndex) { var table = document.querySelector("table"); var columnData = []; // Get the data from the specified column var rows = table.getElementsByTagName("tr"); for (var i = 0; i < rows.length; i++) { var cells = rows[i].getElementsByTagName("td"); if (cells.length > columnIndex) { columnData.push(cells[columnIndex].innerText); } } // Copy the column data to the clipboard var textarea = document.createElement("textarea"); textarea.textContent = columnData.join("\n"); document.body.appendChild(textarea); textarea.select(); document.execCommand("copy"); document.body.removeChild(textarea); //alert("Content copied to clipboard!"); } </script> </body> </html> <!---v1--jquery--CjxzY3JpcHQgc3JjPSJodHRwczovL2NvZGUuanF1ZXJ5LmNvbS9qcXVlcnktMy42LjAubWluLmpzIj48L3NjcmlwdD4KPHN0eWxlPgp0YWJsZXtib3JkZXItY29sbGFwc2U6Y29sbGFwc2U7d2lkdGg6MTAwJX10ZCx0aHtib3JkZXI6MXB4IHNvbGlkICMwMDA7cGFkZGluZzo4cHg7dGV4dC1hbGlnbjpsZWZ0fS5jb3B5LWJ1dHRvbnttYXJnaW4tdG9wOjEwcHh9CiAgPC9zdHlsZT4KICA8c2NyaXB0PgogICAgJChkb2N1bWVudCkucmVhZHkoZnVuY3Rpb24oKSB7CiAgICAgIGZ1bmN0aW9uIHBhcnNlQ1NWKGNzdkRhdGEpIHsKICAgICAgICB2YXIgbGluZXMgPSBjc3ZEYXRhLnNwbGl0KCJcbiIpOwogICAgICAgIHZhciByZXN1bHQgPSBbXTsKICAgICAgICBmb3IgKHZhciBpID0gMDsgaSA8IGxpbmVzLmxlbmd0aDsgaSsrKSB7CiAgICAgICAgICB2YXIgY3VycmVudExpbmUgPSBsaW5lc1tpXS5zcGxpdCgiLCIpOwogICAgICAgICAgaWYgKGN1cnJlbnRMaW5lLmxlbmd0aCA+PSAyKSB7CiAgICAgICAgICAgIHZhciBrZXkgPSBjdXJyZW50TGluZVswXS5yZXBsYWNlKC8iL2csICIiKTsKICAgICAgICAgICAgdmFyIHZhbHVlID0gY3VycmVudExpbmVbMV0ucmVwbGFjZSgvIi9nLCAiIik7CiAgICAgICAgICAgIHJlc3VsdC5wdXNoKHsga2V5OiBrZXksIHZhbHVlOiB2YWx1ZSB9KTsKICAgICAgICAgIH0KICAgICAgICB9CiAgICAgICAKICAgICAgICByZXR1cm4gcmVzdWx0OwogICAgICB9CiAgICAgICQoIiNwYXJzZS1mb3JtIikuc3VibWl0KGZ1bmN0aW9uKGV2ZW50KSB7CiAgICAgICAgZXZlbnQucHJldmVudERlZmF1bHQoKTsKICAgICAgICAKICAgICAgICB2YXIgY3N2VXJsID0gJCgiI2Nzdi11cmwiKS52YWwoKS50cmltKCk7CiAgICAgICAgCiAgICAgICAgLy8gRmV0Y2ggQ1NWIGZpbGUgZnJvbSB0aGUgcHJvdmlkZWQgVVJMCiAgICAgICAgJC5nZXQoY3N2VXJsLCBmdW5jdGlvbihkYXRhKSB7CiAgICAgICAgICB2YXIgaW5wdXRUZXh0ID0gJCgiI2lucHV0LXRleHQiKS52YWwoKS50cmltKCk7CiAgICAgICAgICB2YXIgbGluZXMgPSBpbnB1dFRleHQuc3BsaXQoIlxuIik7CiAgICAgICAgICAKICAgICAgICAgIC8vIFBhcnNlIHRoZSBDU1YgZGF0YQogICAgICAgICAgdmFyIHBhcnNlZERhdGEgPSBwYXJzZUNTVihkYXRhKTsKICAgICAgICAgIAogICAgICAgICAgLy8gUmVwbGFjZSBlYWNoIGxpbmUgaWYgYSBjb3JyZXNwb25kaW5nIHZhbHVlIGV4aXN0cwogICAgICAgICAgdmFyIHRhYmxlQ29udGVudCA9ICI8dGFibGU+PHRyPjx0aD5PbGQgTmFtZTwvdGg+PHRoPk5ldyBOYW1lPC90aD48L3RyPiI7CiAgICAgICAgICBmb3IgKHZhciBpID0gMDsgaSA8IGxpbmVzLmxlbmd0aDsgaSsrKSB7CiAgICAgICAgICAgIHZhciBsaW5lID0gbGluZXNbaV0udHJpbSgpOwogICAgICAgICAgICB2YXIgbWF0Y2hpbmdWYWx1ZSA9IHBhcnNlZERhdGEuZmluZChmdW5jdGlvbihpdGVtKSB7CiAgICAgICAgICAgICAgcmV0dXJuIGl0ZW0ua2V5ID09PSBsaW5lOwogICAgICAgICAgICB9KTsKICAgICAgICAgICAgCiAgICAgICAgICAgIHZhciBvbGROYW1lID0gbGluZTsKICAgICAgICAgICAgdmFyIG5ld05hbWUgPSBtYXRjaGluZ1ZhbHVlID8gbWF0Y2hpbmdWYWx1ZS52YWx1ZSA6ICIiOwogICAgICAgICAgICAKICAgICAgICAgICAgdGFibGVDb250ZW50ICs9ICI8dHI+PHRkPiIgKyBvbGROYW1lICsgIjwvdGQ+PHRkPiIgKyBuZXdOYW1lICsgIjwvdGQ+PC90cj4iOwogICAgICAgICAgfQogICAgICAgICAgdGFibGVDb250ZW50ICs9ICI8L3RhYmxlPiI7CiAgICAgICAgICAKICAgICAgICAgICQoIiNvdXRwdXQiKS5odG1sKHRhYmxlQ29udGVudCk7CiAgICAgICAgICAkKCIuY29weS1idXR0b24iKS5yZW1vdmUoKTsgLy9yZW1vdmUgY29weSBidXR0b24gYmVmb3JlIGFkZGluZyBuZXcgb25lCiAgICAgICAgICAvLyBBZGQgY29weSBidXR0b25zCiAgICAgICAgICB2YXIgY29weUJ1dHRvbiA9ICc8YnV0dG9uIGNsYXNzPSJjb3B5LWJ1dHRvbiIgb25jbGljaz0iY29weUNvbHVtblRvQ2xpcGJvYXJkKDApIj5Db3B5IE9sZCBOYW1lczwvYnV0dG9uPic7CiAgICAgICAgICBjb3B5QnV0dG9uICs9ICc8YnV0dG9uIGNsYXNzPSJjb3B5LWJ1dHRvbiIgb25jbGljaz0iY29weUNvbHVtblRvQ2xpcGJvYXJkKDEpIj5Db3B5IE5ldyBOYW1lczwvYnV0dG9uPic7CiAgICAgICAgICAKICAgICAgICAgICQoIiNvdXRwdXQiKS5iZWZvcmUoY29weUJ1dHRvbik7CiAgICAgICAgfSk7CiAgICAgIH0pOwogICAgfSk7CiAgICAKICAgIC8vIEZ1bmN0aW9uIHRvIGNvcHkgdGFibGUgY29sdW1uIGNvbnRlbnQgdG8gY2xpcGJvYXJkCiAgICBmdW5jdGlvbiBjb3B5Q29sdW1uVG9DbGlwYm9hcmQoY29sdW1uSW5kZXgpIHsKICAgICAgdmFyIHRhYmxlID0gZG9jdW1lbnQucXVlcnlTZWxlY3RvcigidGFibGUiKTsKICAgICAgdmFyIGNvbHVtbkRhdGEgPSBbXTsKICAgICAgCiAgICAgIC8vIEdldCB0aGUgZGF0YSBmcm9tIHRoZSBzcGVjaWZpZWQgY29sdW1uCiAgICAgIHZhciByb3dzID0gdGFibGUuZ2V0RWxlbWVudHNCeVRhZ05hbWUoInRyIik7CiAgICAgIGZvciAodmFyIGkgPSAwOyBpIDwgcm93cy5sZW5ndGg7IGkrKykgewogICAgICAgIHZhciBjZWxscyA9IHJvd3NbaV0uZ2V0RWxlbWVudHNCeVRhZ05hbWUoInRkIik7CiAgICAgICAgaWYgKGNlbGxzLmxlbmd0aCA+IGNvbHVtbkluZGV4KSB7CiAgICAgICAgICBjb2x1bW5EYXRhLnB1c2goY2VsbHNbY29sdW1uSW5kZXhdLmlubmVyVGV4dCk7CiAgICAgICAgfQogICAgICB9CiAgICAgIAogICAgICAvLyBDb3B5IHRoZSBjb2x1bW4gZGF0YSB0byB0aGUgY2xpcGJvYXJkCiAgICAgIHZhciB0ZXh0YXJlYSA9IGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoInRleHRhcmVhIik7CiAgICAgIHRleHRhcmVhLnRleHRDb250ZW50ID0gY29sdW1uRGF0YS5qb2luKCJcbiIpOwogICAgICBkb2N1bWVudC5ib2R5LmFwcGVuZENoaWxkKHRleHRhcmVhKTsKICAgICAgdGV4dGFyZWEuc2VsZWN0KCk7CiAgICAgIGRvY3VtZW50LmV4ZWNDb21tYW5kKCJjb3B5Iik7CiAgICAgIGRvY3VtZW50LmJvZHkucmVtb3ZlQ2hpbGQodGV4dGFyZWEpOwogICAgICAKICAgICAgYWxlcnQoIkNvbnRlbnQgY29waWVkIHRvIGNsaXBib2FyZCEiKTsKICAgIH0KICA8L3NjcmlwdD4KPC9oZWFkPgo8Ym9keT4KICA8aDE+TU1EIEJvbmUgUmVuYW1lciBUb29sPC9oMT4KICAKICA8Zm9ybSBpZD0icGFyc2UtZm9ybSI+CiAgICA8bGFiZWwgZm9yPSJjc3YtdXJsIj5DU1YgVVJMOjwvbGFiZWw+CiAgICA8aW5wdXQgdHlwZT0idGV4dCIgaWQ9ImNzdi11cmwiIHZhbHVlPSJodHRwczovL3J5M3lyLmdpdGh1Yi5pby9tbWRib25lbmFtZXMuY3N2Ij4KICAgIDxicj48YnI+CiAgICA8bGFiZWwgZm9yPSJpbnB1dC10ZXh0Ij5JbnB1dCBUZXh0OjwvbGFiZWw+CiAgICA8YnI+CiAgICA8dGV4dGFyZWEgaWQ9ImlucHV0LXRleHQiIHBsYWNlaG9sZGVyPSJQYXN0ZSBub24gamFwYW5lc2UgYm9uZSBuYW1lcyBoZXJlIj48L3RleHRhcmVhPgogICAgPGJyPgogICAgPGlucHV0IHR5cGU9InN1Ym1pdCIgdmFsdWU9IlN1Ym1pdCI+CiAgPC9mb3JtPgogIAogIDxkaXYgaWQ9Im91dHB1dCI+PC9kaXY+CjwvYm9keT4KPC9odG1sPg== --> _________________________ Bank Saldo Fetch ---------------- <script> function fetchValues() { const inputText = document.getElementById('inputText').value; const euroRegex = /-(\d+(?:,\d+)?)\s*EUR/g; const dateRegex = /^(?!.*Valuta).*\b\d{1,2}\.\s.*$/gm; const euroMatches = Array.from(inputText.matchAll(euroRegex), match => match[1]); const dateMatches = Array.from(inputText.matchAll(dateRegex), match => match[0]); let result = '<table>'; result += '<tr><th>€</th><th>Date</th><th>Text</th></tr>'; for (let i = 1; i < euroMatches.length; i++) { const startIndex = inputText.indexOf(euroMatches[i - 1]); const endIndex = inputText.indexOf(euroMatches[i], startIndex + euroMatches[i - 1].length); let textBetweenMatches = inputText.substring(startIndex + euroMatches[i - 1].length + 1, endIndex).trim(); const truncatedText = textBetweenMatches.substring(0, 45); result += `<tr><td>${euroMatches[i]}€</td><td>${dateMatches[i] ? dateMatches[i].replace(/[•Valuata]/g, '') : ''}</td><td>${truncatedText}</td></tr>`; } result += '</table>'; document.getElementById('result').innerHTML = result; } </script> </head> <body> <textarea id="inputText" rows="10" cols="50" placeholder="Bank Saldo Fetch"></textarea><br> <button onclick="fetchValues()">Fetch Values</button><br> <div id="result"></div> <div id="output"></div> <button onclick="calculateTotals()">Calculate Subtotal</button> <script> function calculateTotals() { const divContent = document.getElementById('result').textContent; const lines = divContent.split('\n'); let totalAll = 0; let totalNettoVMarkt = 0; for (let i = 0; i < lines.length; i++) { const line = lines[i]; const euroValueMatch = line.match(/[0-9,]+\u20AC/); const vendorMatch = line.match(/Netto|V-MARKT/); if (euroValueMatch) { const euroValue = parseFloat(euroValueMatch[0]); totalAll += euroValue; } if (euroValueMatch && vendorMatch) { const euroValue = parseFloat(euroValueMatch[0]); totalNettoVMarkt += euroValue; } } console.log('Total All:', totalAll.toFixed(2) + '€'); console.log('Total Netto + V-MARKT:', totalNettoVMarkt.toFixed(2) + '€'); var outputElement = document.getElementById('output'); var totalAllParagraph = document.createElement('p'); totalAllParagraph.textContent = 'Total All: ' + totalAll.toFixed(2) + '€'; outputElement.appendChild(totalAllParagraph); var totalNettoVMarktParagraph = document.createElement('p'); totalNettoVMarktParagraph.textContent = 'Total Netto + V-MARKT: ' + totalNettoVMarkt.toFixed(2) + '€'; outputElement.appendChild(totalNettoVMarktParagraph); } </script> ______________ Imagejoiner (ImageMagick replacement) ------------------------------------- <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/min/dropzone.min.css"> <style> canvas { width: auto; height: auto; max-width: 100%; max-height: 100%; } </style> </head> <body> <div id="myDropzone" class="dropzone"></div> <div> <input type="radio" name="orientation" value="horizontal" id="radioHorizontal"> <label for="radioHorizontal">Horizontal</label> <input type="radio" name="orientation" value="vertical" id="radioVertical"> <label for="radioVertical">Vertical</label> <br> <input type="checkbox" id="resizeCheckbox"> <label for="resizeCheckbox">Resize smaller images to largest</label> <br> <button id="joinButton">Join Images</button> </div> <div id="imageInfo"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/min/dropzone.min.js"></script> <script> Dropzone.autoDiscover = false; var myDropzone = new Dropzone("#myDropzone", { url: "#", autoProcessQueue: false, maxFiles: 5, acceptedFiles: "image/*", init: function () { var joinButton = document.querySelector("#joinButton"); var radioHorizontal = document.querySelector("#radioHorizontal"); var radioVertical = document.querySelector("#radioVertical"); var resizeCheckbox = document.querySelector("#resizeCheckbox"); var imageFiles = []; this.on("addedfile", function (file) { imageFiles.push(file); }); joinButton.addEventListener("click", function () { var selectedOrientation = radioHorizontal.checked ? "horizontal" : "vertical"; var resizeImages = resizeCheckbox.checked; joinImages(selectedOrientation, resizeImages, imageFiles); }); } }); function joinImages(orientation, resizeImages, imageFiles) { if (imageFiles.length > 1) { var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); var loadedImages = 0; var images = []; // Load the images imageFiles.forEach(function (file) { var img = new Image(); img.onload = function () { loadedImages++; images.push(img); if (loadedImages === imageFiles.length) { var totalWidth = 0; var maxHeight = 0; // Calculate the total width and maximum height of the images images.forEach(function (image) { totalWidth += image.width; maxHeight = Math.max(maxHeight, image.height); }); if (orientation === "horizontal") { canvas.width = totalWidth; canvas.height = maxHeight; } else { if (resizeImages) { // Resize smaller images to match the largest image's height var maxWidth = Math.max(...images.map(img => img.width)); images.forEach(function (image) { if (image.height < maxHeight) { var scaleFactor = maxHeight / image.height; image.width *= scaleFactor; image.height = maxHeight; } }); } canvas.width = Math.max(...images.map(img => img.width)); canvas.height = maxHeight * images.length; } var offsetX = 0; var offsetY = 0; // Draw the images onto the canvas based on the orientation images.forEach(function (img) { if (orientation === "horizontal") { ctx.drawImage(img, offsetX, 0); offsetX += img.width; } else { ctx.drawImage(img, 0, offsetY); offsetY += img.height; } }); var resultContainer = document.getElementById("imageInfo"); resultContainer.innerHTML = ""; resultContainer.appendChild(canvas); } }; img.src = URL.createObjectURL(file); }); } } </script> </body> </html> <!---Download--image--> <button id="downloadButton">Download Joined Image</button> <script> var downloadButton = document.querySelector("#downloadButton"); downloadButton.addEventListener("click", function () { var canvas = document.querySelector("canvas"); var image = canvas.toDataURL("image/png"); var a = document.createElement("a"); a.href = image; a.download = "Download.png"; a.click(); }); </script> _____________________________________ Link to Sitepart ----------------------- <a target="_blank" href="https://alceawis.de/sitepartdisplay.html?url=https%3A%2F%2Falceawis.de%2FHobbies&pattern1=Hobbies&pattern2=Tools" style=color:blue>Example</a><br><br> <details><summary>Create Link</summary> <!DOCTYPE html> <html> <head> <title>Link to Sitepart</title> <script> function generateUrl() { // Get the values from the textboxes const url = document.getElementById("url").value; const pattern1 = document.getElementById("pattern1").value; const pattern2 = document.getElementById("pattern2").value; const generatedUrl = `sitepartdisplay.html?url=${encodeURIComponent(url)}&pattern1=${(pattern1)}&pattern2=${(pattern2)}`; const generatedUrlFin = `<a target="_blank" href="${generatedUrl}" style="color: blue">${generatedUrl}</a>`; document.getElementById("generatedUrl").innerHTML = generatedUrlFin; // Redirect to the generated URL //window.open(generatedUrl, "_blank"); } </script> </head> <body> <h1>LinkToSitepart</h1> <p>Enter the details below to generate the URL:</p> <label for="url">URL:</label> <input type="text" id="url" name="url"> <label for="pattern1">Pattern 1:</label> <input type="text" id="pattern1" name="pattern1"> <label for="pattern2">Pattern 2:</label> <input type="text" id="pattern2" name="pattern2"> <p>Generated URL: <span id="generatedUrl"></span></p> <button onclick="generateUrl()">Generate URL</button> </body> </html> </details> <div id="content"></div> <script> const urlParams = new URLSearchParams(window.location.search); const url = urlParams.get("url"); const pattern1 = urlParams.get("pattern1"); const pattern2 = urlParams.get("pattern2"); fetch(url) .then(response => response.text()) .then(data => { const start = data.indexOf(pattern1) + pattern1.length; const end = data.indexOf(pattern2); const content = data.substring(start, end); const tempElement = document.createElement("div"); tempElement.innerHTML = content; const relativeUrls = tempElement.querySelectorAll("a[href], img[src]"); relativeUrls.forEach(url => { const originalUrl = url.getAttribute("href") || url.getAttribute("src"); const absoluteUrl = new URL(originalUrl, window.location.href).href; url.setAttribute("href", absoluteUrl); url.setAttribute("src", absoluteUrl);}); document.getElementById("content").appendChild(tempElement);}); </script> </body> </html> ____________________ Youtube Timestamp extractor (+FFMPEG command generator) for music album dlds: -------------------------------- <!DOCTYPE html> <html> <head> <title>Extract Timestamps</title> </head> <body> Extract Timestamps from YT Videodescriptions<br> <br> <label for="apiKey">API Key:</label> <input type="password" id="apiKey"> <label for="videoUrl">YouTube Video URL:</label> <input type="text" id="videoUrl" placeholder="yturl"> <input type="text" id="videolength" placeholder="videolength" style="width: 60px;"> <button onclick="extractTimestamps()">Extract Timestamps</button> <br><br><textarea id="timestamps" rows="10" cols="50"></textarea> <script> function extractTimestamps() { var apiKey = document.getElementById("apiKey").value; var videoUrl = document.getElementById("videoUrl").value; if (!apiKey || !videoUrl) { alert("Please enter the API key and video URL."); return; } var videoId = extractVideoId(videoUrl); var apiUrl = `https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=${videoId}&key=${apiKey}`; fetch(apiUrl) .then(response => response.json()) .then(data => { var description = data.items[0].snippet.description; var timestampsAndTitles = extractTimestampsAndTitles(description); var timestampsTextArea = document.getElementById("timestamps"); timestampsTextArea.value = timestampsAndTitles .map(item => `${item.timestamp} ${item.title}`) .join("\n"); var videoDuration = data.items[0].contentDetails.duration; var videoLength = convertISO8601Duration(videoDuration); var videoLengthInput = document.getElementById("videolength"); videoLengthInput.value = videoLength; }) .catch(error => { console.error("Error fetching video details:", error); alert("Error fetching video details. Please check the API key and video URL."); }); } function extractTimestampsAndTitles(description) { var regex = /(\d{1,2}:\d{2}(?::\d{2})?)\s+(.+)/g; var results = []; var match; while ((match = regex.exec(description)) !== null) { var timestamp = match[1]; var title = match[2]; results.push({ timestamp: timestamp, title: title }); } return results; } function extractVideoId(url) { var videoId = ""; var regexPatterns = [ /youtu\.be\/([\w-]+)/, /youtube\.com\/watch\?v=([\w-]+)/, /youtube\.com\/embed\/([\w-]+)/, /youtube\.com\/v\/([\w-]+)/, /youtube\.com\/watch\?.*v=([\w-]+)/ ]; for (var i = 0; i < regexPatterns.length; i++) { var match = url.match(regexPatterns[i]); if (match && match[1]) { videoId = match[1]; break; } } return videoId; } function convertISO8601Duration(duration) { var match = duration.match(/PT(\d+H)?(\d+M)?(\d+S)?/); var hours = match[1] ? parseInt(match[1]) : 0; var minutes = match[2] ? parseInt(match[2]) : 0; var seconds = match[3] ? parseInt(match[3]) : 0; // Format the length as xx:xx var formattedLength = ""; if (hours > 0) { formattedLength += hours.toString().padStart(2, "0") + ":"; } formattedLength += minutes.toString().padStart(2, "0") + ":"; formattedLength += seconds.toString().padStart(2, "0"); return formattedLength; } </script> </body> </html> <hr> <details><summary>Generate FFMPEG</summary> FFMPEG GEnerator <h1>FFmpeg Command Generator</h1> <!--<label for="timestamps">Timestamps:</label><br> <textarea id="timestamps" rows="10" cols="50"></textarea><br><br>--> <label for="sourcefilename">Source Filename:</label><br> <input type="text" id="sourcefilename"><br><br> <button id="submit">Generate Commands</button> <button onclick="replaceText()">Replace Text</button></details><br><br> <pre id="commands"></pre> <script> var timestampsTextarea = document.getElementById('timestamps'); var sourceFilenameTextbox = document.getElementById('sourcefilename'); var submitButton = document.getElementById('submit'); submitButton.addEventListener('click', function() { var timestampsValue = timestampsTextarea.value; var lines = timestampsValue.split('\n'); var sourceFilename = sourceFilenameTextbox.value; var ffmpegCommands = []; for (var i = 0; i < lines.length; i++) { var line = lines[i]; var parts = line.split(' '); var timestamp = parts[0]; var name = parts.slice(1).join(' '); // Generate the FFmpeg command var ffmpegCommand = 'ffmpeg -i "' + sourceFilename + '" -ss ' + timestamp + ' -to ' + (i < lines.length - 1 ? lines[i + 1].split(' ')[0] : '') + ' -c copy "' + name + '.mp3"'; ffmpegCommands.push(ffmpegCommand);} var commandsElement = document.getElementById('commands'); commandsElement.textContent = ffmpegCommands.join('\n'); }); </script> <script> function replaceText() { var commandsElement = document.getElementById("commands"); var videolength = document.getElementById("videolength").value; commandsElement.innerHTML = commandsElement.innerHTML.replace(/-to -c/g, "-to " + videolength + " -c");} </script> _________________________ Fill textbox with ?card= querystring, submit, then stop ------------------------------------------------- <form onsubmit="submitForm()"> <input type="text" name="url" placeholder="Enter URL"> <input id="submit" type="submit" value="Submit"> </form> <!--Testfunction--> <script>function submitForm() {alert('Submitted!');}</script> <script> var urlParams = new URLSearchParams(window.location.search); var card = urlParams.get('card'); if (card !== null && card !== '') { var newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname; //findquerystrings //window.history.replaceState({}, document.title, newUrl); //removequerystrings (all) document.getElementsByName('url')[0].value = card; const submitButton = document.querySelector('input[type="submit"][value="Submit"]'); submitButton.click();} </script> <!--special-idijot-solution--for-kids-who-hate-ampersand-and-only-need-one-querystring- <script> var url = window.location.href; var card = ''; if (url.includes('?card=')) {card = url.split('?card=')[1].replace(/#38;/g, '');} if (card !== null && card !== '') { var newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname; window.history.replaceState({}, document.title, newUrl); document.getElementsByName('url')[0].value = card; document.getElementById('url').value = card; document.getElementById('submit').click(); } </script>--> ____________ Scroll href links right to left (with stop on hover) ----------------------------------------------------- <div id="linksContainer"></div> <script> fetch('pixivreel') .then(response => response.text()) .then(data => { const linksContainer = document.getElementById('linksContainer'); linksContainer.style.display = 'flex'; linksContainer.style.overflow = 'hidden'; const parser = new DOMParser(); const doc = parser.parseFromString(data, 'text/html'); const linkElements = Array.from(doc.querySelectorAll('a')); linkElements.forEach(link => { linksContainer.appendChild(link.cloneNode(true));}); const containerWidth = linksContainer.offsetWidth; let scrollPosition = containerWidth; let isHovered = false; function scrollLinks() { if (!isHovered) { scrollPosition--; if (scrollPosition <= -containerWidth) { scrollPosition = containerWidth;} linksContainer.style.transform = `translateX(${scrollPosition}px)`;} requestAnimationFrame(scrollLinks);} scrollLinks(); linksContainer.addEventListener('mouseenter', () => { isHovered = true;}); linksContainer.addEventListener('mouseleave', () => { isHovered = false;});}) .catch(error => { console.log('Error:', error); }); </script> ______________________ PMX Capable MMD Web Renderer (with stage + multimodelsupport + move stage + vmd2 support)(2024/07/22)(complex8) --------------------------------------------------- =====index.html========== <!--GeneratePmx2Links--> <script> document.addEventListener('DOMContentLoaded', function() { const pmx2linksContainer = document.getElementById('pmx2links'); const links = document.querySelectorAll('a[href*="?pmx="]'); links.forEach(link => { let originalHref = link.getAttribute('href'); let newHref = originalHref.replace('?pmx=', '?pmx2='); const newLink = document.createElement('a'); newLink.textContent = link.textContent; // Copy the text content newLink.setAttribute('href', newHref); // Set the modified href newLink.addEventListener('click', function(event) { event.preventDefault(); // Prevent the default action (navigation) let currentUrl = window.location.href; let newUrl; if (currentUrl.includes('?')) { newUrl = currentUrl + '&' + newHref.split('?')[1]; // Append new query string } else { newUrl = currentUrl + '?' + newHref.split('?')[1]; // Append new query string } window.location.href = newUrl; }); pmx2linksContainer.appendChild(newLink); }); }); </script> <div style="display: flex; flex-direction: row;"> <div id="readystate">...If vmd will cause keychar err, use https://www.mediafire.com/file/9olqch9pazq3fzd/AnimationSmoother.rar...</div> <div id="vmdplay">...</div> <div id="xyzvalue">...</div> </div> <button onclick="togglePhysicsAndReload()">Toggle Physics</button> <script> function togglePhysicsAndReload() { var physicsAreOn = localStorage.getItem("physicsareon"); if (physicsAreOn) { localStorage.removeItem("physicsareon"); } else { localStorage.setItem("physicsareon", "true");} location.reload();} var physicsAreOn = localStorage.getItem("physicsareon"); if (physicsAreOn) { document.querySelector("button").textContent = "Physics On"; } else { document.querySelector("button").textContent = "Physics Off";} </script> <!--<button onclick="clonePMX()">Clone PMX</button>--> <div class="keyboard"> <button id="." onclick="togglePhysicsAndReload()" style="background-color: transparent; border: none;color: transparent;">Move L3.__</button> <button id="moveUpButton">Move Up</button><br> <button id="moveLeftButton">Move Left</button> <button id="moveDownButton">Move Down</button> <button id="moveRightButton">Move Right</button> <button id="." style="background-color: transparent; border: none;color: transparent;">.__</button> <button id="rotateleftButton">RotateLeft</button> <button id="rotaterightButton">RotateRight</button> <a target="_blank" href="https://www.youtube.com/playlist?list=PLBva3abEZvyT-_ajETBGeOCGBA_AFBT5Z#https://www.reddit.com/r/mikumikudance" style=color:blue>r/MMD</a> <a target="_blank" href="https://codepen.io/ryedai1/pens/tags/?selected_tag=mikumikudance" style=color:gray>(tools)</a> (<a target="_blank" href="https://ry3yr.github.io/SampleWebMMD-master.zip" style=color:blue>src-DLD</a>) <!--<a target="_blank" href="http://10.10.10.254/data/UsbDisk1/Volume1/SampleWebMMD-master/index.html?pmx=YusakuFujiki/yusaku.pmx&stage=/livestageclub/livestageclubanimated.pmx&vmd=bts-dna" style=color:blue>Offline-TripMate</a>(<a target="_blank" href="https://alceawis.de/qrgen.html?qr=http://10.10.10.254/data/UsbDisk1/Volume1/SampleWebMMD-master/index.html?pmx=YusakuFujiki/yusaku.pmx&stage=/livestageclub/livestageclubanimated.pmx&vmd=bts-dna" style=color:blue>qr</a>)--> </div> <details> <input type="text" id="buttonvmdInput" value="001" style="width: 100px;"> <button type="button" onclick="copyToClipboard()">Copy</button> <button type="button" onclick="updateQueryStringParameter('vmd', document.getElementById('buttonvmdInput').value);checkfile();">cstm</button> <button type="button" onclick="localStorage.setItem('camid', document.getElementById('buttonvmdInput').value); PoseClickEvent(document.getElementById('buttonvmdInput').value);">cstm+cam</button> <input type="checkbox" id="checkboxSendToPHP"> <label for="checkboxSendToPHP">Send to PHP</label> <!--CopytoClipboard---Code-----> <script> function copyToClipboard() { var inputText = document.getElementById("buttonvmdInput").value; var outputText = '{ id: "' + inputText + '", pose: "' + inputText + '", VmdClip: null, AudioClip: false },'; if (document.getElementById("checkboxSendToPHP").checked) { // Send the output text to mainvmdwrite.php var url = "mainvmdwrite.php"; var xhr = new XMLHttpRequest(); xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { alert("Text sent to mainvmdwrite.php!"); }}; xhr.send("outputText=" + encodeURIComponent(outputText)); } else { navigator.clipboard.writeText(outputText) .then(function() { alert("Text copied to clipboard!");}) .catch(function(error) { console.error("Error copying text: ", error); });}} </script> </details> <script> document.addEventListener('DOMContentLoaded', function() { if (window.self !== window.top) { var copyButton = document.querySelector('button[onclick="copyToClipboard()"]'); copyButton.disabled = true; copyButton.addEventListener('mouseover', function() { var tooltip = document.createElement('span'); tooltip.innerText = 'Disabled by CORS Policy';tooltip.style.position = 'absolute';tooltip.style.backgroundColor = '#000';tooltip.style.color = '#fff';tooltip.style.padding = '5px'; tooltip.style.borderRadius = '4px';tooltip.style.fontSize = '12px';tooltip.style.visibility = 'visible';tooltip.style.top = copyButton.offsetTop + copyButton.offsetHeight + 'px'; tooltip.style.left = copyButton.offsetLeft + 'px';document.body.appendChild(tooltip);}); copyButton.addEventListener('mouseout', function() { var tooltip = document.querySelector('span'); tooltip.parentNode.removeChild(tooltip);});}}); </script> <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> </head> <div class="pose"> <!--<button type="button" value="001" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);">vm1</button>--> <!--<button type="button" value="001" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);">vm1</button>--> <button type="button" value="001" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);location.reload();">vm1</button> <button type="button" value="002" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);location.reload();">vm2</button> <button type="button" value="003" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);location.reload();">vm3(camoff)</button> <button type="button" value="004walknthink" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);location.reload();">vm4</button> <button type="button" value="005hard-carry" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);location.reload();">tst(audio)</button> <button type="button" value="bts-bestofme" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);location.reload();">best(audio)</button> </div> <details><summary>All Motions</summary><div class="file-buttons" id="file-buttons"></div></details> <script> function updateQueryStringParameter(key, value) { var url = new URL(window.location.href); var params = new URLSearchParams(url.search); params.set(key, value); url.search = params.toString(); history.replaceState(null, '', url.toString());} </script> <!--<button id="loadButton" value="./vmd/002.vmd">Load VMD File</button>--> <a href="?pmx=YusakuFujiki/yusaku.pmx">Yu</a> <a href="?pmx=AoiZaizen/AoiZaizen.pmx">Aoi</a> <a href="?pmx=Xion/xion.pmx">Xion</a> <a href="?pmx=9s/9s.pmx">9s</a> <a href="?pmx=2b/na_2b_0418n.pmx">2B</a> <a href="?pmx=TLoZ_Zelda_(Scholar)/zelda_scholar.pmx">BOTW Zelda</a> <a href="?pmx=TLoZ_Zelda_(Skyward_Sword)/Zelda_(Skyward_Sword).pmx">SW Zelda</a> <a href="?pmx=TLoZ_Link_BOTW)/linkbotw.pmx">BOTW Link</a> <a href="?pmx=kh_roxas/kh_roxas.pmx">Roxas</a> <a href="?pmx=off/off.pmx">-[OFF]-</a> <button class="off-button" onclick="window.location.href='?pmx=YusakuFujiki/yusaku.pmx&pmx2=AoiZaizen/AoiZaizen.pmx';" style="background-color: #ffcccc; border: #ff9999; border-radius: 8px; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; transition-duration: 0.4s;">yusaao</button> <button class="off-button" onclick="window.location.href='?pmx=Xion%2Fxion.pmx&pmx2=Roxas%2Froxas.pmx';" style="background-color: #ffcccc; border: #ff9999; border-radius: 8px; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; transition-duration: 0.4s;">Xion&Rox</button> <button onclick="window.location.href='?pmx=YusakuFujiki%2Fyusaku.pmx&pmx2=AoiZaizen%2FAoiZaizen.pmx&stage=%2Flivestageclub%2Flivestageclubanimated.pmx&vmd=30sechug&vmd2=30sechug_2';">yusao-hug</button> </div> <details><summary>2ndChara</summary><div id="pmx2links"></div></details> <div style="display: flex; flex-direction: row;"> <button id="play" onclick="renderer.domElement.requestFullscreen()" style="background-color: pink; background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.25) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.25) 50%, rgba(255, 255, 255, 0.25) 75%, transparent 75%, transparent); background-size: 20px 20px; border: none; color: white; padding: 10px 20px; font-size: 16px; font-weight: bold; border-radius: 5px; box-shadow: 0 0 10px rgba(255, 105, 180, 0.5); cursor: pointer; transition: transform 0.3s;" title="Spacebar">Play Animation and Audio</button> <button id="fullscreenButton" title="F10" style="opacity: 0.2; transition: opacity 0.3s; background-color: #007BFF; border: none; padding: 10px 20px; border-radius: 5px;">Fullscreen</button> <label class="switch"><input type="checkbox" id="toggleSwitch" title="extras yes/no"><span class="slider"></span></label>Face/Lips/Extras: <span id="statusValue">Unknown</span> </div> <!---Toggle-extraz--localstorage-value-between-yes-and-no--> <style> .switch{position:relative;display:inline-block;width:60px;height:34px}.slider,.slider:before{position:absolute;transition:.4s}.switch input{opacity:0;width:0;height:0}.slider{cursor:pointer;top:0;left:0;right:0;bottom:0;background-color:#ccc;border-radius:34px}.slider:before{content:"";height:26px;width:26px;border-radius:50%;left:4px;bottom:4px;background-color:#fff}input:checked+.slider{background-color:#2196f3}input:checked+.slider:before{transform:translateX(26px)} </style> <script> function updateStatus(isChecked) { const statusValue = isChecked ? 'yes' : 'no'; localStorage.setItem('extraz', statusValue); document.getElementById('statusValue').textContent = statusValue;} function loadStatus() { const storedValue = localStorage.getItem('extraz'); const isChecked = storedValue === 'yes'; document.getElementById('toggleSwitch').checked = isChecked; updateStatus(isChecked);} document.getElementById('toggleSwitch').addEventListener('change', (event) => { updateStatus(event.target.checked); }); // Ensure the function is called after the DOM is fully loaded document.addEventListener('DOMContentLoaded', loadStatus); </script> <!----Check VMD File--Existance---> <!--<button id="checkFileButton" onclick="checkfile()">Check File</button>--> <script> function getQueryStringParameter(name) { const urlParams = new URLSearchParams(window.location.search); return urlParams.get(name);} async function checkFileExistence(filePath) { try { const response = await fetch(filePath, { method: 'HEAD' }); if (response.ok) { console.log(`File exists: ${filePath}`); document.getElementById('readystate').textContent = `File exists: ${filePath}`; location.reload(); } else { console.log(`File does not exist (404): ${filePath}`); document.getElementById('readystate').textContent = `File doesn't exist: ${filePath}`;} } catch (error) { console.error(`Error fetching file: ${error}`); document.getElementById('readystate').textContent = `Error fetching file: ${error}`;}} function checkfile() { const vmd = getQueryStringParameter('vmd'); if (vmd) { const filePath = `./vmd/${vmd}.vmd`; checkFileExistence(filePath); } else { console.log('No vmd parameter found in the query string.'); document.getElementById('readystate').textContent = 'No vmd parameter found in the query string.';}} const domContentLoadedHandler = () => { checkfile(); }; </script> <!--AudioPlayback--ThreeJS-ver--> <script> async function playAnimationAndAudio() { const urlParams = new URLSearchParams(window.location.search); const vmdValue = urlParams.get('vmd'); if (!vmdValue) { console.log('No vmd parameter found in the URL'); return false; } console.log('vmdValue from URL:', vmdValue); const audioPath = `audio/${vmdValue}.mp3`; const audioListener = new THREE.AudioListener(); const audio = new THREE.Audio(audioListener); const audioLoader = new THREE.AudioLoader(); // Load audio file try { const audioBuffer = await new Promise((resolve, reject) => { audioLoader.load(audioPath, resolve, onAudioLoadProgress, reject); }); audio.setBuffer(audioBuffer); audio.setLoop(true); // Set to true if audio should loop audio.setVolume(1.0); // Adjust volume as needed audio.play(); console.log('Audio loaded and playing:', audioPath); } catch (error) { console.error('Error loading audio:', error); return false; } // Function to handle audio load progress (optional) function onAudioLoadProgress(xhr) { if (xhr.lengthComputable) { const percentComplete = (xhr.loaded / xhr.total) * 100; console.log('Audio load progress:', percentComplete.toFixed(2) + '%'); } } const clock = new THREE.Clock(); function update() { const delta = clock.getDelta(); } update(); return true; } </script> <!--AudioPlayback--non-ThreeJS-ver--> <!-- <script> function playAnimationAndAudio() { var urlParams = new URLSearchParams(window.location.search); var vmdValue = urlParams.get('vmd'); if (vmdValue) { var audioPath = 'audio/' + vmdValue + '.mp3'; if (window.audioElement && !window.audioElement.paused) { window.audioElement.currentTime = 0; } else { setTimeout(500); window.audioElement = new Audio(audioPath); audioElement.loop = true; } window.audioElement.play(); console.log('Animation triggered'); } else { console.log('No vmd parameter found in the URL');}} </script> --> <div class="stage"> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/herogarden/herogarden.pmx';window.location.href = updatedUrl;})()">herogarden</a> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/parkavenue/parkavenue.pmx';window.location.href = updatedUrl;})()">parkavenue</a> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/livestageclub/livestageclubanimated.pmx';window.location.href = updatedUrl;})()">LiveStage</a> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/h2cu09/h2cu09.pmx';window.location.href = updatedUrl;})()">h2cu09</a> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/SciFi_Cube/SciFi_Cube.pmx';window.location.href = updatedUrl;})()">SciFi_Cube</a> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/kh_twilighttown/kh_station_plaza/Station_Plaza.pmx';window.location.href = updatedUrl;})()">TwilightTownStation</a> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/([?&])stage=[^&]*/g, '$1').replace(/(&|\?)$/, '');var newStageParam = encodeURIComponent('/kh_twtnw/Memory\'s_Skyscraper/Memory\'s_Skyscraper.pmx');updatedUrl += (updatedUrl.indexOf('?') > -1 ? '&' : '?') + 'stage=' + newStageParam;window.location.href = updatedUrl;})()">TWTNW Skyscraper</a> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/palette_stage/palette_stage.pmx';window.location.href = updatedUrl;})()">palette_stage</a> <a href target="_blank" ="#" onclick="redirectToTargetURL();"><b>[TestStageCoordinates]</b></a> </div> <!--redirect--coordinates--for--stage--> <script> function redirectToTargetURL() { var currentURL = window.location.href; var targetURL = "stageloader.html"; var queryParams = currentURL.split("?")[1]; var finalURL = targetURL + "?" + queryParams; window.open(finalURL, "_blank"); } </script> <script src="./libs/three.js"></script> <script src="./libs/mmdparser.min.js"></script> <script src="./libs/ammo.min.js"></script> <script src="./libs/TGALoader.js"></script> <script src="./libs/MMDLoader.js"></script> <script src="./libs/MMDAnimationHelper.js"></script> <script src="./libs/mmd-loader.min.js"></script> <script src="./libs/CCDIKSolver.js"></script> <script src="./libs/MMDPhysics.js"></script> <!--<script src="./libs/Vmd.js"></script> <script src="./libs/VmdFileParser.js"></script>--> <!--<script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/build/three.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/libs/mmdparser.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/ammo.js@0.0.10/ammo.min.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/loaders/TGALoader.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/loaders/MMDLoader.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/animation/MMDAnimationHelper.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/animation/CCDIKSolver.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/animation/MMDPhysics.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/jsm/controls/OrbitControls.js"></script>--> <script src="./js/main.js"></script> </body> </html> <!----Mark--used-button--green--> <script> window.addEventListener('load', function() { const urlParams = new URLSearchParams(window.location.search); var vmdValue = urlParams.get('vmd'); var buttons = document.querySelectorAll("button"); for (var i = 0; i < buttons.length; i++) {if (buttons[i].value === vmdValue) {buttons[i].style.backgroundColor = "lightgreen";}} }); </script> <!--AllMotions-show---onlineCompOnly---> <script> const fileDir = './vmd'; function listFiles() { const fileButtonsContainer = document.getElementById('file-buttons'); fetch(fileDir) .then(response => response.text()) .then(data => { const doc = new DOMParser().parseFromString(data, 'text/html'); const files = [...doc.getElementsByTagName('a')]; files .map(file => file.textContent.trim()) .filter(fileName => fileName.endsWith('.vmd')) .forEach(fileName => { const button = document.createElement('button'); button.type = 'button'; button.value = fileName; button.textContent = fileName.replace('.vmd', ''); button.onclick = () => { updateQueryStringParameter('vmd', fileName.replace('.vmd', '')); location.reload();}; fileButtonsContainer.appendChild(button);});}) .catch(error => { console.error('Error listing files:', error); });} function updateQueryStringParameter(key, value) { const url = new URL(window.location.href); url.searchParams.set(key, value); window.history.replaceState({}, '', url.toString());} window.addEventListener('load', listFiles); </script> <!--keyboard-shortcuts--f10--spacebar--> <script> document.addEventListener('DOMContentLoaded', function() { document.addEventListener('keydown', function(event) { if (event.key === 'F10') { event.preventDefault(); // Prevent default action (fullscreen mode) renderer.domElement.requestFullscreen()}}); document.addEventListener('keydown', function(event) { if (event.key === ' ') { // Spacebar key event.preventDefault(); // Prevent default action (scrolling the page) document.getElementById('play').click();}});}); </script> =====main.js========== let scene, renderer, camera, mesh, mesh2; let hasLoaded = false; let mixer1, mixer2, clock, cameraAnimation; const windowWidth = window.innerWidth; const windowHeight = window.innerHeight; function getQueryStringValue(key) { const urlParams = new URLSearchParams(window.location.search); return urlParams.get(key); } const pmx = getQueryStringValue('pmx'); const vmdpath = getQueryStringValue('vmd') || "bts-bestofme"; const pmx2 = getQueryStringValue('pmx2') || "AoiZaizen/AoiZaizen.pmx"; const cameraId = getQueryStringValue('camera'); const stage = getQueryStringValue('stage') || "/sorclair/sorclair.pmx"; let Pmx; let Pmx2; //define new camposition globally let xyzglobal = []; let positionXYZ = localStorage.getItem('xyz') || "0, 0, 0"; if (positionXYZ) {xyzglobal = positionXYZ.split(',').map(parseFloat);} if (pmx) { Pmx = `./pmx/pronama/${pmx.trim()}`; console.log(`PMX: ${pmx.trim()}`); } else { console.log("No PMX selected."); } if (pmx2) { Pmx2 = `./pmx/pronama/${pmx2.trim()}`; console.log(`PMX2: ${pmx2.trim()}`); } else { console.log("No PMX2 selected."); } let StagePath = stage ? `./stages/${stage.trim()}` : './stages/sorclair/sorclair.pmx'; if (pmx) { Pmx = `./pmx/pronama/${pmx.trim()}`;console.log(`PMX: ${pmx.trim()}`);} else {console.log("No PMX selected.");} if (pmx2) {Pmx2 = `./pmx/pronama/${pmx2.trim()}`;console.log(`PMX2: ${pmx2.trim()}`);} else {console.log("No PMX2 selected.");} if (StagePath) {StagePath = `./stages${stage.trim()}`;} else {StagePath = './stages/sorclair/sorclair.pmx';} console.log('StagePath:', StagePath); if (StagePath) { const loader = new THREE.MMDLoader(); const lastIndex = StagePath.lastIndexOf("/"); const basePath = StagePath.substring(0, lastIndex); const vmd1Path = `${basePath}/001.vmd`; const vmd2Path = `${basePath}/002.vmd`; loader.load(StagePath, (stageObject) => { var ambientLight = new THREE.AmbientLight(0xffffff, 1.0); //hardcoded scene.add(ambientLight); scene.add(stageObject); //set stage pos. let positionXYZ = localStorage.getItem('xyz') || "0, 0, 0"; let xyzArray = []; if (positionXYZ) {xyzArray = positionXYZ.split(',').map(parseFloat);} let x, y, z; if (xyzArray.length === 3 && xyzArray.every(coord => !isNaN(coord))) {[x, y, z] = xyzArray.map((coord, index) => coord + (index === 0 ? -0 : -0));} x = -x; //flip x because we move over 0coordinate //y = 0; //y must always be 0 so we do not fall under the stage z= -z; //flip x because we move over 0coordinate stageObject.position.set(x, y, z); const mixer = new THREE.AnimationMixer(stageObject); loader.loadAnimation(vmd1Path, stageObject, (vmd1Clip) => { vmd1Clip.name = "001"; console.log(`Loaded VMD: ${vmd1Path}`); const motionObject1 = MotionObjects.find(obj => obj.id === "001"); if (motionObject1) { motionObject1.VmdClip = vmd1Clip; const action1 = mixer.clipAction(vmd1Clip); action1.play(); } else { console.warn(`Motion object with id "001" not found.`); } }, onProgress, onError); loader.loadAnimation(vmd2Path, stageObject, (vmd2Clip) => { vmd2Clip.name = "002"; console.log(`Loaded VMD: ${vmd2Path}`); const motionObject2 = MotionObjects.find(obj => obj.id === "002"); if (motionObject2) { motionObject2.VmdClip = vmd2Clip; const action2 = mixer.clipAction(vmd2Clip); action2.play(); } else { console.warn(`Motion object with id "002" not found.`); } }, onProgress, onError); const clock = new THREE.Clock(); const animate = () => { requestAnimationFrame(animate); const delta = clock.getDelta(); mixer.update(delta); renderer.render(scene, camera); }; animate(); }, onProgress, onError); } else {console.warn('No valid stage path found.');} //if (!Stage) {Stage = stage ? `stages${stage}` : '/sorclair/sorclair.pmx';} if (!Pmx) {Pmx = `./pmx/pronama/AoiZaizen/AoiZaizen.pmx`;} console.log('StagePath:', StagePath); const MotionObjects = [ { id: "001", pose: "001", VmdClip: null, AudioClip: false }, { id: "002", pose: "002", VmdClip: null, AudioClip: false }, ]; window.onload = () => { Init(); LoadStage().then(() => { LoadModels().then(() => { }); }); }; function Init() { document.getElementById("moveLeftButton").addEventListener("click", () => { camera.position.x -= 1; }); document.getElementById("moveRightButton").addEventListener("click", () => { camera.position.x += 1; }); document.getElementById("moveUpButton").addEventListener("click", () => { camera.position.y += 1; }); document.getElementById("moveDownButton").addEventListener("click", () => { camera.position.y -= 1; }); document.getElementById("rotaterightButton").addEventListener("click", () => { mesh.rotateY(Math.PI / 4); }); document.getElementById("rotateleftButton").addEventListener("click", () => { mesh.rotateY(-Math.PI / 4); }); const storedValue = localStorage.getItem('xyz'); const displayDiv = document.getElementById('xyzvalue'); displayDiv.innerHTML = "<b>&nbsp;XYZ</b>" + storedValue; scene = new THREE.Scene(); renderer = new THREE.WebGLRenderer({ alpha: true }); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); camera = new THREE.PerspectiveCamera(100, windowWidth / windowHeight, 1, 1000); // Initialize camera position //let positionXYZ = localStorage.getItem('xyz'); //let xyzArray = []; //if (positionXYZ) {xyzArray = positionXYZ.split(',').map(parseFloat);} //if (xyzArray.length === 3) { //const [x, y, z] = xyzArray; //camera.position.set(x, y, z);} else { //camera.position.set(0, 19, 20); //} let positionXYZ = localStorage.getItem('xyz'); let xyzArray = []; if (positionXYZ) {xyzArray = positionXYZ.split(',').map(parseFloat);} let x, y, z; if (xyzArray.length === 3 && xyzArray.every(coord => !isNaN(coord))) {[x, y, z] = xyzArray.map((coord, index) => coord + (index === 0 ? 15 : 15)); // Add 15 to x and y } else { x = 0;y = 19;z = 20;} camera.position.set(x, y, z); clock = new THREE.Clock(); } function LoadStage() { return new Promise((resolve, reject) => { const loader = new THREE.MMDLoader(); loader.load(StagePath, (stageObject) => { resolve(); }, onProgress, reject); }); } let animate; function startAnimation() { document.getElementById('readystate').innerHTML = 'Camera(localstorage): ready - ' + localStorage.getItem('vmd') + ' <a href="javascript:location.reload(true)">Reload</a>'; if (!animate) { console.error('Animation function not initialized.'); return; } animate(); // Start the animation loop } document.getElementById('play').addEventListener('click', async () => { const urlParams = new URLSearchParams(window.location.search); const vmdValue = urlParams.get('vmd') || "bts-bestofme"; if (!vmdValue) { console.log('No vmd parameter found in the URL'); return false;} console.log('vmdValue from URL:', vmdValue); const audioPath = `audio/${vmdValue}.mp3`; const audioListener = new THREE.AudioListener(); const audio = new THREE.Audio(audioListener); const audioLoader = new THREE.AudioLoader(); try { const audioBuffer = await new Promise((resolve, reject) => { audioLoader.load(audioPath, resolve, onAudioLoadProgress, reject); }); const loopDuration = parseFloat(localStorage.getItem('vmdplay')); audio.setBuffer(audioBuffer); audio.setLoop(true); // Set to true if audio should loop audio.setVolume(1.0); // Adjust volume as needed audio.play(); console.log('Audio loaded and playing:', audioPath);} catch (error) { console.error('Error loading audio:', error); document.getElementById('readystate').textContent = "Error loading Audio"; return false;} function onAudioLoadProgress(xhr) { if (xhr.lengthComputable) { const percentComplete = (xhr.loaded / xhr.total) * 100; console.log('Audio load progress:', percentComplete.toFixed(2) + '%');}} try { startAnimation(); } catch (error) { console.error('Error loading models:', error);}}); async function LoadModels() { const loader = new THREE.MMDLoader(); function LoadPMX(path) { return new Promise((resolve, reject) => { loader.load(path, (object) => { resolve(object); }, onProgress, reject); });} async function LoadVMDAnimation(mesh, isMesh2 = false) { function getQueryStringParameter(name) { const urlParams = new URLSearchParams(window.location.search); return urlParams.get(name);} const vmdId = getQueryStringParameter('vmd') || 'bts-bestofme'; const vmdId2 = getQueryStringParameter('vmd2') || vmdId; const vmdPaths = isMesh2 ? [ `./vmd/${vmdId2}.vmd`, `./vmd/${vmdId2}_lips.vmd`, `./vmd/${vmdId2}_facials.vmd` ] : [ `./vmd/${vmdId}.vmd`, `./vmd/${vmdId}_lips.vmd`, `./vmd/${vmdId}_facials.vmd` ]; localStorage.setItem('vmd', isMesh2 ? vmdId2 : vmdId); async function fileExists(url) { return new Promise((resolve) => { const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { resolve(xhr.status === 200); } }; xhr.onerror = () => resolve(false); xhr.send(); }); } // Check if 'extraz' is set to 'yes' and adjust paths accordingly const checkExtraz = localStorage.getItem('extraz') === 'yes'; const pathsToCheck = [vmdPaths[0]]; // Always check the base VMD file if (checkExtraz) { pathsToCheck.push(vmdPaths[1], vmdPaths[2]);} const animations = []; for (const path of pathsToCheck) { if (await fileExists(path)) { const vmdClip = await new Promise((resolve, reject) => { loader.loadAnimation(path, mesh, (clip) => { clip.name = path; resolve(clip); }, onProgress, reject);}); animations.push(vmdClip); if (path.includes('_lips') || path.includes('_facials')) { console.log(`Loaded additional VMD: ${path}`);} } else { console.log(`File not found: ${path}`);}} if (animations.length > 0) { const mainAnimation = animations.find(clip => !clip.name.includes('_lips') && !clip.name.includes('_facials')); if (mainAnimation) { const vmdPlayTime = mainAnimation.duration.toFixed(2); // Get the VMD animation duration localStorage.setItem('vmdplay', vmdPlayTime); // Save the VMD play time to localStorage const vmdPlayDiv = document.getElementById('vmdplay'); if (vmdPlayDiv) { vmdPlayDiv.innerHTML = `<b>VMD Playtime:</b> ${vmdPlayTime} seconds`;}} return animations; } else {console.log('No VMD files loaded.'); const readystateDiv = document.getElementById('readystate'); if (readystateDiv) { readystateDiv.textContent = 'MotionError: No valid VMD files found.';} return [];}} async function LoadModel1() { let positionXYZ = localStorage.getItem('xyz') || "0, 0, 0"; let position = new THREE.Vector3(0, 0, 0); if (positionXYZ) { const xyzArray = positionXYZ.split(',').map(parseFloat); if (xyzArray.length === 3) { const [x, y, z] = xyzArray; //camera.position.set(x, y, z); //position.set(x, y, z); } else {console.error('Stored xyz coordinates in localStorage are not in the expected format.');} } else {console.error('No xyz coordinates found in localStorage.');} const mesh = await LoadPMX(Pmx); mesh.position.copy(position); scene.add(mesh); const vmdClip = await LoadVMDAnimation(mesh, false); // Pass false for mesh const helper = new THREE.MMDAnimationHelper({ afterglow: 1.0 }); const mmd = { mesh: mesh, animation: vmdClip }; helper.add(mmd.mesh, { animation: mmd.animation, physics: true }); return { mesh: mesh, helper: helper };} async function LoadModel2() { try {if (!Pmx2) { throw new Error('Pmx2 is not defined.');} let positionXYZ = localStorage.getItem('xyz') || "0, 0, 0"; let position = new THREE.Vector3(0, 0, 0); if (positionXYZ) { const xyzArray = positionXYZ.split(',').map(parseFloat); if (xyzArray.length === 3) { const [x, y, z] = xyzArray; position.set(x, y, z); } else {throw new Error('Stored xyz coordinates in localStorage are not in the expected format.');} } else {throw new Error('No xyz coordinates found in localStorage.');} const mesh2 = await LoadPMX(Pmx2); //mesh2.position.copy(position); //mesh2.position.x += 15; //!new URLSearchParams(window.location.search).has('vmd2') && (mesh2.position.x += 15); mesh2.position.x = parseInt(new URLSearchParams(window.location.search).get('distance')) || (new URLSearchParams(window.location.search).has('vmd2') ? 0 : 15); scene.add(mesh2); const vmdClip = await LoadVMDAnimation(mesh2, true); // Pass true for mesh2 const helper = new THREE.MMDAnimationHelper({ afterglow: 1.0 }); helper.add(mesh2, { animation: vmdClip, physics: true }); return { mesh: mesh2, helper }; } catch (error) { console.error('Error loading model 2:', error); return null;}} async function LoadCameraAnimation(camera) { let camid; if (new URLSearchParams(window.location.search).has('camera')) { camid = new URLSearchParams(window.location.search).get('camera'); } else if (new URLSearchParams(window.location.search).has('vmd')) { camid = new URLSearchParams(window.location.search).get('vmd'); } else { camid = localStorage.getItem('camid'); if (!camid) { camid = 'bts-bestofme';}} const cameraVmdPath = "./camera/" + camid + ".vmd"; try { let positionXYZ = localStorage.getItem('xyz'); let xyzArray = []; if (positionXYZ) {xyzArray = positionXYZ.split(',').map(parseFloat);} let x, y, z; if (xyzArray.length === 3 && xyzArray.every(coord => !isNaN(coord))) {[x, y, z] = xyzArray.map((coord, index) => coord + (index === 0 ? 15 : 15));} //camera.position.set(x, y, z); const vmdClip = await new Promise((resolve, reject) => { loader.loadAnimation(cameraVmdPath, camera, (vmdClip) => { vmdClip.name = camid; resolve(vmdClip);}, onProgress, reject);}); return vmdClip;} catch (error) {console.error('Error loading camera animation:', error); throw error;}} const { mesh: mesh1, helper: helper1 } = await LoadModel1(); const { mesh: mesh2, helper: helper2 } = await LoadModel2(); const fov = 45; // Define the field of view const aspect = window.innerWidth / window.innerHeight; // Define the aspect ratio const near = 1; // Define the near clipping plane const far = 1000; // Define the far clipping plane const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); const cameraVmdClip = await LoadCameraAnimation(camera); const cameraHelper = new THREE.MMDAnimationHelper(); cameraHelper.add(camera, { animation: cameraVmdClip }); const clock = new THREE.Clock(); animate = () => { requestAnimationFrame(animate); const delta = clock.getDelta(); helper1.update(delta); if (helper2) helper2.update(delta); cameraHelper.update(delta); // Update camera animation renderer.render(scene, camera);};} function onProgress(xhr) { if (xhr.lengthComputable) { const percentComplete = xhr.loaded / xhr.total * 100; console.log(Math.round(percentComplete) + '% downloaded'); document.getElementById('readystate').innerHTML = Math.round(percentComplete) + '% downloaded (if stuck, click <a href="audio" target="_blank">here</a>) ' + 'Camera: ready - ' + localStorage.getItem('camid');}} function onError(xhr) { console.error("Error loading resource:", xhr); document.getElementById('readystate').textContent = "Error loading resource: " + xhr.statusText;} fullscreenButton.addEventListener('click', () => { if (!document.fullscreenElement) { //document.body.requestFullscreen(); renderer.domElement.requestFullscreen(); } else { if (document.exitFullscreen) { document.exitFullscreen(); } } }); _______________________________ PMX Capable MMD Web Renderer (with stage + multimodelsupport)(2024/07/13-complete rewrite standalone from prev ver) ----------------------------- Download: https://ry3yr.github.io/SampleWebMMD-master.zip Src: https://codeberg.org/alceawisteria/MMD_Web_Renderer ====main.js=== let scene, renderer, camera, mesh, mesh2; let hasLoaded = false; let mixer1, mixer2, clock, cameraAnimation; const windowWidth = window.innerWidth; const windowHeight = window.innerHeight; function getQueryStringValue(key) { const urlParams = new URLSearchParams(window.location.search); return urlParams.get(key); } const pmx = getQueryStringValue('pmx'); const vmdpath = getQueryStringValue('vmd') || "bts-bestofme"; const pmx2 = getQueryStringValue('pmx2') || "AoiZaizen/AoiZaizen.pmx"; const cameraId = getQueryStringValue('camera'); const stage = getQueryStringValue('stage') || "/sorclair/sorclair.pmx"; let Pmx; let Pmx2; if (pmx) { Pmx = `./pmx/pronama/${pmx.trim()}`; console.log(`PMX: ${pmx.trim()}`); } else { console.log("No PMX selected."); } if (pmx2) { Pmx2 = `./pmx/pronama/${pmx2.trim()}`; console.log(`PMX2: ${pmx2.trim()}`); } else { console.log("No PMX2 selected."); } let StagePath = stage ? `./stages/${stage.trim()}` : './stages/sorclair/sorclair.pmx'; if (pmx) { Pmx = `./pmx/pronama/${pmx.trim()}`;console.log(`PMX: ${pmx.trim()}`);} else {console.log("No PMX selected.");} if (pmx2) {Pmx2 = `./pmx/pronama/${pmx2.trim()}`;console.log(`PMX2: ${pmx2.trim()}`);} else {console.log("No PMX2 selected.");} if (StagePath) {StagePath = `./stages${stage.trim()}`;} else {StagePath = './stages/sorclair/sorclair.pmx';} console.log('StagePath:', StagePath); if (StagePath) { const loader = new THREE.MMDLoader(); const lastIndex = StagePath.lastIndexOf("/"); const basePath = StagePath.substring(0, lastIndex); const vmd1Path = `${basePath}/001.vmd`; const vmd2Path = `${basePath}/002.vmd`; loader.load(StagePath, (stageObject) => { var ambientLight = new THREE.AmbientLight(0xffffff, 1.0); //hardcoded scene.add(ambientLight); scene.add(stageObject); const mixer = new THREE.AnimationMixer(stageObject); loader.loadAnimation(vmd1Path, stageObject, (vmd1Clip) => { vmd1Clip.name = "001"; console.log(`Loaded VMD: ${vmd1Path}`); const motionObject1 = MotionObjects.find(obj => obj.id === "001"); if (motionObject1) { motionObject1.VmdClip = vmd1Clip; const action1 = mixer.clipAction(vmd1Clip); action1.play(); } else { console.warn(`Motion object with id "001" not found.`); } }, onProgress, onError); loader.loadAnimation(vmd2Path, stageObject, (vmd2Clip) => { vmd2Clip.name = "002"; console.log(`Loaded VMD: ${vmd2Path}`); const motionObject2 = MotionObjects.find(obj => obj.id === "002"); if (motionObject2) { motionObject2.VmdClip = vmd2Clip; const action2 = mixer.clipAction(vmd2Clip); action2.play(); } else { console.warn(`Motion object with id "002" not found.`); } }, onProgress, onError); const clock = new THREE.Clock(); const animate = () => { requestAnimationFrame(animate); const delta = clock.getDelta(); mixer.update(delta); renderer.render(scene, camera); }; animate(); }, onProgress, onError); } else {console.warn('No valid stage path found.');} //if (!Stage) {Stage = stage ? `stages${stage}` : '/sorclair/sorclair.pmx';} if (!Pmx) {Pmx = `./pmx/pronama/AoiZaizen/AoiZaizen.pmx`;} console.log('StagePath:', StagePath); const MotionObjects = [ { id: "001", pose: "001", VmdClip: null, AudioClip: false }, ]; window.onload = () => { Init(); LoadStage().then(() => { LoadModels().then(() => { }); }); }; function Init() { document.getElementById("moveLeftButton").addEventListener("click", () => { camera.position.x -= 1; }); document.getElementById("moveRightButton").addEventListener("click", () => { camera.position.x += 1; }); document.getElementById("moveUpButton").addEventListener("click", () => { camera.position.y += 1; }); document.getElementById("moveDownButton").addEventListener("click", () => { camera.position.y -= 1; }); document.getElementById("rotaterightButton").addEventListener("click", () => { mesh.rotateY(Math.PI / 4); }); document.getElementById("rotateleftButton").addEventListener("click", () => { mesh.rotateY(-Math.PI / 4); }); scene = new THREE.Scene(); renderer = new THREE.WebGLRenderer({ alpha: true }); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); camera = new THREE.PerspectiveCamera(100, windowWidth / windowHeight, 1, 1000); camera.position.set(0, 19, 20); clock = new THREE.Clock(); } function LoadStage() { return new Promise((resolve, reject) => { const loader = new THREE.MMDLoader(); loader.load(StagePath, (stageObject) => { resolve(); }, onProgress, reject); }); } let animate; function startAnimation() { document.getElementById('readystate').innerHTML = 'Camera(localstorage): ready - ' + localStorage.getItem('vmd') + ' <a href="javascript:location.reload(true)">Reload</a>'; if (!animate) { console.error('Animation function not initialized.'); return; } animate(); // Start the animation loop } document.getElementById('play').addEventListener('click', async () => { const urlParams = new URLSearchParams(window.location.search); const vmdValue = urlParams.get('vmd') || "bts-bestofme"; if (!vmdValue) { console.log('No vmd parameter found in the URL'); return false;} console.log('vmdValue from URL:', vmdValue); const audioPath = `audio/${vmdValue}.mp3`; const audioListener = new THREE.AudioListener(); const audio = new THREE.Audio(audioListener); const audioLoader = new THREE.AudioLoader(); try { const audioBuffer = await new Promise((resolve, reject) => { audioLoader.load(audioPath, resolve, onAudioLoadProgress, reject); }); audio.setBuffer(audioBuffer); audio.setLoop(true); // Set to true if audio should loop audio.setVolume(1.0); // Adjust volume as needed audio.play(); console.log('Audio loaded and playing:', audioPath); } catch (error) { console.error('Error loading audio:', error); document.getElementById('readystate').textContent = "Error loading Audio"; return false; } function onAudioLoadProgress(xhr) { if (xhr.lengthComputable) { const percentComplete = (xhr.loaded / xhr.total) * 100; console.log('Audio load progress:', percentComplete.toFixed(2) + '%'); }} try { startAnimation(); } catch (error) { console.error('Error loading models:', error); } }); async function LoadModels() { const loader = new THREE.MMDLoader(); function LoadPMX(path) { return new Promise(resolve => { loader.load(path, (object) => { resolve(object); }, onProgress, onError); }); } async function LoadVMDAnimation(mesh, id) { function getQueryStringParameter(name) { const urlParams = new URLSearchParams(window.location.search); return urlParams.get(name); } const vmdId = getQueryStringParameter('vmd') || 'bts-bestofme'; const vmdPath = `./vmd/${vmdId}.vmd`; localStorage.setItem('vmd', vmdId); return new Promise((resolve, reject) => { loader.loadAnimation(vmdPath, mesh, (vmdClip) => { vmdClip.name = vmdId; resolve(vmdClip); }, onProgress, reject); }); } async function LoadCameraAnimation(camera) { let camid; if (new URLSearchParams(window.location.search).has('camera')) { camid = new URLSearchParams(window.location.search).get('camera'); } else if (new URLSearchParams(window.location.search).has('vmd')) { camid = new URLSearchParams(window.location.search).get('vmd'); } else { camid = localStorage.getItem('camid'); if (!camid) { camid = 'bts-bestofme'; } } const cameraVmdPath = "./camera/" + camid + ".vmd"; try { const vmdClip = await new Promise((resolve, reject) => { loader.loadAnimation(cameraVmdPath, camera, (vmdClip) => { vmdClip.name = camid; // Set the name to the loaded camid resolve(vmdClip); }, onProgress, reject); }); return vmdClip; } catch (error) { console.error('Error loading camera animation:', error); throw error; // Re-throw the error to propagate it } } async function LoadModel1() { const mesh = await LoadPMX(Pmx); scene.add(mesh); const vmdClip = await LoadVMDAnimation(mesh, "001"); const helper = new THREE.MMDAnimationHelper({ afterglow: 1.0 }); const mmd = { mesh: mesh, animation: vmdClip }; helper.add(mmd.mesh, { animation: mmd.animation, physics: true }); return { mesh: mesh, helper: helper }; } async function LoadModel2() { if (Pmx2) { const mesh2 = await LoadPMX(Pmx2); mesh2.position.x += 15; scene.add(mesh2); const vmdClip = await LoadVMDAnimation(mesh2, "002"); const helper = new THREE.MMDAnimationHelper({ afterglow: 1.0 }); const mmd = { mesh: mesh2, animation: vmdClip }; helper.add(mmd.mesh, { animation: mmd.animation, physics: true }); return { mesh: mesh2, helper: helper }; } } const { mesh: mesh1, helper: helper1 } = await LoadModel1(); const { mesh: mesh2, helper: helper2 } = await LoadModel2(); const fov = 45; // Define the field of view const aspect = window.innerWidth / window.innerHeight; // Define the aspect ratio const near = 1; // Define the near clipping plane const far = 1000; // Define the far clipping plane const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); const cameraVmdClip = await LoadCameraAnimation(camera); const cameraHelper = new THREE.MMDAnimationHelper(); cameraHelper.add(camera, { animation: cameraVmdClip }); const clock = new THREE.Clock(); animate = () => { requestAnimationFrame(animate); const delta = clock.getDelta(); helper1.update(delta); if (helper2) helper2.update(delta); cameraHelper.update(delta); // Update camera animation renderer.render(scene, camera); }; } function onProgress(xhr) { if (xhr.lengthComputable) { const percentComplete = xhr.loaded / xhr.total * 100; console.log(Math.round(percentComplete) + '% downloaded'); document.getElementById('readystate').innerHTML = Math.round(percentComplete) + '% downloaded (if stuck, click <a href="audio" target="_blank">here</a>) ' + 'Camera: ready - ' + localStorage.getItem('camid'); } } function onError(xhr) { console.error("Error loading resource:", xhr); document.getElementById('readystate').textContent = "Error loading resource: " + xhr.statusText; } fullscreenButton.addEventListener('click', () => { if (!document.fullscreenElement) { //document.body.requestFullscreen(); renderer.domElement.requestFullscreen(); } else { if (document.exitFullscreen) { document.exitFullscreen(); } } }); ===========index.htm.====== <!--GeneratePmx2Links--> <script> document.addEventListener('DOMContentLoaded', function() { const pmx2linksContainer = document.getElementById('pmx2links'); const links = document.querySelectorAll('a[href*="?pmx="]'); links.forEach(link => { let originalHref = link.getAttribute('href'); let newHref = originalHref.replace('?pmx=', '?pmx2='); const newLink = document.createElement('a'); newLink.textContent = link.textContent; // Copy the text content newLink.setAttribute('href', newHref); // Set the modified href newLink.addEventListener('click', function(event) { event.preventDefault(); // Prevent the default action (navigation) let currentUrl = window.location.href; let newUrl; if (currentUrl.includes('?')) { newUrl = currentUrl + '&' + newHref.split('?')[1]; // Append new query string } else { newUrl = currentUrl + '?' + newHref.split('?')[1]; // Append new query string } window.location.href = newUrl; }); pmx2linksContainer.appendChild(newLink); }); }); </script> <div id="readystate">...If vmd will cause keychar err, use https://www.mediafire.com/file/9olqch9pazq3fzd/AnimationSmoother.rar...</div> <button onclick="togglePhysicsAndReload()">Toggle Physics</button> <script> function togglePhysicsAndReload() { var physicsAreOn = localStorage.getItem("physicsareon"); if (physicsAreOn) { localStorage.removeItem("physicsareon"); } else { localStorage.setItem("physicsareon", "true");} location.reload();} var physicsAreOn = localStorage.getItem("physicsareon"); if (physicsAreOn) { document.querySelector("button").textContent = "Physics On"; } else { document.querySelector("button").textContent = "Physics Off";} </script> <!--<button onclick="clonePMX()">Clone PMX</button>--> <div class="keyboard"> <button id="." onclick="togglePhysicsAndReload()" style="background-color: transparent; border: none;color: transparent;">Move L3.__</button> <button id="moveUpButton">Move Up</button><br> <button id="moveLeftButton">Move Left</button> <button id="moveDownButton">Move Down</button> <button id="moveRightButton">Move Right</button> <button id="." style="background-color: transparent; border: none;color: transparent;">.__</button> <button id="rotateleftButton">RotateLeft</button> <button id="rotaterightButton">RotateRight</button> <a target="_blank" href="https://www.youtube.com/playlist?list=PLBva3abEZvyT-_ajETBGeOCGBA_AFBT5Z#https://www.reddit.com/r/mikumikudance" style=color:blue>r/MMD</a> <a target="_blank" href="https://codepen.io/ryedai1/pens/tags/?selected_tag=mikumikudance" style=color:gray>(tools)</a> (<a target="_blank" href="https://ry3yr.github.io/SampleWebMMD-master.zip" style=color:blue>src-DLD</a>) <!--<a target="_blank" href="http://10.10.10.254/data/UsbDisk1/Volume1/SampleWebMMD-master/index.html?pmx=YusakuFujiki/yusaku.pmx&stage=/livestageclub/livestageclubanimated.pmx&vmd=bts-dna" style=color:blue>Offline-TripMate</a>(<a target="_blank" href="https://alceawis.de/qrgen.html?qr=http://10.10.10.254/data/UsbDisk1/Volume1/SampleWebMMD-master/index.html?pmx=YusakuFujiki/yusaku.pmx&stage=/livestageclub/livestageclubanimated.pmx&vmd=bts-dna" style=color:blue>qr</a>)--> </div> <details> <input type="text" id="buttonvmdInput" value="001" style="width: 100px;"> <button type="button" onclick="copyToClipboard()">Copy</button> <button type="button" onclick="updateQueryStringParameter('vmd', document.getElementById('buttonvmdInput').value);checkfile();">cstm</button> <button type="button" onclick="localStorage.setItem('camid', document.getElementById('buttonvmdInput').value); PoseClickEvent(document.getElementById('buttonvmdInput').value);">cstm+cam</button> <input type="checkbox" id="checkboxSendToPHP"> <label for="checkboxSendToPHP">Send to PHP</label> <!--CopytoClipboard---Code-----> <script> function copyToClipboard() { var inputText = document.getElementById("buttonvmdInput").value; var outputText = '{ id: "' + inputText + '", pose: "' + inputText + '", VmdClip: null, AudioClip: false },'; if (document.getElementById("checkboxSendToPHP").checked) { // Send the output text to mainvmdwrite.php var url = "mainvmdwrite.php"; var xhr = new XMLHttpRequest(); xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { alert("Text sent to mainvmdwrite.php!"); }}; xhr.send("outputText=" + encodeURIComponent(outputText)); } else { navigator.clipboard.writeText(outputText) .then(function() { alert("Text copied to clipboard!");}) .catch(function(error) { console.error("Error copying text: ", error); });}} </script> </details> <script> document.addEventListener('DOMContentLoaded', function() { if (window.self !== window.top) { var copyButton = document.querySelector('button[onclick="copyToClipboard()"]'); copyButton.disabled = true; copyButton.addEventListener('mouseover', function() { var tooltip = document.createElement('span'); tooltip.innerText = 'Disabled by CORS Policy';tooltip.style.position = 'absolute';tooltip.style.backgroundColor = '#000';tooltip.style.color = '#fff';tooltip.style.padding = '5px'; tooltip.style.borderRadius = '4px';tooltip.style.fontSize = '12px';tooltip.style.visibility = 'visible';tooltip.style.top = copyButton.offsetTop + copyButton.offsetHeight + 'px'; tooltip.style.left = copyButton.offsetLeft + 'px';document.body.appendChild(tooltip);}); copyButton.addEventListener('mouseout', function() { var tooltip = document.querySelector('span'); tooltip.parentNode.removeChild(tooltip);});}}); </script> <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> </head> <div class="pose"> <!--<button type="button" value="001" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);">vm1</button>--> <!--<button type="button" value="001" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);">vm1</button>--> <button type="button" value="001" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);location.reload();">vm1</button> <button type="button" value="002" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);location.reload();">vm2</button> <button type="button" value="003" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);location.reload();">vm3(camoff)</button> <button type="button" value="004walknthink" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);location.reload();">vm4</button> <button type="button" value="005hard-carry" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);location.reload();">tst(audio)</button> <button type="button" value="bts-bestofme" onclick="updateQueryStringParameter('vmd', this.value); localStorage.setItem('camid', this.value);location.reload();">best(audio)</button> </div> <details><summary>All Motions</summary><div class="file-buttons" id="file-buttons"></div></details> <script> function updateQueryStringParameter(key, value) { var url = new URL(window.location.href); var params = new URLSearchParams(url.search); params.set(key, value); url.search = params.toString(); history.replaceState(null, '', url.toString());} </script> <!--<button id="loadButton" value="./vmd/002.vmd">Load VMD File</button>--> <a href="?pmx=YusakuFujiki/yusaku.pmx">Yu</a> <a href="?pmx=AoiZaizen/AoiZaizen.pmx">Aoi</a> <a href="?pmx=Xion/xion.pmx">Xion</a> <a href="?pmx=9s/9s.pmx">9s</a> <a href="?pmx=2b/na_2b_0418n.pmx">2B</a> <a href="?pmx=TLoZ_Zelda_(Scholar)/zelda_scholar.pmx">BOTW Zelda</a> <a href="?pmx=TLoZ_Zelda_(Skyward_Sword)/Zelda_(Skyward_Sword).pmx">SW Zelda</a> <a href="?pmx=TLoZ_Link_BOTW)/linkbotw.pmx">BOTW Link</a> <a href="?pmx=kh_roxas/kh_roxas.pmx">Roxas</a> <a href="?pmx=off/off.pmx">-[OFF]-</a> <button class="off-button" onclick="window.location.href='?pmx=YusakuFujiki/yusaku.pmx&pmx2=AoiZaizen/AoiZaizen.pmx';" style="background-color: #ffcccc; border: #ff9999; border-radius: 8px; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; transition-duration: 0.4s;">yusaao</button> <button class="off-button" onclick="window.location.href='?pmx=Xion%2Fxion.pmx&pmx2=Roxas%2Froxas.pmx';" style="background-color: #ffcccc; border: #ff9999; border-radius: 8px; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; transition-duration: 0.4s;">Xion&Rox</button> </div> <details><summary>2ndChara</summary><div id="pmx2links"></div></details> <button id="play" onclick="" style="background-color: pink; background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.25) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.25) 50%, rgba(255, 255, 255, 0.25) 75%, transparent 75%, transparent); background-size: 20px 20px; border: none; color: white; padding: 10px 20px; font-size: 16px; font-weight: bold; border-radius: 5px; box-shadow: 0 0 10px rgba(255, 105, 180, 0.5); cursor: pointer; transition: transform 0.3s;" title="Spacebar">Play Animation and Audio</button> <button id="fullscreenButton" title="F10">Fullscreen</button> <!----Check VMD File--Existance---> <!--<button id="checkFileButton" onclick="checkfile()">Check File</button>--> <script> function getQueryStringParameter(name) { const urlParams = new URLSearchParams(window.location.search); return urlParams.get(name);} async function checkFileExistence(filePath) { try { const response = await fetch(filePath, { method: 'HEAD' }); if (response.ok) { console.log(`File exists: ${filePath}`); document.getElementById('readystate').textContent = `File exists: ${filePath}`; location.reload(); } else { console.log(`File does not exist (404): ${filePath}`); document.getElementById('readystate').textContent = `File doesn't exist: ${filePath}`;} } catch (error) { console.error(`Error fetching file: ${error}`); document.getElementById('readystate').textContent = `Error fetching file: ${error}`;}} function checkfile() { const vmd = getQueryStringParameter('vmd'); if (vmd) { const filePath = `./vmd/${vmd}.vmd`; checkFileExistence(filePath); } else { console.log('No vmd parameter found in the query string.'); document.getElementById('readystate').textContent = 'No vmd parameter found in the query string.';}} const domContentLoadedHandler = () => { checkfile(); }; </script> <!--AudioPlayback--ThreeJS-ver--> <script> async function playAnimationAndAudio() { const urlParams = new URLSearchParams(window.location.search); const vmdValue = urlParams.get('vmd'); if (!vmdValue) { console.log('No vmd parameter found in the URL'); return false; } console.log('vmdValue from URL:', vmdValue); const audioPath = `audio/${vmdValue}.mp3`; const audioListener = new THREE.AudioListener(); const audio = new THREE.Audio(audioListener); const audioLoader = new THREE.AudioLoader(); // Load audio file try { const audioBuffer = await new Promise((resolve, reject) => { audioLoader.load(audioPath, resolve, onAudioLoadProgress, reject); }); audio.setBuffer(audioBuffer); audio.setLoop(true); // Set to true if audio should loop audio.setVolume(1.0); // Adjust volume as needed audio.play(); console.log('Audio loaded and playing:', audioPath); } catch (error) { console.error('Error loading audio:', error); return false; } // Function to handle audio load progress (optional) function onAudioLoadProgress(xhr) { if (xhr.lengthComputable) { const percentComplete = (xhr.loaded / xhr.total) * 100; console.log('Audio load progress:', percentComplete.toFixed(2) + '%'); } } const clock = new THREE.Clock(); function update() { const delta = clock.getDelta(); } update(); return true; } </script> <!--AudioPlayback--non-ThreeJS-ver--> <!-- <script> function playAnimationAndAudio() { var urlParams = new URLSearchParams(window.location.search); var vmdValue = urlParams.get('vmd'); if (vmdValue) { var audioPath = 'audio/' + vmdValue + '.mp3'; if (window.audioElement && !window.audioElement.paused) { window.audioElement.currentTime = 0; } else { setTimeout(500); window.audioElement = new Audio(audioPath); audioElement.loop = true; } window.audioElement.play(); console.log('Animation triggered'); } else { console.log('No vmd parameter found in the URL');}} </script> --> <div class="stage"> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/herogarden/herogarden.pmx';window.location.href = updatedUrl;})()">herogarden</a> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/parkavenue/parkavenue.pmx';window.location.href = updatedUrl;})()">parkavenue</a> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/livestageclub/livestageclubanimated.pmx';window.location.href = updatedUrl;})()">LiveStage</a> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/h2cu09/h2cu09.pmx';window.location.href = updatedUrl;})()">h2cu09</a> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/SciFi_Cube/SciFi_Cube.pmx';window.location.href = updatedUrl;})()">SciFi_Cube</a> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/kh_twilighttown/kh_station_plaza/Station_Plaza.pmx';window.location.href = updatedUrl;})()">TwilightTownStation</a> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/([?&])stage=[^&]*/g, '$1').replace(/(&|\?)$/, '');var newStageParam = encodeURIComponent('/kh_twtnw/Memory\'s_Skyscraper/Memory\'s_Skyscraper.pmx');updatedUrl += (updatedUrl.indexOf('?') > -1 ? '&' : '?') + 'stage=' + newStageParam;window.location.href = updatedUrl;})()">TWTNW Skyscraper</a> </div> <script src="./libs/three.js"></script> <script src="./libs/mmdparser.min.js"></script> <script src="./libs/ammo.min.js"></script> <script src="./libs/TGALoader.js"></script> <script src="./libs/MMDLoader.js"></script> <script src="./libs/MMDAnimationHelper.js"></script> <script src="./libs/mmd-loader.min.js"></script> <script src="./libs/CCDIKSolver.js"></script> <script src="./libs/MMDPhysics.js"></script> <!--<script src="./libs/Vmd.js"></script> <script src="./libs/VmdFileParser.js"></script>--> <!--<script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/build/three.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/libs/mmdparser.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/ammo.js@0.0.10/ammo.min.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/loaders/TGALoader.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/loaders/MMDLoader.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/animation/MMDAnimationHelper.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/animation/CCDIKSolver.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/animation/MMDPhysics.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/jsm/controls/OrbitControls.js"></script>--> <script src="./js/main.js"></script> </body> </html> <!----Mark--used-button--green--> <script> window.addEventListener('load', function() { const urlParams = new URLSearchParams(window.location.search); var vmdValue = urlParams.get('vmd'); var buttons = document.querySelectorAll("button"); for (var i = 0; i < buttons.length; i++) {if (buttons[i].value === vmdValue) {buttons[i].style.backgroundColor = "lightgreen";}} }); </script> <!--AllMotions-show---onlineCompOnly---> <script> const fileDir = './vmd'; function listFiles() { const fileButtonsContainer = document.getElementById('file-buttons'); fetch(fileDir) .then(response => response.text()) .then(data => { const doc = new DOMParser().parseFromString(data, 'text/html'); const files = [...doc.getElementsByTagName('a')]; files .map(file => file.textContent.trim()) .filter(fileName => fileName.endsWith('.vmd')) .forEach(fileName => { const button = document.createElement('button'); button.type = 'button'; button.value = fileName; button.textContent = fileName.replace('.vmd', ''); button.onclick = () => { updateQueryStringParameter('vmd', fileName.replace('.vmd', '')); location.reload();}; fileButtonsContainer.appendChild(button);});}) .catch(error => { console.error('Error listing files:', error); });} function updateQueryStringParameter(key, value) { const url = new URL(window.location.href); url.searchParams.set(key, value); window.history.replaceState({}, '', url.toString());} window.addEventListener('load', listFiles); </script> <!--keyboard-shortcuts--f10--spacebar--> <script> document.addEventListener('DOMContentLoaded', function() { document.addEventListener('keydown', function(event) { if (event.key === 'F10') { event.preventDefault(); // Prevent default action (fullscreen mode) renderer.domElement.requestFullscreen()}}); document.addEventListener('keydown', function(event) { if (event.key === ' ') { // Spacebar key event.preventDefault(); // Prevent default action (scrolling the page) document.getElementById('play').click();}});}); </script> ___________________________________ PMX Capable MMD Web Renderer (with stage support) -------------------------------- Download: https://ry3yr.github.io/SampleWebMMD-master.zip Src: https://github.com/Momijinn/SampleWebMMD ===/js/main.js ===== let scene, renderer, camera, mesh, helper, cameraAnimation; let ready = false; const windowWidth = window.innerWidth; const windowHeight = window.innerHeight; const clock = new THREE.Clock(); function getQueryStringValue(key) { const urlParams = new URLSearchParams(window.location.search); return urlParams.get(key); } const pmx = getQueryStringValue('pmx'); const stage = getQueryStringValue('stage'); let Pmx; let Stage; if (pmx) { Pmx = `./pmx/pronama/${pmx.trim()}`; } else { console.log("No PMX selected."); } if (stage) { Stage = `./stages${stage.trim()}`; } else { console.log("No stage selected."); } if (!Pmx) { Pmx = `./pmx/pronama/AoiZaizen/AoiZaizen.pmx`; } if (!Stage) { Stage = "./stages/sorclair/sorclair.pmx"; } const MotionObjects = [ { id: "001", pose: "001", VmdClip: null, AudioClip: false }, { id: "002", pose: "002", VmdClip: null, AudioClip: false }, { id: "003", pose: "003", VmdClip: null, AudioClip: false }, { id: "bts-bestofme", pose: "bts-bestofme", VmdClip: null, AudioClip: true }, ]; window.onload = () => { Init(); LoadModeler(); Render(); }; function Init() { document.getElementById("moveLeftButton").addEventListener("click", moveCameraLeft); document.getElementById("moveRightButton").addEventListener("click", moveCameraRight); document.getElementById("moveUpButton").addEventListener("click", moveCameraUp); document.getElementById("moveDownButton").addEventListener("click", moveCameraDown); document.getElementById("rotaterightButton").addEventListener("click", rotateCameraRight); document.getElementById("rotateleftButton").addEventListener("click", rotateCameraLeft); function moveCameraLeft() { camera.position.x -= 1; } function moveCameraRight() { camera.position.x += 1; } function moveCameraUp() { camera.position.y += 1; } function moveCameraDown() { camera.position.y -= 1; } function rotateCameraRight() { mesh.rotateY(Math.PI / 4); } function rotateCameraLeft() { mesh.rotateY(-Math.PI / 4); } scene = new THREE.Scene(); const ambient = new THREE.AmbientLight(0xeeeeee); scene.add(ambient); renderer = new THREE.WebGLRenderer({ alpha: true }); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth, window.innerHeight); renderer.setClearColor(0xcccccc, 0); document.body.appendChild(renderer.domElement); camera = new THREE.PerspectiveCamera(100, windowWidth / windowHeight, 1, 1000); camera.position.set(0, 19, 20); } async function LoadModeler() { const loader = new THREE.MMDLoader(); function LoadPMX() { return new Promise(resolve => { loader.load(Pmx, object => { mesh = object; scene.add(mesh); resolve(true); },);});} function LoadVMD(id) { return new Promise(resolve => { const path = "./vmd/" + id + ".vmd"; const val = MotionObjects.findIndex(MotionObject => MotionObject.id == id); loader.loadAnimation(path, mesh, vmd => { vmd.name = id; MotionObjects[val].VmdClip = vmd; //newid = id; //console.log(newid); document.getElementById('readystate').innerHTML = "Checking motion vmd - " + id + ' (if stuck, click <a href="js/main.js" target="_blank">here</a>)'; resolve(true); },);});} function LoadCamera(id) { let camid; if (new URLSearchParams(window.location.search).has('camera')) { camid = new URLSearchParams(window.location.search).get('camera'); } else { camid = localStorage.getItem('camid'); if (!camid) { camid = 'bts-bestofme'; } } const path = "./camera/" + camid + ".vmd"; return new Promise((resolve, reject) => { loader.loadAnimation(path, camera, cameraAnimation => { cameraAnimation.name = path; resolve(cameraAnimation); console.log(path); }, onProgress, (xhr) => reject(new Error(`Failed to load Camera VMD file: ${path}`))); }); } function LoadAudio(id) { return new Promise(resolve => { const path = "./audio/" + id + ".mp3"; const val = MotionObjects.findIndex(MotionObject => MotionObject.id == id); if (MotionObjects[val].AudioClip) { new THREE.AudioLoader().load(path, buffer => { const listener = new THREE.AudioListener(); const audio = new THREE.Audio(listener).setBuffer(buffer); MotionObjects[val].AudioClip = audio; document.getElementById('readystate').innerHTML = "Checking audio - " + id + ' (if stuck, click <a href="audio" target="_blank">here</a>)'; resolve(true); },); } else { resolve(false);}});} const loadAdditionalPMX = () => { return new Promise(resolve => { loader.load(Stage, object => { const additionalMesh = object; scene.add(additionalMesh); resolve(true); const loadAdditionalPMX = () => { return new Promise(resolve => { loader.load(Stage, object => { const additionalMesh = object; scene.add(additionalMesh); resolve(true); }); }); }; let path; //preperations for 001.vmd and 002.vmd try {path = `./stages${stage.trim()}`;} catch (e) { path = '/default/default';} const lastIndex = path.lastIndexOf("/"); const basePath = path.substring(0, lastIndex); const vmd1 = `${basePath}/001.vmd`; const vmd2 = `${basePath}/002.vmd`; console.log(vmd1); console.log(vmd2); let mixer; const url = window.location.href; const isAnimated = url.indexOf('animated') !== -1; if (isAnimated) { function createMixer() { mixer = new THREE.AnimationMixer(object); } function playAnimation(animationClip) { const action = mixer.clipAction(animationClip); action.play(); } loader.loadAnimation(vmd1, object, (animationClip) => { createMixer(); playAnimation(animationClip); }); loader.loadAnimation(vmd2, object, (animationClip) => { playAnimation(animationClip); }); function animate() { requestAnimationFrame(animate); const deltaTime = clock.getDelta(); if (mixer) { mixer.update(deltaTime); } renderer.render(scene, camera); } animate(); } },);});}; await Promise.all([loadAdditionalPMX()]); await LoadPMX(); await Promise.all(MotionObjects.map(async (MotionObject) => {return await LoadVMD(MotionObject.id);})); await Promise.all(MotionObjects.map(async (MotionObject) => {return await LoadAudio(MotionObject.id);})); cameraAnimation = await LoadCamera("camera-animation-id"); // Ensure to load camera animation VmdControl("loop", true);} function VmdControl(id, loop) { const index = MotionObjects.findIndex(MotionObject => MotionObject.id == id); if (index === -1) { console.log("not Found ID"); //document.getElementById('readystate').textContent = "Default Camera: ready"; document.getElementById('readystate').textContent = "Camera: ready - " + localStorage.getItem('camid'); return; } ready = false; helper = new THREE.MMDAnimationHelper({ afterglow: 2.0, resetPhysicsOnLoop: true }); const enablePhysics = localStorage.getItem("physicsareon") === "true"; helper.add(mesh, { animation: MotionObjects[index].VmdClip, physics: enablePhysics }); if (MotionObjects[index].AudioClip) { MotionObjects[index].AudioClip.play(); } if (cameraAnimation) { helper.add(camera, {animation: cameraAnimation}); } const mixer = helper.objects.get(mesh).mixer; if (!loop) { mixer.existingAction(MotionObjects[index].VmdClip).setLoop(THREE.LoopOnce); } mixer.addEventListener("loop", (event) => { console.log("loop"); }); mixer.addEventListener("finished", (event) => { console.log("finished"); VmdControl("loop", true); }); ready = true; } function onProgress(xhr) { if (xhr.lengthComputable) { const percentComplete = xhr.loaded / xhr.total * 100; console.log(Math.round(percentComplete, 2) + '% downloaded'); } } function onError(xhr) { console.log("ERROR", xhr); } function Render() { requestAnimationFrame(Render); renderer.clear(); renderer.render(scene, camera); if (ready) { helper.update(clock.getDelta()); } } const generatePoseClickEvent = (motionObjects) => { const functionBody = motionObjects.map(function (motion) { return "case '" + motion.pose + "':\n" + " VmdControl('" + motion.id + "', " + (motion.pose === "pose1") + ");\n" + " break;\n"; }).join(""); const poseClickEventFunction = new Function("id", "switch (id) { " + functionBody + " default: VmdControl('001', true); break; }"); return poseClickEventFunction; }; const PoseClickEvent = generatePoseClickEvent(MotionObjects); console.log(PoseClickEvent); ===/index.html== <div id="readystate">...</div> <button onclick="togglePhysicsAndReload()">Toggle Physics</button> <script> function togglePhysicsAndReload() { var physicsAreOn = localStorage.getItem("physicsareon"); if (physicsAreOn) { localStorage.removeItem("physicsareon"); } else { localStorage.setItem("physicsareon", "true");} location.reload();} var physicsAreOn = localStorage.getItem("physicsareon"); if (physicsAreOn) { document.querySelector("button").textContent = "Physics On"; } else { document.querySelector("button").textContent = "Physics Off";} </script> <div class="keyboard"> <button id="." onclick="togglePhysicsAndReload()" style="background-color: transparent; border: none;color: transparent;">Move L3.__</button> <button id="moveUpButton">Move Up</button><br> <button id="moveLeftButton">Move Left</button> <button id="moveDownButton">Move Down</button> <button id="moveRightButton">Move Right</button> <button id="." style="background-color: transparent; border: none;color: transparent;">.__</button> <button id="rotateleftButton">RotateLeft</button> <button id="rotaterightButton">RotateRight</button> <a target="_blank" href="https://www.youtube.com/playlist?list=PLBva3abEZvyT-_ajETBGeOCGBA_AFBT5Z#https://www.reddit.com/r/mikumikudance" style=color:blue>r/MMD</a> <a target="_blank" href="https://codepen.io/ryedai1/pens/tags/?selected_tag=mikumikudance" style=color:gray>(tools)</a> </div> <details> <input type="text" id="buttonvmdInput" value="001" style="width: 100px;"> <button type="button" onclick="copyToClipboard()">Copy</button> <button type="button" onclick="PoseClickEvent(document.getElementById('buttonvmdInput').value)">cstm</button> <button type="button" onclick="localStorage.setItem('camid', document.getElementById('buttonvmdInput').value); PoseClickEvent(document.getElementById('buttonvmdInput').value);">cstm+cam</button> <input type="checkbox" id="checkboxSendToPHP"> <label for="checkboxSendToPHP">Send to PHP</label> <!--CopytoClipboard---Code-----> <script> function copyToClipboard() { var inputText = document.getElementById("buttonvmdInput").value; var outputText = '{ id: "' + inputText + '", pose: "' + inputText + '", VmdClip: null, AudioClip: false },'; if (document.getElementById("checkboxSendToPHP").checked) { // Send the output text to mainvmdwrite.php var url = "mainvmdwrite.php"; var xhr = new XMLHttpRequest(); xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { alert("Text sent to mainvmdwrite.php!"); }}; xhr.send("outputText=" + encodeURIComponent(outputText)); } else { navigator.clipboard.writeText(outputText) .then(function() { alert("Text copied to clipboard!");}) .catch(function(error) { console.error("Error copying text: ", error); });}} </script> </details> <script> document.addEventListener('DOMContentLoaded', function() { if (window.self !== window.top) { var copyButton = document.querySelector('button[onclick="copyToClipboard()"]'); copyButton.disabled = true; copyButton.addEventListener('mouseover', function() { var tooltip = document.createElement('span'); tooltip.innerText = 'Disabled by CORS Policy';tooltip.style.position = 'absolute';tooltip.style.backgroundColor = '#000';tooltip.style.color = '#fff';tooltip.style.padding = '5px'; tooltip.style.borderRadius = '4px';tooltip.style.fontSize = '12px';tooltip.style.visibility = 'visible';tooltip.style.top = copyButton.offsetTop + copyButton.offsetHeight + 'px'; tooltip.style.left = copyButton.offsetLeft + 'px';document.body.appendChild(tooltip);}); copyButton.addEventListener('mouseout', function() { var tooltip = document.querySelector('span'); tooltip.parentNode.removeChild(tooltip);});}}); </script> <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> </head> <div class="pose"> <button type="button" value="001" onclick="localStorage.setItem('camid', this.value);PoseClickEvent(this.value);">vm1</button> <button type="button" value="002" onclick="localStorage.setItem('camid', this.value);PoseClickEvent(this.value);">vm2</button> <button type="button" value="003" onclick="localStorage.setItem('camid', this.value);PoseClickEvent(this.value);">vm3(camoff)</button> <button type="button" value="004walknthink" onclick="localStorage.setItem('camid', this.value);PoseClickEvent(this.value);">vm4</button> <button type="button" value="005hard-carry" onclick="localStorage.setItem('camid', this.value);PoseClickEvent(this.value);">tst(audio)</button> <!--set audio to "true" in main.js and have a 005hard-carry.mp3 in audio folder"--> <button type="button" value="bts-bestofme" onclick="localStorage.setItem('camid', this.value);PoseClickEvent(this.value);">best(audio)</button> <!--<button id="loadButton" value="./vmd/002.vmd">Load VMD File</button>--> <a href="?pmx=YusakuFujiki/yusaku.pmx">Yu</a> <a href="?pmx=AoiZaizen/AoiZaizen.pmx">Aoi</a> <a href="?pmx=Xion/xion.pmx">Xion</a> <a href="?pmx=2b/na_2b_0418n.pmx">2B</a> <a href="?pmx=TLoZ_Zelda_(Scholar)/zelda_scholar.pmx">BOTW Zelda</a> <a href="?pmx=TLoZ_Link_BOTW)/linkbotw.pmx">BOTW Link</a> <a href="?pmx=kh_roxas/kh_roxas.pmx">Roxas</a> <a href="?pmx=kh_terra/Casual/Terra%20[Casual].pmx">Terra(KHBBS)</a> <a href="?pmx=kh_aqua/Casual%20Aqua/Aqua%20[Casual%20Skirt].pmx">Aqua(KHBBS)</a> </div> <div class="stage"> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/herogarden/herogarden.pmx';window.location.href = updatedUrl;})()">herogarden</a> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/parkavenue/parkavenue.pmx';window.location.href = updatedUrl;})()">parkavenue</a> <a href="javascript:(function() {var currentUrl = window.location.href;var updatedUrl = currentUrl.replace(/(\?|&)stage=([^&]*)/g, '') + (currentUrl.indexOf('?') > -1 ? '&' : '?') +'stage=/livestageclub/livestageclubanimated.pmx';window.location.href = updatedUrl;})()">LiveStage</a> </div> <script src="./libs/three.js"></script> <script src="./libs/mmdparser.min.js"></script> <script src="./libs/ammo.min.js"></script> <script src="./libs/TGALoader.js"></script> <script src="./libs/MMDLoader.js"></script> <script src="./libs/MMDAnimationHelper.js"></script> <script src="./libs/mmd-loader.min.js"></script> <script src="./libs/CCDIKSolver.js"></script> <script src="./libs/MMDPhysics.js"></script> <!--<script src="./libs/Vmd.js"></script> <script src="./libs/VmdFileParser.js"></script>--> <!--<script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/build/three.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/libs/mmdparser.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/ammo.js@0.0.10/ammo.min.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/loaders/TGALoader.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/loaders/MMDLoader.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/animation/MMDAnimationHelper.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/animation/CCDIKSolver.js"></script> <script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js@r106/examples/js/animation/MMDPhysics.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/jsm/controls/OrbitControls.js"></script> --> <script src="./js/main.js"></script> </body> </html> __________________________ MMD PMD texture fixer: -------------------- <!DOCTYPE html> <html> <head> <title>Image Drag and Drop</title> <style> #drop-zone { width: 400px; height: 400px; border: 2px dashed gray; margin: 20px auto; text-align: center; line-height: 400px; font-size: 20px; } #image-element { max-width: 100%; max-height: 400px; margin-top: 20px; } #download-button { display: none; margin-top: 10px; } </style> </head> <body> <div id="drop-zone">Drag and drop an image here</div> <img id="image-element" src="" alt="Processed Image"> <a id="download-button" href="#" download="">Download</a> <script> // Get the HTML elements const dropZone = document.getElementById('drop-zone'); const imageElement = document.getElementById('image-element'); const downloadButton = document.getElementById('download-button'); // Add event listeners for drag and drop events dropZone.addEventListener('dragover', handleDragOver); dropZone.addEventListener('drop', handleFileDrop); // Handle the dragover event to allow the drop function handleDragOver(event) { event.preventDefault(); } // Handle the drop event function handleFileDrop(event) { event.preventDefault(); // Get the dropped file const file = event.dataTransfer.files[0]; // Create a FileReader object to read the file const reader = new FileReader(); // Set up the onload event handler reader.onload = function(e) { // Create a new image element const newImage = new Image(); // Set the onload event handler to handle image loading newImage.onload = function() { // Perform the image processing steps const processedImage = processImage(newImage); // Display the processed image imageElement.src = processedImage.src; // Set the download link properties downloadButton.href = processedImage.src; downloadButton.setAttribute('download', file.name); // Show the download button downloadButton.style.display = 'block'; }; // Set the source of the new image to the dropped file newImage.src = e.target.result; }; // Read the dropped file as a data URL reader.readAsDataURL(file); } // Function to process the image and fit it into the criteria function processImage(image) { // Create a canvas element const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); // Ensure the canvas dimensions are power-of-two (POT) const canvasWidth = Math.pow(2, Math.floor(Math.log2(image.width))); const canvasHeight = Math.pow(2, Math.floor(Math.log2(image.height))); canvas.width = canvasWidth; canvas.height = canvasHeight; // Draw the image on the canvas ctx.drawImage(image, 0, 0, canvasWidth, canvasHeight); // Convert the image to RGBA format if necessary if (ctx.getImageData(0, 0, 1, 1).data.length !== 4) { const imageData = ctx.getImageData(0, 0, canvasWidth, canvasHeight); const rgbaImageData = convertToRGBA(imageData); ctx.putImageData(rgbaImageData, 0, 0); } // Create a new image element with the processed image data const processedImage = new Image(); processedImage.src = canvas.toDataURL(); return processedImage; } // Function to convert the image data to RGBA format function convertToRGBA(imageData) { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); canvas.width = imageData.width; canvas.height = imageData.height; // Create a new ImageData object with RGBA format const rgbaImageData = ctx.createImageData(imageData.width, imageData.height); // Convert the pixel data to RGBA format for (let i = 0; i < imageData.data.length; i += 4) { rgbaImageData.data[i] = imageData.data[i]; rgbaImageData.data[i + 1] = imageData.data[i + 1]; rgbaImageData.data[i + 2] = imageData.data[i + 2]; rgbaImageData.data[i + 3] = 255; // Set alpha channel to opaque } return rgbaImageData; } </script> </body> </html> ____________________ Image attribute analyzer: ------------------------- <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/min/dropzone.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/min/dropzone.min.js"></script> <div id="myDropzone" class="dropzone"></div> <div id="imageInfo"></div> <script> Dropzone.autoDiscover = false; var myDropzone = new Dropzone("#myDropzone", { url: "#", autoProcessQueue: false, maxFiles: 5, acceptedFiles: "image/*", init: function () { var submitButton = document.querySelector("#submit"); this.on("addedfile", function (file) { processImage(file);}); submitButton.addEventListener("click", function () { myDropzone.processQueue();});}}); function processImage(file) { var reader = new FileReader(); reader.onload = function (event) { var img = new Image(); img.onload = function () { var canvas = document.createElement("canvas"); var context = canvas.getContext("2d"); context.drawImage(img, 0, 0); var codec = img.src.split(";")[0].split(":")[1]; var width = img.width; var height = img.height; var fileSize = file.size; var colorSpace = extractColorSpace(context); var bitDepth = extractBitDepth(context); var fileFormat = extractFileFormat(file); displayImageInfo(file, codec, width, height, fileSize, colorSpace, bitDepth, fileFormat);}; img.src = event.target.result;}; reader.readAsDataURL(file);} function extractColorSpace(context) { return context.getImageData(0, 0, 1, 1).colorSpace;} function extractBitDepth(context) { return context.getImageData(0, 0, 1, 1).data.length * 8;} function extractFileFormat(file) { var fileNameParts = file.name.split("."); return fileNameParts[fileNameParts.length - 1];} function displayImageInfo(file, codec, width, height, fileSize, colorSpace, bitDepth, fileFormat) { var infoDiv = document.getElementById("imageInfo"); var imageDiv = document.createElement("div"); var imgName = document.createElement("p"); var imgInfo = document.createElement("p"); imgName.innerHTML = "<hr><br>Image Name: " + file.name; var thumbnail = document.createElement("img"); thumbnail.src = URL.createObjectURL(file); thumbnail.width = 45; thumbnail.height = 45; imgInfo.innerHTML = "Image Info: Codec: " + codec + "<br>"; if (height % 2 !== 0) { imgInfo.innerHTML += "<span style='color: red;'>Height: " + height + "px</span><br>"; } else { imgInfo.innerHTML += "Height: " + height + "px<br>"; } if (width % 2 !== 0) { imgInfo.innerHTML += "<span style='color: red;'>Width: " + width + "px</span><br>"; } else { imgInfo.innerHTML += "Width: " + width + "px<br>"; } imgInfo.innerHTML += "File Size: " + fileSize + " bytes<br>Color Space: " + colorSpace + "<br>Bit Depth: " + bitDepth + " bits<br>File Format: " + fileFormat + "<br>"; imgInfo.appendChild(thumbnail); imageDiv.appendChild(imgName); imageDiv.appendChild(imgInfo); infoDiv.appendChild(imageDiv); } </script> </body> </html> _______________________ Dynamically change link behaviour with toggle button ------------------------------------------- <button id="toggleButton">Download</button> <script> function toggleDownloadParam() { var links = document.querySelectorAll('a[id="dld"]'); for (var i = 0; i < links.length; i++) { var link = links[i]; if (link.href.indexOf('?') === -1) { link.href += '?download=yes'; } else { link.href += '&download=yes'; } } } var toggleButton = document.getElementById('toggleButton'); toggleButton.addEventListener('click', function() { if (toggleButton.classList.contains('on')) { toggleButton.classList.remove('on'); toggleButton.textContent = 'Toggle'; toggleDownloadParam(); } else { toggleButton.classList.add('on'); toggleButton.textContent = 'Toggle (On)'; toggleDownloadParam(); } }); </script> <a href="example.html" id="dld">Download Link 1</a><br> _________________________________________ Nitter Instance Selector ------------------------ <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <label for="nitterUrl"><a href=https://status.d420.de/#https://github.com/zedeus/nitter/issues/986 target=_blank>Nitter</a> URL:</label> <select id="nitterUrl"> <option value="https://nitter.privacydev.net/">https://nitter.privacydev.net/</option> <option value="https://nitter.no-logs.com/">https://nitter.no-logs.com/</option> <option value="https://nitter.poast.org/">https://nitter.poast.org/</option> <option value="https://nitter.kavin.rocks/">https://nitter.kavin.rocks/ (noRSS)</option> </select> <input type="text" id="username" value="alceawisteria"> <input type="checkbox" id="renderRss" checked> Render RSS <input type="checkbox" id="openNewTab"> Open in new tab automatically <br> <button onclick="generateLink()">Generate Link</button> <br><br> <div id="linkOutput"></div> <div id="rssOutput"></div> <br> <br><br> <script> function generateLink() { var nitterUrl = document.getElementById("nitterUrl").value; var username = document.getElementById("username").value; var link = nitterUrl + username; var linkOutput = document.getElementById("linkOutput"); var rsslink = nitterUrl + username + "/rss"; var rssOutput = $("#rssOutput"); var renderRss = document.getElementById("renderRss").checked; var openNewTab = document.getElementById("openNewTab").checked; if (openNewTab) { linkOutput.innerHTML = "<a href='" + link + "' target=_blank>" + link + "</a>"; linkOutput.getElementsByTagName("a")[0].click(); } else { linkOutput.innerHTML = "<a href='" + link + "' target=_blank>" + link + "</a>"; } if (renderRss) { var rssUrl = link + "/rss"; var rss2JsonUrl = "https://api.rss2json.com/v1/api.json?rss_url=" + encodeURIComponent(rssUrl); $.ajax(rss2JsonUrl, { accepts: { json: "application/json" }, dataType: "json", success: function (data) { var items = data.items.slice(0, 10); var rssHtml = "<ul>"; items.forEach(function (item) { var title = item.title; var description = item.description; var pubDate = new Date(item.pubDate).toLocaleDateString(); var author = item.author; var link = item.link; rssHtml += "<li>"; rssHtml += "<h3><a href='" + link + "' target='_blank'>" + title + "</a></h3>"; rssHtml += "<p>" + description + "</p>"; rssHtml += "<p><strong>Date:</strong> " + pubDate + "</p>"; rssHtml += "<p><strong>Author:</strong> " + author + "</p>"; rssHtml += "</li>"; }); rssHtml += "</ul>"; rssOutput.html(rssHtml); }, error: function () { rssOutput.html("Error loading RSS feed."); } }); } else { rssOutput.html(rsslink); } } </script> ___________________________________________ Fetch 100 tag entry mastodon ---------------------------- <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div> <label for="instance-url">Instance URL:</label> <input type="text" id="instance-url" placeholder="Enter instance URL" value="https://"> </div> <div> <label for="tag">Tag:</label> <input type="text" id="tag" placeholder="Enter tag"> </div> <button onclick="fetchEntries()">Fetch Entries</button> <hr> <div id="entries"></div> <script> var initialFetchURL = 'https://mastodon.cloud/api/v1/timelines/tag/MastodonArt?limit=100'; fetchEntries(); function fetchEntries() { var instanceURL = document.getElementById('instance-url').value; var tag = document.getElementById('tag').value; var apiUrl = initialFetchURL; if (instanceURL && tag) { apiUrl = instanceURL + '/api/v1/timelines/tag/' + tag + '?limit=100'; } $.ajax({ url: apiUrl, dataType: 'json', success: function(data) { displayEntries(data); }, error: function(error) { console.log('Error:', error); } }); } function displayEntries(entries) { var entriesDiv = document.getElementById('entries'); entriesDiv.innerHTML = ''; entries.forEach(function(entry) { var entryHTML = '<div>'; entryHTML += '<p>' + entry.content + '</p>'; entryHTML += '<p>Author: ' + entry.account.display_name + '</p>'; entryHTML += '<p><a href="' + entry.url + '" target="_blank">View Toot</a></p>'; entryHTML += '<hr>'; entryHTML += '</div>'; entriesDiv.innerHTML += entryHTML; }); } </script> </body> </html> ____________________________ Favorite Clothes with table generator ------------------------------------- <table> <tr> <th>Image</th><th>Description</th><th>Source</th><th>Purchasable</th> </tr> <tr><td><a href="https://www.pixiv.net/en/artworks/116877725" target="_blank"><img src="https://medium-media.vgm.io/albums/84/55848/55848-1477525776.jpg" alt="Image" width="100" height="100"></a></td> <td>Pretty dress worn by the GodEater Girl<br> on the <a href="https://vgmdb.net/album/55848" target="_blank">Cover of the 5th Anniv CD</a></td> <td><a href="https://vgmdb.net/album/55848" target="_blank">SRC</a></td> <td>No</td> </tr> <!-- Add more rows as needed --> <tr><td><a href="https://www.amazon.com/Cosplay-Automata-Costume-Kimono-Halloween/dp/B0BNVZJ6FL" target="_blank"><img src="https://m.media-amazon.com/images/I/61maeTQesuL._AC_SX569_.jpg" alt="Image" width="100" height="100"></a></td><td>2Bs Kimono (Switch DLC) <a href="https://vgmdb.net/album/55848" target="_blank">eBay</a></td> <td><a href="https://www.nintendo.de/DLC/NieR-Automata-6C2P4A118680823-2233414.html" target="_blank">SRC</a></td> <td>Yes</td> </tr> </table> <!---New_Entry_Generator--> <details><summary>(+)</summary> <style> .entry{margin-bottom:10px}.entry input[type=text]{width:200px;margin-right:10px}.preview{border:1px solid #ccc;padding:10px;width:300px;height:100px}#outputTable{margin-top:20px;border-collapse:collapse}#outputTable td,#outputTable th{padding:5px;border:1px solid #ccc} </style> <form> <div class="entry"> <input type="text" id="imageURL" placeholder="Image URL" oninput="updatePreview()"> <input type="text" id="imageLink" placeholder="Image Link URL" oninput="updatePreview()"> <input type="text" id="description" placeholder="Description" oninput="updatePreview()"> <input type="text" id="sourceLink" placeholder="Source Link URL" oninput="updatePreview()"> <select id="purchasable" onchange="updatePreview()"> <option value="Yes">Yes</option> <option value="No">No</option> </select></div></form> <table id="outputTable"></table> <textarea id="outputText" rows="10" cols="50" readonly></textarea> <script> function updatePreview() { var imageURL = document.getElementById("imageURL").value; var imageLink = document.getElementById("imageLink").value; var description = document.getElementById("description").value; var sourceLink = document.getElementById("sourceLink").value; var purchasable = document.getElementById("purchasable").value; var outputTable = document.getElementById("outputTable"); var outputText = document.getElementById("outputText"); var row = '<tr>' + '<td><a href="' + imageLink + '" target="_blank"><img src="' + imageURL + '" alt="Image" width="50" height="50"></a></td>' + '<td>' + description + '</td>' + '<td><a href="' + sourceLink + '" target="_blank">SRC</a></td>' + '<td>' + purchasable + '</td>' + '</tr>'; outputTable.innerHTML = row; var outputCode = '<tr>' + '<td><a href="' + imageLink + '" target="_blank"><img src="' + imageURL + '" alt="Image" width="100" height="100"></a></td>' + '<td>' + description + '</td>\n' + '<td><a href="' + sourceLink + '" target="_blank">SRC</a></td>\n' + '<td>' + purchasable + '</td>\n' + '</tr>'; outputText.value = outputCode; } </script> ______________________________________ Fetch full Table from site --------------------------- <script> function fetchTable() { fetch('https://alceawis.de/favclothes.html') .then(response => response.text()) .then(html => { const tempElement = document.createElement('div'); tempElement.innerHTML = html; const table = tempElement.querySelector('table'); const div = document.getElementById('tableContainer'); div.appendChild(table); }) } //document.addEventListener('DOMContentLoaded', fetchTable); </script> <button onclick="fetchTable()">Fetch Table</button> <div id="tableContainer"></div> ____________________ Bookmarklets (with copy function) ---------------------------------- <!--Mastodon--Fediverse--Bookmarklet--> <a href="https://codepen.io/ryedai1/pen/NWJoeRW" target="_blank"><img src="https://donestech.net/files/noticies/xarxa-fediverse-mastodon.png" style="width:50px" alt="feditext">Reroute any mastodon/fedi link to your home instance</a><br> <textarea id="feditext" rows="8" cols="80"></textarea><br> <button onclick="openBookmarkDialogfeditext()">Add to Bookmark</button> <button onclick="copyToClipboardfeditext()">Copy to Clipboard</button> <script> var decodedStringfeditext = atob('amF2YXNjcmlwdDooZnVuY3Rpb24oKSB7CiAgdmFyIGVuY29kZWRVcmwgPSBlbmNvZGVVUklDb21wb25lbnQod2luZG93LmxvY2F0aW9uLmhyZWYpOwogIHZhciByZWRpcmVjdFVybCA9ICJodHRwczovL2FsY2VhLXdpc3RlcmlhLmRlL1BIUC8wZGVtby8yMDIzLTEwLTIyLU1hc3RvZG9uVG9vdFNlYXJjaC9zZWFyY2htYXN0b3VybC5waHA/c2VhcmNoPSIgKyBlbmNvZGVkVXJsICsgIiZwYlVybD1odHRwcyUzQSUyRiUyRnBiLnRvZG9uLmRlJmFwaWtleT1hcGlrZXloZXJlIjsKICB3aW5kb3cubG9jYXRpb24uaHJlZiA9IHJlZGlyZWN0VXJsOw=='); function openBookmarkDialogfeditext() { var bookmarkName = prompt("Enter bookmark name:"); if (bookmarkName) { var bookmarkUrl = decodedStringfeditext; if (window.navigator.userAgent.indexOf("Chrome") !== -1 && chrome && chrome.bookmarks) { chrome.bookmarks.create({ title: bookmarkName, url: bookmarkUrl }, function() { alert("Bookmark added: " + bookmarkName); }); } else if (window.navigator.userAgent.indexOf("Firefox") !== -1 && browser && browser.bookmarks) { browser.bookmarks.create({ title: bookmarkName, url: bookmarkUrl }).then(function() { alert("Bookmark added: " + bookmarkName); }); } else { alert("Sorry, your browser does not support the bookmarking feature.");}}} function copyToClipboardfeditext() { var feditext = document.getElementById("feditext").value; var tempInput = document.createElement("input"); tempInput.value = feditext; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); document.execCommand("copy"); document.body.removeChild(tempInput); alert("Text copied to clipboard: " + feditext);} document.getElementById("feditext").value = decodedStringfeditext; </script> <hr> <!--Youtube--Super8--Bookmarklet--> <a href="https://alceawis.de/super8" target="_blank"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Invidious-logo.svg/120px-Invidious-logo.svg.png" style="width:50px" alt="super8text">Reroute any youtube links to super8/invidious</a><br> <textarea id="super8text" rows="8" cols="80"></textarea><br> <button onclick="openBookmarkDialogsuper8text()">Add to Bookmark</button> <button onclick="copyToClipboardsuper8text()">Copy to Clipboard</button> <script> var decodedStringsuper8text = atob('amF2YXNjcmlwdDooZnVuY3Rpb24oKSB7CiAgdmFyIGN1cnJlbnRVcmwgPSB3aW5kb3cubG9jYXRpb24uaHJlZjsKICB2YXIgZGVza3RvcFJlZ2V4ID0gL3lvdXR1YmVcLmNvbVwvd2F0Y2hcP2FwcD1kZXNrdG9wLzsKICB2YXIgbW9iaWxlUmVnZXggPSAvbVwueW91dHViZVwuY29tXC8vOwogIHZhciB5b3V0dVJlZ2V4ID0gL3lvdXR1XC5iZVwvKFtcdy1dKykvOwogIHZhciByZXBsYWNlbWVudFVybCA9ICJodHRwczovL3N1cGVyOC5hYnN0dXJ6dGF1LmJlL3dhdGNoP3Y9IjsKICBpZiAoZGVza3RvcFJlZ2V4LnRlc3QoY3VycmVudFVybCkgfHwgbW9iaWxlUmVnZXgudGVzdChjdXJyZW50VXJsKSB8fCB5b3V0dVJlZ2V4LnRlc3QoY3VycmVudFVybCkpIHsKICAgIHZhciB2aWRlb0lkID0gY3VycmVudFVybC5tYXRjaCgvWz8mXXY9KFtcdy1dKykvKVsxXTsKICAgIHZhciBuZXdVcmwgPSByZXBsYWNlbWVudFVybCArIHZpZGVvSWQ7CiAgICB3aW5kb3cubG9jYXRpb24uaHJlZiA9IG5ld1VybDsKICB9Cn0pKCk7'); function openBookmarkDialogsuper8text() { var bookmarkName = prompt("Enter bookmark name:"); if (bookmarkName) { var bookmarkUrl = decodedStringsuper8text; if (window.navigator.userAgent.indexOf("Chrome") !== -1 && chrome && chrome.bookmarks) { chrome.bookmarks.create({ title: bookmarkName, url: bookmarkUrl }, function() { alert("Bookmark added: " + bookmarkName); }); } else if (window.navigator.userAgent.indexOf("Firefox") !== -1 && browser && browser.bookmarks) { browser.bookmarks.create({ title: bookmarkName, url: bookmarkUrl }).then(function() { alert("Bookmark added: " + bookmarkName); }); } else { alert("Sorry, your browser does not support the bookmarking feature.");}}} function copyToClipboardsuper8text() { var super8text = document.getElementById("super8text").value; var tempInput = document.createElement("input"); tempInput.value = super8text; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); document.execCommand("copy"); document.body.removeChild(tempInput); alert("Text copied to clipboard: " + super8text);} document.getElementById("super8text").value = decodedStringsuper8text; </script> <hr> <!--Pinterest--Bookmarklet--> <a href="https://codepen.io/ryedai1/pen/QWPNBBr" target="_blank"><img src="https://images.vexels.com/media/users/3/137399/isolated/preview/47c9900ae893cbed1e1599ab9c8bcb18-pinterest-symbol-logo.png?w=738&amp;fmt=webp" style="width:50px" alt="pinteresttext">Extract the pinterest main image from the current page</a> (<a target="_blank" href="https://alcea-wisteria.de/PHP/0demo/2024-03-11-ImgExtract4Websites/Pinterest/xtrctpin.php?pinurl=https://www.pinterest.de/pin/804877764644009233/">Demo</a>)<br> <textarea id="pinteresttext" rows="8" cols="80"></textarea><br> <button onclick="openBookmarkDialogpinteresttext()">Add to Bookmark</button> <button onclick="copyToClipboardpinteresttext()">Copy to Clipboard</button> <script> var decodedStringpinteresttext = atob('amF2YXNjcmlwdDooZnVuY3Rpb24oKSB7IHZhciBjdXJyZW50VXJsID0gZW5jb2RlVVJJQ29tcG9uZW50KHdpbmRvdy5sb2NhdGlvbi5ocmVmKTsgdmFyIGFwaVVybCA9ICdodHRwczovL2FsY2VhLXdpc3RlcmlhLmRlL1BIUC8wZGVtby8yMDI0LTAzLTExLUltZ0V4dHJhY3Q0V2Vic2l0ZXMvUGludGVyZXN0L3h0cmN0cGluLnBocD9waW51cmw9JzsgdmFyIHRhcmdldFVybCA9IGFwaVVybCArIGN1cnJlbnRVcmw7IHdpbmRvdy5vcGVuKHRhcmdldFVybCk7IH0pKCk7Cg'); function openBookmarkDialogpinteresttext() { var bookmarkName = prompt("Enter bookmark name:"); if (bookmarkName) { var bookmarkUrl = decodedStringpinteresttext; if (window.navigator.userAgent.indexOf("Chrome") !== -1 && chrome && chrome.bookmarks) { chrome.bookmarks.create({ title: bookmarkName, url: bookmarkUrl }, function() { alert("Bookmark added: " + bookmarkName); }); } else if (window.navigator.userAgent.indexOf("Firefox") !== -1 && browser && browser.bookmarks) { browser.bookmarks.create({ title: bookmarkName, url: bookmarkUrl }).then(function() { alert("Bookmark added: " + bookmarkName); }); } else { alert("Sorry, your browser does not support the bookmarking feature.");}}} function copyToClipboardpinteresttext() { var pinteresttext = document.getElementById("pinteresttext").value; var tempInput = document.createElement("input"); tempInput.value = pinteresttext; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); document.execCommand("copy"); document.body.removeChild(tempInput); alert("Text copied to clipboard: " + pinteresttext);} document.getElementById("pinteresttext").value = decodedStringpinteresttext; </script> <hr> _________________________________________ Screenshoot current page --------------------------------------- <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script> </head> <body> <button onclick="captureScreenshot()">*click*</button> <script> function captureScreenshot() { // Set the dimensions of the screenshot to the entire document, including content beyond the scrollbar var width = document.documentElement.scrollWidth; var height = document.documentElement.scrollHeight; html2canvas(document.body, { width: width, height: height, scrollX: 0, scrollY: 0, windowWidth: document.documentElement.clientWidth, windowHeight: document.documentElement.clientHeight }).then(function(canvas) { var screenshotImage = canvas.toDataURL(); var pageTitle = document.title; var filename = pageTitle.replace(/[^\w\s]/gi, ''); var timestamp = new Date().getTime(); filename += '_' + timestamp; //var link = document.createElement('a'); //link.href = screenshotImage; //link.download = filename + '.png'; //link.click(); var newTab = window.open(); newTab.document.write('<img src="' + screenshotImage + '"/>'); }); } </script> ___________________ Create image snapshot of element: --------------------------------- <p id="customFont" class="customfont" contenteditable="true">Hello world!</p>´ <button id="captureButton">*Cheese!!*</button> <div id="imageContainer"></div> <script> const captureButton = document.getElementById('captureButton'); const imageContainer = document.getElementById('imageContainer'); captureButton.addEventListener('click', function() { const paragraph = document.getElementById('customFont'); let content = paragraph.innerHTML; content = content.replace(/<\/div>/g, ' ').replace(/<div>/g, ' ').replace(/&amp;/g, '&'); const paragraphComputedStyle = getComputedStyle(paragraph); const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); canvas.width = parseFloat(paragraphComputedStyle.width); canvas.height = parseFloat(paragraphComputedStyle.height) + 50; const computedStyle = getComputedStyle(paragraph); context.font = computedStyle.font; context.fillStyle = computedStyle.color; const textMetrics = context.measureText(content); const textHeight = textMetrics.actualBoundingBoxAscent + textMetrics.actualBoundingBoxDescent; const yCoordinate = (canvas.height - textHeight) / 2 + textMetrics.actualBoundingBoxAscent; context.fillText(content, 0, yCoordinate); canvas.toBlob(function(blob) { while (imageContainer.firstChild) { imageContainer.removeChild(imageContainer.firstChild); } const image = document.createElement('img'); const reader = new FileReader(); reader.onloadend = function() { image.src = reader.result; }; reader.readAsDataURL(blob); imageContainer.appendChild(image); }, 'image/png'); }); </script> __________________________ Font test: ---------------------------------------------------- <style type="text/css"> @font-face { font-family: "My Custom Font"; src: url(https://alceawis.de/other/extra/font/GreatVibes-Regular.otf) format("truetype"); } p.customfont { font-family: "My Custom Font", Verdana, Tahoma; } .drag-drop-area { border: 2px dashed #ccc; padding: 20px; text-align: center; font-size: 18px; cursor: pointer; } </style> </head> <body> <p id="customFont" class="customfont" contenteditable="true">Hello world!</p> <input type="range" id="fontSizeSlider" min="10" max="50" value="16" step="2" onchange="changeFontSize()"> <style id="customFontFace"></style> <script> function changeFontSource(fontUrl) { var fontFace = document.getElementById("customFontFace"); fontFace.innerHTML = "@font-face { font-family: 'My Custom Font'; src: url(" + fontUrl + ") format('truetype'); }"; } function changeFontSize() { var fontSize = document.getElementById("fontSizeSlider").value; var customFont = document.getElementById("customFont"); customFont.style.fontSize = fontSize + "px"; } function handleDragOver(event) { event.preventDefault(); event.stopPropagation(); event.dataTransfer.dropEffect = 'copy'; } function handleDrop(event) { event.preventDefault(); event.stopPropagation(); var file = event.dataTransfer.files[0]; var fontUrl = URL.createObjectURL(file); changeFontSource(fontUrl); } function handleUrlInput() { var fontUrl = document.getElementById("fontUrlInput").value; changeFontSource(fontUrl); } function handleFileBrowse(event) { var file = event.target.files[0]; var fontUrl = URL.createObjectURL(file); changeFontSource(fontUrl); } // Function to handle the font selection from the dropdown function handleFontSelection() { var dropdown = document.getElementById("fontDropdown"); var selectedOption = dropdown.options[dropdown.selectedIndex]; var fontUrl = selectedOption.value; var pretext = selectedOption.getAttribute("pretext"); var softkeyboardUrl = selectedOption.getAttribute("softkeyboard"); if (pretext) { var customFont = document.getElementById("customFont"); customFont.innerText = pretext; } if (softkeyboardUrl) { fetchSoftkeyboardContent(softkeyboardUrl); } changeFontSource(fontUrl); } function fetchSoftkeyboardContent(url) { fetch(url) .then(function (response) { return response.text(); }) .then(function (data) { var softkeyboardDiv = document.getElementById("softkeyboardDiv"); softkeyboardDiv.innerHTML = data; }) .catch(function (error) { console.log('Error fetching softkeyboard content:', error); }); } </script> <select id="fontDropdown" onchange="handleFontSelection()"> <option value="other/extra/font/GreatVibes-Regular.otf" pretext="Great Vibes !">Great Vibes</option> <option value="other/extra/font/learning_curve_regular_ot_ps.otf" pretext="Learning Curves">Learning Curve</option> <option value="other/extra/font/learning_curve_regular_ot_ps.otf" pretext="">--other--</option> <option value="other/extra/font/others/heo.ttf" pretext="󱴻󱳍󱳳󱴰" softkeyboard="other/extra/font/0softkbs/heo.html">Heo</option> </select> <hr> <div class="drag-drop-area" ondragover="handleDragOver(event)" ondrop="handleDrop(event)"> <p>Drag and drop a font file here</p> </div> <label for="fontUrlInput">or enter a URL to a font:</label> <input type="text" id="fontUrlInput" onchange="handleUrlInput()"> <!-- Add file browse input element --> <input type="file" id="fileBrowseInput" style="display: none;" onchange="handleFileBrowse(event)"> <br>or pick a local file: <button onclick="document.getElementById('fileBrowseInput').click()">Browse</button> <div id="softkeyboardDiv"></div> <!---Save_to image ---> <button id="captureButton">*Cheese!!*</button> <div id="imageContainer"></div> <script> const captureButton = document.getElementById('captureButton'); const imageContainer = document.getElementById('imageContainer'); captureButton.addEventListener('click', function() { const paragraph = document.getElementById('customFont'); let content = paragraph.innerHTML; content = content.replace(/<\/div>/g, ' ').replace(/<div>/g, ' '); const paragraphComputedStyle = getComputedStyle(paragraph); const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); canvas.width = parseFloat(paragraphComputedStyle.width); canvas.height = parseFloat(paragraphComputedStyle.height) + 50; const computedStyle = getComputedStyle(paragraph); context.font = computedStyle.font; context.fillStyle = computedStyle.color; const textMetrics = context.measureText(content); const textHeight = textMetrics.actualBoundingBoxAscent + textMetrics.actualBoundingBoxDescent; const yCoordinate = (canvas.height - textHeight) / 2 + textMetrics.actualBoundingBoxAscent; context.fillText(content, 0, yCoordinate); canvas.toBlob(function(blob) { while (imageContainer.firstChild) { imageContainer.removeChild(imageContainer.firstChild); } const image = document.createElement('img'); const reader = new FileReader(); reader.onloadend = function() { image.src = reader.result; }; reader.readAsDataURL(blob); imageContainer.appendChild(image); }, 'image/png'); }); </script> ________________________________________ Save current page to html -------------------------- <unique> <button onclick="savePageAsHTML()">Save Page as HTML</button> <script> function savePageAsHTML() { var placeholder = document.querySelector('unique'); placeholder.parentNode.removeChild(placeholder); var html = document.documentElement.outerHTML; var filename = 'dyingfedi.html'; var element = document.createElement('a'); element.setAttribute('href', 'data:text/html;charset=utf-8,' + encodeURIComponent(html)); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); document.body.appendChild(placeholder); } </script> </unique> ______________ FolderLister (spoilertag) with download as html function ----------------------------- <!DOCTYPE html> <html> <head> <style> .folder { margin-left: 20px; } .empty-folder { color: gray; } </style> </head> <body> <h1>Drag and Drop Folder Lister</h1> <div> <label for="baseUrl">Base URL: </label> <input type="text" id="baseUrl" placeholder="Enter base URL" value="http://10.10.10.254/data/UsbDisk1/Volume1"> </div> <div> <label for="excludeText">Exclude Text: </label> <input type="text" id="excludeText" placeholder="Enter text to exclude" value="D_drive/"> </div> <div id="folderList" ondragover="allowDrop(event)" ondrop="drop(event)"> <p>Drop a folder here to list its contents:</p> </div> <script> function allowDrop(event) { event.preventDefault(); } function drop(event) { event.preventDefault(); const folder = event.dataTransfer.items[0].webkitGetAsEntry(); const baseUrl = document.getElementById("baseUrl").value; const excludeText = document.getElementById("excludeText").value; listFolderContents(folder, document.getElementById("folderList"), baseUrl, excludeText); } function listFolderContents(folder, parentElement, baseUrl, excludeText) { if (folder.isDirectory) { const details = document.createElement("details"); const summary = document.createElement("summary"); summary.textContent = folder.name; details.appendChild(summary); const subFolderList = document.createElement("ul"); details.appendChild(subFolderList); parentElement.appendChild(details); const directoryReader = folder.createReader(); function readEntries() { directoryReader.readEntries(function (entries) { if (entries.length > 0) { entries.forEach(function (entry) { listFolderContents(entry, subFolderList, baseUrl, excludeText); }); readEntries(); // Continue reading entries in chunks } else if (subFolderList.childElementCount === 0) { details.classList.add("empty-folder"); // Apply the CSS class to the empty folder } }); } readEntries(); } else { const listItem = document.createElement("li"); const link = document.createElement("a"); link.textContent = folder.name; link.target = "_blank"; link.href = baseUrl ? baseUrl + folder.fullPath : "file:///123/" + folder.fullPath; if (excludeText && link.href.includes(excludeText)) { link.href = link.href.replace(excludeText, ""); } listItem.appendChild(link); parentElement.appendChild(listItem); } } </script> <!--Download--> <script> function downloadHTML() { const folderList = document.getElementById("folderList").cloneNode(true); const baseUrl = document.getElementById("baseUrl").value; updateHyperlinks(folderList, baseUrl); const doctype = document.implementation.createDocumentType('html', '', ''); const html = document.implementation.createDocument('', 'html', doctype); html.documentElement.appendChild(folderList); const serializer = new XMLSerializer(); const htmlString = serializer.serializeToString(html); const blob = new Blob([htmlString], { type: 'text/html' }); const url = URL.createObjectURL(blob); const downloadLink = document.createElement('a'); downloadLink.href = url; downloadLink.download = 'folder_list.html'; downloadLink.click(); } function updateHyperlinks(element, baseUrl) { const links = element.getElementsByTagName('a'); for (let i = 0; i < links.length; i++) { const link = links[i]; const href = link.getAttribute('href'); if (baseUrl) { link.href = href; } else { link.href = href; } } } </script> <button onclick="downloadHTML()">Download HTML</button> ____________________________ Github commits per day chart ------------------------------------ <!DOCTYPE html> <html> <head> <title>Commit Chart</title> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <div> <label for="apiUrl">API URL:</label> <input type="text" id="apiUrl" value="https://api.github.com/repos/Ry3yr/ry3yr.github.io/commits?per_page=50"> <button id="loadButton" onclick="loadChart()">Load Chart</button> </div> <div id="repoName"></div> <canvas id="commitChart"></canvas> <script> let chart; function loadChart() { if (chart) { chart.destroy(); // Clear the existing chart } const apiUrl = document.getElementById('apiUrl').value; fetch(apiUrl) .then(response => response.json()) .then(data => { // Extract commit dates const commitDates = data.map(commit => new Date(commit.commit.author.date).toLocaleDateString()); // Count commits per day const commitCounts = {}; commitDates.forEach(date => { commitCounts[date] = (commitCounts[date] || 0) + 1; }); // Prepare data for the chart const labels = Object.keys(commitCounts); const values = Object.values(commitCounts); // Get the repository name from the API URL const repoName = getRepoName(apiUrl); // Display the repository name document.getElementById('repoName').textContent = `Repository: ${repoName}`; // Create the chart const ctx = document.getElementById('commitChart').getContext('2d'); chart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: 'Commits per Day', data: values, backgroundColor: 'rgba(54, 162, 235, 0.6)' }] }, options: { scales: { x: { display: true, reverse: true, // Invert the x-axis title: { display: true, text: 'Date' } }, y: { beginAtZero: true, stepSize: 1 } } } }); }); } // Extract the repository name from the API URL function getRepoName(apiUrl) { const parts = apiUrl.split('/'); return parts[parts.length - 3] + '/' + parts[parts.length - 2]; } // Load chart with default API URL loadChart(); </script> ______________________ URL-online-check-and-fallback-redirect ------------------------------------------------------------ <a href="#" id="checkURLLink">Check URL</a> <div id="result"></div> <script> document.getElementById('checkURLLink').addEventListener('click', function() { var url = "https://alcea-wisteria.de/PHP/0demo/2023-08-15-JSFiddle-Clone/htmls/0ld/link.html"; //var url = "https://alcea-wisteria.de/PHP/0demo/2023-08-15-JSFiddle-Clone/jsfiddle-user.ph?mode=lowbandwidth" var xhr = new XMLHttpRequest(); xhr.open('HEAD', url); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { const corsStatus = xhr.getResponseHeader('Access-Control-Allow-Origin'); const headers = xhr.getAllResponseHeaders(); const result = document.getElementById('result'); if (corsStatus || headers.includes('content-length') || headers.includes('content-type') || headers.includes('last-modified')) { result.innerHTML = '<strong>Accessing original URL</strong><br>'; result.innerHTML += 'Access-Control-Allow-Origin: ' + corsStatus + '<br>'; window.open(url, "_blank"); } else { result.innerHTML = '<strong>Accessing static backup</strong><br>'; result.innerHTML += 'Response Headers:<br>' + headers + '<br>'; var alternativeUrl = "https://ry3yr.github.io/jsfiddleclone/jsfiddle-user.html?mode=lowbandwidth"; window.open(alternativeUrl, "_blank"); } } }; xhr.send(); }); </script> ________________________________ Set favico --------- <script> var link = document.createElement('link'); link.rel = 'icon'; link.type = 'image/gif'; link.href = 'https://alceawis.de/other/images/bg/chocoomnomnom32.gif'; document.head.appendChild(link); </script> _____________________ Txt and Folder lister with Reorder capability (can generate cmd too) --------------------------------------------------------------------- <!DOCTYPE html> <html> <head> <title>Draggable Grid Example</title> <style> .grid-container { display: grid; grid-template-columns: repeat(2, 1fr); grid-gap: 10px; } .grid-item { padding: 10px; border: 1px solid #ccc; background-color: #f9f9f9; cursor: grab; } .grid-item.dragging { opacity: .5; cursor: grabbing; } </style> </head> <body> <div class="grid-container"> <div id="folder-grid" class="grid-item"> <h3>Folder Files</h3> </div> <div id="text-grid" class="grid-item"> <h3>Text Lines</h3> </div> </div> <script> let folderGrid = null; let textGrid = null; let clickedItem = null; function createGridItem(content, draggable = true) { const gridItem = document.createElement("div"); gridItem.className = "grid-item"; gridItem.textContent = content; if (draggable) { gridItem.draggable = true; gridItem.addEventListener("dragstart", function (event) { event.dataTransfer.setData("text/plain", content); gridItem.classList.add("dragging"); }); gridItem.addEventListener("dragend", function () { gridItem.classList.remove("dragging"); }); } gridItem.addEventListener("click", function () { if (clickedItem === null) { clickedItem = gridItem; gridItem.classList.add("dragging"); } else { swapItems(clickedItem, gridItem); clickedItem = null; gridItem.classList.remove("dragging"); } }); return gridItem; } function addFileToList(file) { if (file.isDirectory) { return; // Exclude directories from the list } const fileName = file.name; const isHeaderPresent = folderGrid.querySelector("h3"); const gridItem = createGridItem(fileName); if (isHeaderPresent) { folderGrid.appendChild(gridItem); } else { const header = document.createElement("h3"); header.textContent = "Folder Files"; folderGrid.appendChild(header); folderGrid.appendChild(gridItem); } } function addLineToList(line) { const gridItem = createGridItem(line.trim(), false); textGrid.appendChild(gridItem); } function readTextFile(file) { const reader = new FileReader(); reader.onload = function (event) { const lines = event.target.result.split("\n"); lines.forEach((line) => { addLineToList(line); }); }; reader.readAsText(file); } function traverseDirectory(directory) { const directoryReader = directory.createReader(); directoryReader.readEntries(function (entries) { entries.forEach((entry) => { if (entry.isFile) { entry.file(function (file) { if (file.type === "text/plain") { readTextFile(file); } else { addFileToList(file); } }); } else if (entry.isDirectory) { addFileToList(entry); traverseDirectory(entry); } }); }); } function swapItems(item1, item2) { const tempContent = item1.textContent; item1.textContent = item2.textContent; item2.textContent = tempContent; } window.addEventListener("DOMContentLoaded", function () { folderGrid = document.getElementById("folder-grid"); textGrid = document.getElementById("text-grid"); folderGrid.addEventListener("dragover", function (event) { event.preventDefault(); }); folderGrid.addEventListener("drop", function (event) { event.preventDefault(); const isHeaderPresent = folderGrid.querySelector("h3"); if (!isHeaderPresent) { const header = document.createElement("h3"); header.textContent = "Folder Files"; folderGrid.appendChild(header); } const items = event.dataTransfer.items; for (let i = 0; i < items.length; i++) { const item = items[i]; if (item.kind === "file") { const entry = item.webkitGetAsEntry(); if (entry) { if (entry.isDirectory) { addFileToList(entry); traverseDirectory(entry); } else if (entry.isFile) { entry.file(function (file) { if (file.type === "text/plain") { readTextFile(file); } else { addFileToList(file); } }); } } } } }); textGrid.addEventListener("dragover", function (event) { event.preventDefault(); }); textGrid.addEventListener("drop", function (event) { event.preventDefault(); const items = event.dataTransfer.items; for (let i = 0; i < items.length; i++) { const item = items[i]; if (item.kind === "file") { const entry = item.webkitGetAsEntry(); if (entry && entry.isFile) { entry.file(function (file) { if (file.type === "text/plain") { readTextFile(file); } }); } } } }); }); </script> </body> <label for="insert-text">Insert Text:</label> <input type="text" id="insert-text" placeholder="Insert Text" /> <br /> <label for="placeholder-text">Placeholder Text:</label> <input type="text" id="placeholder-text" placeholder="Placeholder Text" /> <br /> <label for="after-text">After Text:</label> <input type="text" id="after-text" placeholder="After Text" /> <br /> <button id="copy-button">Copy to Clipboard</button> <script> document.getElementById("copy-button").addEventListener("click", function () { const folderGridLines = Array.from(document.getElementById("folder-grid").querySelectorAll("div")).map(line => line.innerText); const textGridLines = Array.from(document.getElementById("text-grid").querySelectorAll("div")).map(line => line.innerText); const insertText = document.getElementById("insert-text").value || "Insert text"; const placeholderText = document.getElementById("placeholder-text").value || "placeholder"; const afterText = document.getElementById("after-text").value; const combinedContent = folderGridLines.map((line, index) => `${insertText} "${line}" ${placeholderText} "${textGridLines[index]}"${afterText ? " " + afterText : ""}`).join('\n'); const tempTextarea = document.createElement("textarea"); tempTextarea.value = combinedContent; document.body.appendChild(tempTextarea); tempTextarea.select(); document.execCommand("copy"); document.body.removeChild(tempTextarea); //alert("Content copied to clipboard!"); }); </script> </body> </html> ________________ Line-Keeper--Remover-add-leading-0s ----------------------------------- <body> <textarea id="linesToFilter" rows="10" cols="50"></textarea> <br> <input type="text" id="keyword" placeholder="Enter keyword" /> <button id="filterButton">Filter Lines</button> <br> <input type="text" id="eraseTextbox" placeholder="Enter phrase to erase" /> <button id="eraseButton">Erase</button> <br> <button id="leadingNumbersButton">Leading Numbers</button> <input type="checkbox" id="leadingZeroCheckbox" /> <label for="leadingZeroCheckbox">Leading Zero</label> <script> const linesToFilterInput = document.getElementById('linesToFilter'); const keywordInput = document.getElementById('keyword'); const filterButton = document.getElementById('filterButton'); const mainTextbox = document.getElementById('linesToFilter'); const eraseTextbox = document.getElementById('eraseTextbox'); const eraseButton = document.getElementById('eraseButton'); const leadingNumbersButton = document.getElementById('leadingNumbersButton'); const leadingZeroCheckbox = document.getElementById('leadingZeroCheckbox'); filterButton.addEventListener('click', function() { const linesToFilter = linesToFilterInput.value.split('\n'); const keyword = keywordInput.value; const filteredLines = linesToFilter.filter(line => line.includes(keyword)); const newContent = filteredLines.join('\n'); linesToFilterInput.value = newContent; }); eraseButton.addEventListener('click', function() { const phraseToErase = eraseTextbox.value; const content = mainTextbox.value; const newContent = content.replace(new RegExp(phraseToErase, 'g'), ''); mainTextbox.value = newContent; }); leadingNumbersButton.addEventListener('click', function() { const linesToNumber = mainTextbox.value.split('\n'); const useLeadingZero = leadingZeroCheckbox.checked; let numberedLines = ''; for (let i = 0; i < linesToNumber.length; i++) { let lineNumber = i + 1; if (useLeadingZero) { lineNumber = lineNumber.toString().padStart(linesToNumber.length.toString().length, '0'); } numberedLines += `${lineNumber}. ${linesToNumber[i]}\n`; } mainTextbox.value = numberedLines; }); </script> </body> </html> _______________________________ Fetch Youtube Playlist + duration (&reorder cap) -------------------------------- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>YouTube Playlist Videos</title> <style> table {border-collapse: collapse; width: 100%} td, th {text-align: left; padding: 8px; border-bottom: 1px solid #ddd} th {background-color: #f2f2f2} </style> </head> <body> <form id="playlistForm"> <label for="playlistInput">YouTube Playlist URL:</label> <input type="text" id="playlistInput" required><br> <label for="apiKeyInput">YouTube API Key:</label> <input type="text" id="apiKeyInput" required><br> <input type="checkbox" id="sortCheckbox"> <label for="sortCheckbox">Sort by playlist order</label><br> <input type="submit" value="Get Video List"> </form> <table id="videoTable"> <thead> <tr> <th>Video Name</th> <th>Playtime</th> <th>Date</th> <th>Exact Time of Upload</th> </tr> </thead> <tbody id="videoList"></tbody> </table> <script> function convertDuration(duration) { var match = duration.match(/PT(\d+H)?(\d+M)?(\d+S)?/); var hours = (parseInt(match[1]) || 0); var minutes = (parseInt(match[2]) || 0); var seconds = (parseInt(match[3]) || 0); return hours + "h " + minutes + "m " + seconds + "s"; } function convertDate(date) { var isoDate = new Date(date); return isoDate.toDateString(); } function convertExactTime(date) { var isoDate = new Date(date); var year = isoDate.getFullYear().toString().padStart(4, '0'); var month = (isoDate.getMonth() + 1).toString().padStart(2, '0'); var day = isoDate.getDate().toString().padStart(2, '0'); var hours = isoDate.getHours().toString().padStart(2, '0'); var minutes = isoDate.getMinutes().toString().padStart(2, '0'); return year + month + day + '' + hours + '' + minutes; } document.getElementById("playlistForm").addEventListener("submit", function (event) { event.preventDefault(); var playlistUrl = document.getElementById("playlistInput").value; var apiKey = document.getElementById("apiKeyInput").value; var playlistId = playlistUrl.match(/(?:list=)([\w-]+)/)[1]; var apiUrl = "https://www.googleapis.com/youtube/v3/playlistItems"; var params = { part: "snippet,contentDetails", maxResults: 150, playlistId: playlistId, key: apiKey, }; var url = apiUrl + "?" + Object.keys(params) .map(function (key) { return encodeURIComponent(key) + "=" + encodeURIComponent(params[key]); }) .join("&"); var videoList = document.getElementById("videoList"); videoList.innerHTML = ""; var videoItems = []; var totalDuration = 0; // Variable to store the total playtime var fetchPromises = []; // Array to store fetch promises var pageToken = ""; // Pagination token function fetchVideos(pageToken) { var url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&playlistId=" + playlistId + "&maxResults=50&key=" + apiKey + "&pageToken=" + pageToken; fetch(url) .then((response) => response.json()) .then((data) => { var nextPageToken = data.nextPageToken; // Get pagination token for the next page data.items.forEach(function (item, index) { var videoId = item.contentDetails.videoId; var videoTitle = item.snippet.title; var vId = item.contentDetails.videoId; var durUrl = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=" + vId + "&key=" + apiKey; var fetchPromise = fetch(durUrl) .then((response) => response.json()) .then((durationData) => { var duration = durationData.items[0].contentDetails.duration; var videoDuration = convertDuration(duration); var videoDate = item.snippet.publishedAt; var videoDateFormatted = convertDate(videoDate); var videoExactTime = convertExactTime(videoDate); videoItems.push({ videoId: videoId, videoTitle: videoTitle, videoDuration: videoDuration, videoDate: videoDateFormatted, videoExactTime: videoExactTime, playlistIndex: index, }); totalDuration += getDurationInSeconds(duration); }) .catch((error) => { console.log(error); // Handle the error, e.g., display an error message for this video }); fetchPromises.push(fetchPromise); }); if (nextPageToken) { // Fetch the next page if there is a pagination token fetchVideos(nextPageToken); } else { // All pages have been fetched, proceed with processing the data Promise.all(fetchPromises) .then(() => { if (document.getElementById("sortCheckbox").checked) { // Sort by playlist order videoItems.sort((a, b) => a.playlistIndex - b.playlistIndex); } else { // Sort by date videoItems.sort( (a, b) => new Date(a.videoDate) - new Date(b.videoDate) ); } videoItems.forEach(function (video) { var videoRow = document.createElement("tr"); var videoNameCell = document.createElement("td"); var videoNameLink = document.createElement("a"); videoNameLink.href = "https://www.youtube.com/watch?v=" + video.videoId; videoNameLink.target = "_blank"; videoNameLink.textContent = video.videoTitle; videoNameCell.appendChild(videoNameLink); videoRow.appendChild(videoNameCell); var playtimeCell = document.createElement("td"); playtimeCell.textContent = video.videoDuration; videoRow.appendChild(playtimeCell); var dateCell = document.createElement("td"); dateCell.textContent = video.videoDate; videoRow.appendChild(dateCell); var exactTimeCell = document.createElement("td"); exactTimeCell.textContent = video.videoExactTime; videoRow.appendChild(exactTimeCell); videoList.appendChild(videoRow); }); var totalDurationRow = document.createElement("tr"); var totalDurationCell = document.createElement("td"); totalDurationCell.setAttribute("colspan", "4"); totalDurationCell.innerHTML = "Total Playtime: " + convertSecondsToDuration(totalDuration) + " <a href='" + playlistUrl + "' target='_blank'>" + playlistUrl + "</a>"; totalDurationRow.appendChild(totalDurationCell); videoList.appendChild(totalDurationRow); }) .catch((error) => { console.log(error); var videoTable = document.getElementById("videoTable"); videoTable.innerHTML = "An error occurred while fetching the video list."; }); } }) .catch((error) => { console.log(error); var videoTable = document.getElementById("videoTable"); videoTable.innerHTML = "An error occurred while fetching the video list."; }); } fetchVideos(pageToken); function getDurationInSeconds(duration) { var match = duration.match(/PT(\d+H)?(\d+M)?(\d+S)?/); var hours = parseInt(match[1]) || 0; var minutes = parseInt(match[2]) || 0; var seconds = parseInt(match[3]) || 0; return hours * 3600 + minutes * 60 + seconds; } function convertSecondsToDuration(seconds) { var hours = Math.floor(seconds / 3600); var minutes = Math.floor((seconds % 3600) / 60); var secs = seconds % 60; return ( hours.toString().padStart(2, "0") + "h " + minutes.toString().padStart(2, "0") + "m " + secs.toString().padStart(2, "0") + "s" ); } }); function copyTableToClipboard() { var table = document.getElementById("videoTable"); var tableHtml = table.outerHTML; var tempElement = document.createElement("textarea"); tempElement.value = tableHtml; document.body.appendChild(tempElement); tempElement.select(); document.execCommand("copy"); document.body.removeChild(tempElement); alert("Table copied to clipboard as HTML!"); } var copyButton = document.createElement("button"); copyButton.textContent = "Copy Table"; copyButton.addEventListener("click", copyTableToClipboard); document.body.appendChild(copyButton); function reorderRowsByDate() { var table = document.getElementById("videoTable"); var tbody = table.querySelector("#videoList"); var rows = Array.from(tbody.getElementsByTagName("tr")); var tableData = rows.map(function (row) { return Array.from(row.getElementsByTagName("td")).map(function (cell) { if (cell.hasChildNodes() && cell.firstChild.nodeName === "A") { return cell.innerHTML; // Preserve link structure } else { return cell.textContent; } }); }); tableData.sort(function (a, b) { var dateA = new Date(a[2]); var dateB = new Date(b[2]); return dateA - dateB; }); for (var i = 0; i < rows.length; i++) { var cells = rows[i].getElementsByTagName("td"); for (var j = 0; j < cells.length; j++) { // Restore link structure if necessary if (tableData[i][j].includes("<a href=")) { cells[j].innerHTML = tableData[i][j]; } else { cells[j].textContent = tableData[i][j]; } } } } var reorderButton = document.createElement("button"); reorderButton.textContent = "Reorder by Date"; reorderButton.addEventListener("click", reorderRowsByDate); document.body.appendChild(reorderButton); </script> <button onclick="reorderRowsByVideoName()">Reorder by Video Name</button> <script> function reorderRowsByVideoName() { var table = document.getElementById("videoTable"); var tbody = table.querySelector("#videoList"); var rows = Array.from(tbody.getElementsByTagName("tr")); var tableData = rows.map(function(row) { return Array.from(row.getElementsByTagName("td")).map(function(cell) { if (cell.hasChildNodes() && cell.firstChild.nodeName === "A") { return cell.innerHTML; } else { return cell.textContent; } }); }); tableData.sort(function(a, b) { var nameA = a[0].toLowerCase(); var nameB = b[0].toLowerCase(); if (nameA < nameB) return -1; if (nameA > nameB) return 1; return 0; }); for (var i = 0; i < rows.length; i++) { var cells = rows[i].getElementsByTagName("td"); for (var j = 0; j < cells.length; j++) { if (tableData[i][j].includes("<a href=")) { cells[j].innerHTML = tableData[i][j]; } else { cells[j].textContent = tableData[i][j]; } } } } </script> <button onclick="reorderRowsByUploadTime()">Reorder by Exact Time of Upload</button> <script> function reorderRowsByUploadTime() { var table = document.getElementById("videoTable"); var tbody = table.querySelector("#videoList"); var rows = Array.from(tbody.getElementsByTagName("tr")); // Extract the rows and their corresponding timestamps var tableData = rows.map(function(row) { // Assuming the timestamp is in the last cell of each row var cells = row.getElementsByTagName("td"); var timestamp = cells[cells.length - 1].textContent.trim(); return { row: row, time: parseInt(timestamp) }; }); // Sort the rows by the timestamp tableData.sort(function(a, b) { return a.time - b.time; }); // Reorder the rows in the table body tableData.forEach(function(data) { tbody.appendChild(data.row); }); } </script> <!---https://stackoverflow.com/questions/15596753/how-do-i-get-video-durations-with-youtube-api-version-3---> _______________________________ Open details tag (id) if keyword exists in url ------------------------------------------------------------------- <script> window.addEventListener("DOMContentLoaded", function() { var url = window.location.href; var keyword = "instance"; if (url.indexOf(keyword) !== -1) { var detailsElement = document.getElementById("mtd"); detailsElement.setAttribute("open", "true"); } }); </script> <details id="mtd"></details> ____________________________________________ Limit link to header <h1> --------------------- <span style="display: block; text-align: center;"><a href="Hobbies_old.html" style="color: #454138;"><h1 style="display: inline;">Hobbies</h1></a></span> ______________________ Sneaky Random youtube playlistvideo autoplay er --------------------------------------------------------------- <div id="videoTitle"></div> <script> const urlParams = new URLSearchParams(window.location.search); const apiKey = urlParams.get('apikey') || 'YOUR_DEFAULT_API_KEY'; const playlistId = urlParams.get('playlistid') || 'PLdR7m7PFLzQ7RqOVfxk2Fr2F-a7iWzovn'; function fetchRandomVideo() { fetch(`https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=${playlistId}&key=${apiKey}`) .then(response => response.json()) .then(data => { const randomIndex = Math.floor(Math.random() * data.items.length); const video = data.items[randomIndex].snippet; const videoId = video.resourceId.videoId; const iframe = document.createElement('iframe'); iframe.width = '100'; iframe.height = '20'; iframe.src = `https://super8.absturztau.be/embed/${videoId}?si=playlist=${playlistId}&autoplay=1`; iframe.title = 'YouTube video player'; iframe.frameBorder = '0'; iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share'; iframe.allowFullscreen = true; document.body.appendChild(iframe); const videoTitle = video.title; const titleElement = document.getElementById('videoTitle'); titleElement.textContent = videoTitle; }) .catch(error => console.log('Error:', error)); } fetchRandomVideo(); </script> </body> ______________________________ Redirect current url/page querystrings to other url -------------------------------------------------- <a href="#" onclick="redirectToTargetURL();">Click here to redirect querystrings</a> <script> function redirectToTargetURL() { var currentURL = window.location.href; var targetURL = "https://alceawis.de/other/extra/scripts/z_teststuff/mtdnotifications.php"; var queryParams = currentURL.split("?")[1]; var finalURL = targetURL + "?" + queryParams; window.location.href = finalURL; } </script> ___________________________________ Display multiuser mtd tl in tableview ----------------------------------------- <style> table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid black; padding: 2px; text-align: left; } th { background-color: #f2f2f2; } </style> </head> <body> <table> <thead> <tr> <th>User ID</th> <th>Posts</th> </tr> </thead> <tbody id="results"></tbody> </table> <script> // Fetch the contents of the mtdusers.txt file fetch('https://ry3yr.github.io/mtduserspublic.txt') .then(response => response.text()) .then(data => { // Split the data into lines const lines = data.split('\n'); // Iterate over each line lines.forEach(line => { // Extract the user ID and instance URL const [userid, instanceurl] = line.split(' '); // Construct the API URL const apiUrl = `${instanceurl}/api/v1/accounts/${userid}/statuses`; // Check if the URL contains the 'limit' parameter const urlParams = new URLSearchParams(window.location.search); const limitParam = urlParams.get('limit'); const limit = limitParam ? parseInt(limitParam) : 1; // Fetch posts using the Mastodon API fetch(`${apiUrl}?limit=${limit}`) .then(response => response.json()) .then(data => { // Check if there are any posts if (data.length > 0) { // Create a new row in the table for the user const tableRow = document.createElement('tr'); // User ID cell const userIdCell = document.createElement('td'); fetch(`${instanceurl}/api/v1/accounts/${userid}`) .then(response => response.json()) .then(data => { const username = data.username; const userpfp = data.avatar_static; const userLink = document.createElement('a'); userLink.href = `${instanceurl}/@${username}`; userLink.target = '_blank'; userLink.innerHTML = `<img src="${userpfp}" alt="${username}" width="128px"> ${username}`; userIdCell.appendChild(userLink); }) .catch(error => { console.log('Error fetching user data for User ID:', userid); console.error(error); }); tableRow.appendChild(userIdCell); // Posts cell const postsCell = document.createElement('td'); // Iterate over each post data.forEach(async post => { const postContent = await replaceEmojis(post.content, post.emojis); const linkUrl = `${instanceurl}/web/statuses/${post.id}`; const timestamp = new Date(post.created_at).toLocaleString(); // Create a separate cell for each post const postCell = document.createElement('td'); postCell.innerHTML = `${postContent}<br><a href="${linkUrl}" target="_blank">View</a> ${timestamp}`; postsCell.appendChild(postCell); }); // Add the posts cell to the table row tableRow.appendChild(postsCell); // Append the row to the table body const tableBody = document.getElementById('results'); tableBody.appendChild(tableRow); } else { console.log('No posts found for User ID:', userid); } }) .catch(error => { console.log('Error fetching posts for User ID:', userid); console.error(error); }); }); }) .catch(error => { console.log('Error:', error); }); // Function to replace emoji codes with images async function replaceEmojis(content, emojis) { for (const emoji of emojis) { const shortcode = emoji.shortcode; const url = emoji.url; const shortcodePattern = new RegExp(':' + shortcode + ':', 'g'); const emojiTag = `<img src="${url}" alt="${shortcode}" width="20px">`; content = content.replace(shortcodePattern, emojiTag); } return content; } </script> </body> </html> ____________________________ Navbar with hamburger menu toggle ----------------------------------------- <style> .navbar{list-style-type:none;margin:0;padding:0;background-color:#fff;float:right;margin-right:120px}.navbar li{display:inline-block;position:relative}.navbar a{display:block;color:#000;text-decoration:none;padding:8px}.navbar a:hover{background-color:#f5f}.submenu{display:none;position:absolute;background-color:#fff;left:-45px;top:100%;width:200px}.navbar li:hover .submenu{display:block}.submenu li{display:block;color:#000}.navbar .active .submenu{top:0} </style> <script> function toggleNavbar() { var navbar = document.getElementById('navbar'); navbar.style.display = (navbar.style.display === 'none' || navbar.style.display === '') ? 'block' : 'none'; } </script> <script> function toggleLayout() { var extraLink = document.getElementById('extraLink'); var navbar = document.querySelector('.navbar'); var submenus = document.querySelectorAll('.submenu'); var checkbox = document.getElementById('layoutCheckbox'); if (checkbox.checked) { extraLink.style.display = 'inline'; navbar.style.position = 'absolute'; navbar.style.left = '0'; navbar.style.top = '0'; navbar.style.margin = '0'; navbar.style.width = '120px'; navbar.style.height = '100vh'; navbar.style.display = 'flex'; navbar.style.flexDirection = 'column'; submenus.forEach(function(submenu) {submenu.style.left = '100%'; submenu.style.top = '0';}); } else { //extraLink.style.display = 'none'; navbar.style.float = 'right'; navbar.style.marginRight = '120px'; navbar.style.marginLeft = '0';}} </script> <a href="#" id="extraLink" style="position: fixed; right: 130px; top: 0;display:none;" onclick="toggleNavbar(event)">[-]</a> <nav> <ul class="navbar" id="navbar"> <li class="u-nav-item"><a class="u-button-style u-nav-link u-text-active-palette-1-base u-text-hover-palette-2-base" href="index.html">Homepage</a></li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-text-active-palette-1-base u-text-hover-palette-2-base" href="About.html?user=alcea">About</a></li> <li class="u-nav-item"> <a class="u-button-style u-nav-link u-text-active-palette-1-base u-text-hover-palette-2-base" href="Contact.html">Contact</a> <div class="u-nav-popup submenu"> <ul class="u-h-spacing-5 u-nav u-unstyled u-v-spacing-5 u-nav-2"> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="https://www.abcsubmit.com/view/id_1f8339emu_jn1?utm=abcsubmit" target="_blank">Mail [📬]</a></li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="verify.html#mastodon" target="_blank">Mastodon [📬]</a></li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="verify.html#twitter" target="_blank">Twitter [📬]</a></li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="https://reddit.com/user/repeekyraid#https://www.reddit.com/user/-Rye-/" target="_blank">Reddit [📬]</a></li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="Comments.html">Comments</a></li> </ul></div></li><li class="u-nav-item"> <a class="u-button-style u-nav-link u-text-active-palette-1-base u-text-hover-palette-2-base" href="Hobbies.html">Hobbies</a> <div class="u-nav-popup submenu"> <ul class="u-h-spacing-5 u-nav u-unstyled u-v-spacing-5 u-nav-3"> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="All_Project_%28spoiler_button%29.html">OSTRip </a> </li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="pastebinlinks.html?note=FAQ" target=_blank>FAQ [🡕]</a> </li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="Art.html">Art</a> </li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="code.html">Code</a> </li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="Games.html">GamingStuff</a> </li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="Blog.html">Blog</a> </li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="favs.html">Favorites</a> </li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="https://ry3yr.github.io/OSTR/" target=_blank>OldSite [🡕]</a> </li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="UnderratedContent.html" target=_blank>Underrated [🡕]</a> </li> </ul></div></li><li class="u-nav-item"> <a class="u-button-style u-nav-link u-text-active-palette-1-base u-text-hover-palette-2-base" href="Music.html">Music</a> <div class="u-nav-popup submenu"><ul class=u-"nav-4"> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="Releases.html">Releases</a> </li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="Startseiteplayer.html">Musicplayer</a> </li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="midisheetmusic.html">Sheet Music (Midi)</a> </li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="Unresoundtracker.html">UnreSoundtracker</a> </li> <li class="u-nav-item"><a class="u-button-style u-nav-link u-white" href="radio.html">Radio/Shoutcast</a> </li> <li class="u-nav-item"><input type="checkbox" id="layoutCheckbox" onchange="toggleLayout()"></li> </ul></div></li></ul></nav> ________________________________________ Fetch pixiv link and display from random -------------------------------------- <!--for use with --https://codepen.io/ryedai1/pen/ZEPGdOx--> <button id="extractButton">Random pixiv !</button> <div id="artworkContainer"></div> <script> document.getElementById('extractButton').addEventListener('click', function() { // Fetch the HTML file fetch('https://ry3yr.github.io/pixiv-artworks-archive.html') .then(response => response.text()) .then(html => { // Create a temporary DOM element to parse the HTML const tempElement = document.createElement('div'); tempElement.innerHTML = html; const artworkLinks = tempElement.querySelectorAll('a[target=_blank]'); const randomIndex = Math.floor(Math.random() * artworkLinks.length); const randomArtworkLink = artworkLinks[randomIndex]; const linkHref = randomArtworkLink.href; const linkText = randomArtworkLink.textContent; const artworkId = linkHref.match(/\/(\d+)$/)[1]; const embedCode = `<div><img src="https://embed.pixiv.net/decorate.php?illust_id=${artworkId}&mode=sns-automator" width="50%"></div><br>`; const link = `<a href="${linkHref}" target="_blank">${linkText}</a>`; const artworkContainer = document.getElementById('artworkContainer'); artworkContainer.innerHTML = embedCode + link; }) .catch(error => { console.error('Error:', error); }); }); </script> _________________________________ FetchMastodon Notifications ----------------------- <b>?userid=111958546062297646&apikey=APIKEYHERE&instanceurl=https://mastodon.social</b> <br> <head> <title>Mastodon Notifications</title> <style> .notification { border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; } .notification .account { font-weight: bold; } .notification .status { margin-top: 5px; } .notification .date { font-size: 0.8em; color: #888; cursor: pointer; text-decoration: underline; } .notification.reply { background-color: lightblue; } .notification.fav { background-color: pink; } </style> </head> <body> <div id="notifications"></div> <div id="error"></div> <script> // Get the query parameters from the URL const urlParams = new URLSearchParams(window.location.search); const apiKey = urlParams.get('apikey'); const userId = urlParams.get('userid'); const instanceUrl = urlParams.get('instanceurl'); // Create a new XMLHttpRequest object const xhr = new XMLHttpRequest(); // Define the API endpoint URL const apiUrl = `${instanceUrl}/api/v1/notifications`; // Set up the request xhr.open('GET', apiUrl); xhr.setRequestHeader('Authorization', `Bearer ${apiKey}`); // Define the onload callback function xhr.onload = function() { if (xhr.status === 200) { const notifications = JSON.parse(xhr.responseText); // Display the notifications const notificationsDiv = document.getElementById('notifications'); notifications.forEach(notification => { const notificationElement = createNotificationElement(notification); notificationsDiv.appendChild(notificationElement); }); } else { const errorDiv = document.getElementById('error'); errorDiv.textContent = 'Request failed. Status: ' + xhr.status; console.error('Request failed. Status:', xhr.status); } }; // Define the onerror callback function xhr.onerror = function() { const errorDiv = document.getElementById('error'); errorDiv.textContent = 'Request failed. Please check your network connection.'; console.error('Request failed. Please check your network connection.'); }; // Send the request xhr.send(); // Helper function to create a notification element function createNotificationElement(notification) { const notificationElement = document.createElement('div'); notificationElement.classList.add('notification'); const accountElement = document.createElement('div'); accountElement.classList.add('account'); accountElement.textContent = notification.account.display_name || notification.account.username; const statusElement = document.createElement('div'); statusElement.classList.add('status'); statusElement.innerHTML = notification.status.content; const dateElement = document.createElement('div'); dateElement.classList.add('date'); const date = new Date(notification.created_at); dateElement.textContent = date.toLocaleString(); dateElement.addEventListener('click', function() { window.open(notification.status.url, '_blank'); }); // Find all links in the status and set target="_blank" const links = statusElement.getElementsByTagName('a'); for (let i = 0; i < links.length; i++) { links[i].setAttribute('target', '_blank'); } if (notification.type === 'mention') { notificationElement.classList.add('reply'); } else if (notification.type === 'favourite') { notificationElement.classList.add('fav'); } notificationElement.appendChild(accountElement); notificationElement.appendChild(statusElement); notificationElement.appendChild(dateElement); return notificationElement; } </script> </body> </html> _______________________________ Replace Text in nearby Textfield: ------------------------------------------------- <button id="replaceButton">Replace</button> <script> function replaceText() { var textField = document.getElementById("outputTextarea"); var newText = textField.value.replace(/Alcea/gi, "arusea"); textField.value = newText; } document.getElementById("replaceButton").addEventListener("click", replaceText); </script> _______________________________ Escape characters inside var string (for form safe submittal) ---------------------------------------------------------------------- const value = document.createTextNode(textarea.value).nodeValue; //no emoji support //const valueatob = btoa(value); //convert to base64 for sending via querystring (optional for other things) (source: https://alcea-wisteria.de/PHP/0demo/2024-02-18-Fake-SocialMedia/post2mtd.html#https://alceawis.de/other/extra/scripts/fakesocialmedia/post2mtd.html) ________________________________________ Mastodon querystring poster -------------------------------------------- <div id="postInfo"></div> <script> const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); const instanceurl = urlParams.get('instanceurl'); const user = urlParams.get('user'); const apikey = urlParams.get('apikey'); const encodedValue = urlParams.get('value'); const encoding = urlParams.get('encoding') || 'base64'; // Retrieve the encoding value or use 'base64' as default let decodedValue; if (encoding === 'base64') { decodedValue = atob(encodedValue); // Use base64 decoding if encoding is 'base64' } else { decodedValue = decodeURIComponent(encodedValue); // Use URI decoding for other encoding schemes } const apiUrl = `${instanceurl}`; //const apiUrl = `${instanceurl}/api/v1/statuses`; const userId = user; const apiKey = apikey; const postData = { status: decodedValue, }; const postInfoDiv = document.getElementById('postInfo'); fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}`, }, body: JSON.stringify(postData), }) .then(response => { if (!response.ok) { throw new Error('Error creating post: ' + response.status); } return response.json(); }) .then(data => { console.log('Post created successfully:', data); postInfoDiv.innerText = JSON.stringify(data); }) .catch(error => { console.error('Error creating post:', error); postInfoDiv.innerText = 'Error creating post: ' + error; }); </script> Old-Base64-only-ver: CiAgPGRpdiBpZD0icG9zdEluZm8iPjwvZGl2PgoKICA8c2NyaXB0PgogICAgY29uc3QgcXVlcnlTdHJpbmcgPSB3aW5kb3cubG9jYXRpb24uc2VhcmNoOwogICAgY29uc3QgdXJsUGFyYW1zID0gbmV3IFVSTFNlYXJjaFBhcmFtcyhxdWVyeVN0cmluZyk7CiAgICBjb25zdCBpbnN0YW5jZXVybCA9IHVybFBhcmFtcy5nZXQoJ2luc3RhbmNldXJsJyk7CiAgICBjb25zdCB1c2VyID0gdXJsUGFyYW1zLmdldCgndXNlcicpOwogICAgY29uc3QgYXBpa2V5ID0gdXJsUGFyYW1zLmdldCgnYXBpa2V5Jyk7CiAgICBjb25zdCBlbmNvZGVkVmFsdWUgPSB1cmxQYXJhbXMuZ2V0KCd2YWx1ZScpOwogICAgY29uc3QgZGVjb2RlZFZhbHVlID0gYXRvYihlbmNvZGVkVmFsdWUpOwogICAgY29uc3QgYXBpVXJsID0gYCR7aW5zdGFuY2V1cmx9YDsKICAgIC8vY29uc3QgYXBpVXJsID0gYCR7aW5zdGFuY2V1cmx9L2FwaS92MS9zdGF0dXNlc2A7CiAgICBjb25zdCB1c2VySWQgPSB1c2VyOwogICAgY29uc3QgYXBpS2V5ID0gYXBpa2V5OwogICAgY29uc3QgcG9zdERhdGEgPSB7CiAgICAgIHN0YXR1czogZGVjb2RlZFZhbHVlLAogICAgfTsKCiAgICBmZXRjaChhcGlVcmwsIHsKICAgICAgbWV0aG9kOiAnUE9TVCcsCiAgICAgIGhlYWRlcnM6IHsKICAgICAgICAnQ29udGVudC1UeXBlJzogJ2FwcGxpY2F0aW9uL2pzb24nLAogICAgICAgICdBdXRob3JpemF0aW9uJzogYEJlYXJlciAke2FwaUtleX1gLAogICAgICB9LAogICAgICBib2R5OiBKU09OLnN0cmluZ2lmeShwb3N0RGF0YSksCiAgICB9KQogICAgICAudGhlbihyZXNwb25zZSA9PiByZXNwb25zZS5qc29uKCkpCiAgICAgIC50aGVuKGRhdGEgPT4gewogICAgICAgIGNvbnNvbGUubG9nKCdQb3N0IGNyZWF0ZWQgc3VjY2Vzc2Z1bGx5OicsIGRhdGEpOwogICAgICAgIGNvbnN0IHBvc3RJbmZvRGl2ID0gZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoJ3Bvc3RJbmZvJyk7CiAgICAgICAgcG9zdEluZm9EaXYuaW5uZXJUZXh0ID0gSlNPTi5zdHJpbmdpZnkoZGF0YSk7CiAgICAgIH0pCiAgICAgIC5jYXRjaChlcnJvciA9PiB7CiAgICAgICAgY29uc29sZS5lcnJvcignRXJyb3IgY3JlYXRpbmcgcG9zdDonLCBlcnJvcik7CiAgICAgIH0pOwogIDwvc2NyaXB0Pg== ____________________________ Hide img based on texinput keyword: -------------------------- <style>.hidden-image {display: none;}</style> <input type="text" id="imageKeyword" placeholder="Enter image keyword"> <script> document.addEventListener("DOMContentLoaded", function() { // Get all the images on the page var images = document.getElementsByTagName("img"); function handleKeywordChange() { var keyword = document.getElementById('imageKeyword').value.toLowerCase(); for (var i = 0; i < images.length; i++) { var img = images[i]; var imgUrl = img.getAttribute("src"); if (imgUrl && imgUrl.toLowerCase().includes(keyword)) { img.classList.remove("hidden-image"); } else { img.classList.add("hidden-image"); } } } document.getElementById('imageKeyword').addEventListener('input', handleKeywordChange); handleKeywordChange(); }); </script> _________________________ Empty fake img placeholder (var size) image ------------------------------------------- <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+Ph4DwADCAH6LH6x7QAAAABJRU5ErkJggg==" alt="Empty PNG" width=45px> ___________________________ Invisible details spoiler triggered with href ------------------------------------- <a href="javascript:var spoiler = document.getElementById('pastplaying'); spoiler.open = !spoiler.open;">LastPlaying</a> <details id="pastplaying"> <summary style="display: none;"></summary> <div class="custom-summary" onclick="toggleDetails()"></div> <div class="dropdown-content"> •<a target="_blank" href="https://codepen.io/ryedai1/full/ZEPMqZB" style=color:blue>AntenneBayern</a> •<a target="_blank" href="https://codepen.io/ryedai1/full/ZEPMqZB?baseurl=https://myonlineradio.de/bigfm/playlist?date=" style=color:blue>BigFM</a> </details><br> ______________________________________________________ Enable disabledElement with unobstr \ hidden from plainsight link ---------------------- Add ALLOW SOURCE VIEW <a href="javascript:void(0);" style="text-decoration: none;color: black;" onclick="document.getElementById('Save').disabled = false;">snippet</a> <br> <input type="submit" id=Save value="Save" disabled> ______________________________________________________ AES Crypt (HTMLCRYPT) light: ------------ <title>Encryption Tool</title> <script> function stringToArrayBuffer(str) { var encoder = new TextEncoder(); return encoder.encode(str); } function arrayBufferToString(buffer) { var decoder = new TextDecoder(); return decoder.decode(buffer); } async function generateAESKey() { var key = await crypto.subtle.generateKey( { name: "AES-CBC", length: 256 }, true, ["encrypt", "decrypt"] ); return key; } async function encryptAES(data, key) { var iv = crypto.getRandomValues(new Uint8Array(16)); var encrypted = await crypto.subtle.encrypt( { name: "AES-CBC", iv: iv }, key, data ); return { iv: iv, ciphertext: new Uint8Array(encrypted) }; } async function decryptAES(ciphertext, key, iv) { var decrypted = await crypto.subtle.decrypt( { name: "AES-CBC", iv: iv }, key, ciphertext ); return new Uint8Array(decrypted); } async function handleSubmit(event) { event.preventDefault(); var password = document.getElementById("password").value; var htmlText = document.getElementById("htmlText").value; var passwordBuffer = stringToArrayBuffer(password); var keyMaterial = await crypto.subtle.importKey( "raw", passwordBuffer, { name: "PBKDF2" }, false, ["deriveKey"] ); var aesKey = await crypto.subtle.deriveKey( { name: "PBKDF2", salt: new Uint8Array(16), // Use a random salt iterations: 100000, hash: "SHA-256" }, keyMaterial, { name: "AES-CBC", length: 256 }, true, ["encrypt", "decrypt"] ); var htmlBuffer = stringToArrayBuffer(htmlText); var encryptedData = await encryptAES(htmlBuffer, aesKey); var ivHex = Array.prototype.map .call(encryptedData.iv, (x) => ("00" + x.toString(16)).slice(-2)) .join(""); var ciphertextHex = Array.prototype.map .call(encryptedData.ciphertext, (x) => ("00" + x.toString(16)).slice(-2)) .join(""); var encryptedOutput = ivHex + ciphertextHex; document.getElementById("encryptedOutput").textContent = encryptedOutput; // Calculate SHA-256 hash of the encrypted output var encoder = new TextEncoder(); var data = encoder.encode(encryptedOutput); var hashBuffer = await crypto.subtle.digest("SHA-256", data); var hashArray = Array.from(new Uint8Array(hashBuffer)); var hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join(""); document.getElementById("sha256Output").textContent = hashHex; } async function handleDecrypt(event) { event.preventDefault(); var password = document.getElementById("password").value; var encryptedHex = document.getElementById("encryptedOutput").textContent; var passwordBuffer = stringToArrayBuffer(password); var keyMaterial = await crypto.subtle.importKey( "raw", passwordBuffer, { name: "PBKDF2" }, false, ["deriveKey"] ); var aesKey = await crypto.subtle.deriveKey( { name: "PBKDF2", salt: new Uint8Array(16), // Use a random salt for real-world scenarios iterations: 100000, hash: "SHA-256" }, keyMaterial, { name: "AES-CBC", length: 256 }, true, ["encrypt", "decrypt"] ); var ivHex = encryptedHex.substr(0, 32); var ciphertextHex = encryptedHex.substr(32); var ivBytes = new Uint8Array(ivHex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); var ciphertextBytes = new Uint8Array(ciphertextHex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); var decryptedBytes = await decryptAES(ciphertextBytes, aesKey, ivBytes); var decryptedHTML = arrayBufferToString(decryptedBytes); document.getElementById("decryptedOutput").innerHTML = decryptedHTML; } </script> </head> <body> <h1>Encryption Tool</h1> <form onsubmit="handleSubmit(event)"> <label for="password">Password:</label> <input type="password" id="password" required> <br> <label for="htmlText">HTML Text:</label> <br> <textarea id="htmlText" rows="10" cols="50"></textarea> <br> <input type="submit" value="Encrypt"> </form> <div> <h3>Encrypted Output:</h3> <textarea id="encryptedOutput" rows="10" cols="50"></textarea> </div> <div> <details><summary>Sha</summary><h3>SHA-256 Output:</h3> <textarea id="sha256Output"></textarea></details> </div> <form onsubmit="handleDecrypt(event)"> <!--<h3>Decryptiona</h3> <input type="submit" value="Decrypt"> </form> <div> <h3>Decrypted Output:</h3> <textarea id="decryptedOutput"></textarea> </div>--> <hr> <!DOCTYPE html> <html> <head> <title>Decryption Tool</title> You need to trigger encrypt first <script> function stringToArrayBuffer(str) { var encoder = new TextEncoder(); return encoder.encode(str); } function arrayBufferToString(buffer) { var decoder = new TextDecoder(); return decoder.decode(buffer); } async function decryptAES(ciphertext, key, iv) { var decrypted = await crypto.subtle.decrypt( { name: "AES-CBC", iv: iv }, key, ciphertext ); return new Uint8Array(decrypted); } async function handleDecrypt(event) { event.preventDefault(); var password = document.getElementById("password").value; var encryptedHex = document.getElementById("encryptedOutput").value; var passwordBuffer = stringToArrayBuffer(password); var keyMaterial = await crypto.subtle.importKey( "raw", passwordBuffer, { name: "PBKDF2" }, false, ["deriveKey"] ); var aesKey = await crypto.subtle.deriveKey( { name: "PBKDF2", salt: new Uint8Array(16), // Use a random salt for real-world scenarios iterations: 100000, hash: "SHA-256" }, keyMaterial, { name: "AES-CBC", length: 256 }, true, ["encrypt", "decrypt"] ); var ivHex = encryptedHex.substr(0, 32); var ciphertextHex = encryptedHex.substr(32); var ivBytes = new Uint8Array(ivHex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); var ciphertextBytes = new Uint8Array(ciphertextHex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); var decryptedBytes = await decryptAES(ciphertextBytes, aesKey, ivBytes); var decryptedHTML = arrayBufferToString(decryptedBytes); document.getElementById("decryptedOutput").innerText = decryptedHTML; } </script> <h1>Decrypt</h1> <script> function stringToArrayBuffer2(str) { var encoder = new TextEncoder(); return encoder.encode(str); } function arrayBufferToString2(buffer) { var decoder = new TextDecoder(); return decoder.decode(buffer); } async function decryptAES2(ciphertext, key, iv) { var decrypted = await crypto.subtle.decrypt( { name: "AES-CBC", iv: iv, }, key, ciphertext ); return new Uint8Array(decrypted); } async function handleDecrypt2(event) { event.preventDefault(); var password = document.getElementById("password").value; var encryptedHex = document.getElementById("encryptedOutput").value; var passwordBuffer = stringToArrayBuffer2(password); var keyMaterial = await crypto.subtle.importKey( "raw", passwordBuffer, { name: "PBKDF2" }, false, ["deriveKey"] ); var aesKey = await crypto.subtle.deriveKey( { name: "PBKDF2", salt: new Uint8Array(16), // Use a random salt for real-world scenarios iterations: 100000, hash: "SHA-256", }, keyMaterial, { name: "AES-CBC", length: 256 }, true, ["encrypt", "decrypt"] ); var ivHex = encryptedHex.substr(0, 32); var ciphertextHex = encryptedHex.substr(32); var ivBytes = new Uint8Array( ivHex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)) ); var ciphertextBytes = new Uint8Array( ciphertextHex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)) ); var decryptedBytes = await decryptAES2(ciphertextBytes, aesKey, ivBytes); var decryptedHTML = arrayBufferToString2(decryptedBytes); document.getElementById("decryptedOutput").innerHTML = decryptedHTML; } </script> <form onsubmit="handleDecrypt2(event)"> <input type="password" id="password" required> <input type="submit" value="Decrypt"> </form> <div> <div id="decryptedOutput"></div> </div> <hr><hr><br> DEcryptionBoilerplate<br> <plaintext> <script> function stringToArrayBuffer(str) { var encoder = new TextEncoder(); return encoder.encode(str); } function arrayBufferToString(buffer) { var decoder = new TextDecoder(); return decoder.decode(buffer); } async function decryptAES(ciphertext, key, iv) { var decrypted = await crypto.subtle.decrypt( { name: "AES-CBC", iv: iv }, key, ciphertext ); return new Uint8Array(decrypted); } async function handleDecrypt(event) { event.preventDefault(); var password = document.getElementById("password").value; var encryptedHex = document.getElementById("encryptedOutput").value; var passwordBuffer = stringToArrayBuffer(password); var keyMaterial = await crypto.subtle.importKey( "raw", passwordBuffer, { name: "PBKDF2" }, false, ["deriveKey"] ); var aesKey = await crypto.subtle.deriveKey( { name: "PBKDF2", salt: new Uint8Array(16), // Use a random salt for real-world scenarios iterations: 100000, hash: "SHA-256" }, keyMaterial, { name: "AES-CBC", length: 256 }, true, ["encrypt", "decrypt"] ); var ivHex = encryptedHex.substr(0, 32); var ciphertextHex = encryptedHex.substr(32); var ivBytes = new Uint8Array(ivHex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); var ciphertextBytes = new Uint8Array(ciphertextHex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16))); var decryptedBytes = await decryptAES(ciphertextBytes, aesKey, ivBytes); var decryptedHTML = arrayBufferToString(decryptedBytes); document.getElementById("decryptedOutput").innerHTML = decryptedHTML; } </script> <form onsubmit="handleDecrypt(event)"> <input type="password" id="password" required> <textarea id="encryptedOutput" rows="10" cols="50" style="display: none;">3a89c921bc7d3a731fa1b499823724084e388e770e8f2099ad179ef843c99cabd27e52077aa5b7875f790e6a3af6496e4149d436ac6424c10ccc2b8b78383e78 </textarea> <input type="submit" value="Decrypt"> </form><div><div id="decryptedOutput"></div></div> _______________ Iframe with cachebusting reload button: -------------------------------------- <button onclick="addCacheBustingParameter()" style="background:gray; border:transparent;">ReMeet</button><br><br> <iframe id="friends" src="https://alceawis.de/other/extra/personal/friends/friends.html " style="border:0px #ffffff none;" name="statusit" scrolling="no" frameborder="0" marginheight="0px" marginwidth="0px" height=100% width="900" allowfullscreen></iframe> <script> function addCacheBustingParameter() { var iframe = document.getElementById('friends'); var iframeSrc = iframe.src; iframe.src = iframeSrc + '?cache=' + Date.now(); } </script> _________________________________ Open mastodon url in home instance: ------------------------------ <a href="?search=https://sunny.garden/@Iva852/109293246960188756&pbUrl=https://pb.todon.de&apikey=apikey">test</a><br> <!DOCTYPE html> <html> <head> <title>API Key Form</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <!-- HTML form to input the API key, pbUrl, and URL --> <form id="apiForm"> <label for="apikey">API Key:</label> <input type="text" id="apikey" name="apikey" required> <br> <label for="pbUrl">pbUrl:</label> <input type="text" id="pbUrl" name="pbUrl" required> <br> <label for="url">URL:</label> <input type="text" id="url" name="url" pattern="https://.*" required> <input type="submit" value="Submit"> <input type="button" value="Clear" id="clearButton"> </form> <!-- Result container --> <div id="result"></div> <script> $(document).ready(function() { // Function to get query string parameter value by name function getQueryStringParam(name) { const urlParams = new URLSearchParams(window.location.search); return urlParams.get(name); } // Function to populate textboxes from query string values function populateTextboxesFromQueryString() { const apiKeyParam = getQueryStringParam('apikey'); const pbUrlParam = getQueryStringParam('pbUrl'); const urlParam = getQueryStringParam('search'); $('#apikey').val(apiKeyParam); $('#pbUrl').val(pbUrlParam); $('#url').val(urlParam); } // Call the function to populate textboxes on page load populateTextboxesFromQueryString(); // Check if ampersand is present in the URL bar const urlBarValue = window.location.href; if (urlBarValue.includes('&')) { // Retrieve form values const apiKey = $('#apikey').val(); const pbUrl = $('#pbUrl').val(); const search = $('#url').val(); // Perform AJAX request performAjaxRequest(apiKey, pbUrl, search); } // Perform AJAX request function performAjaxRequest(apiKey, pbUrl, search) { var url = pbUrl + "/api/v2/search/?q=" + encodeURIComponent(search) + "&limit=1&resolve=true"; // Disable form elements $("#apikey").prop("disabled", true); $("#pbUrl").prop("disabled", true); $("#url").prop("disabled", true); $("#submit").prop("disabled", true); // Perform AJAX request $.ajax({ url: url, headers: { "Authorization": "Bearer " + apiKey }, success: function(response) { if (response.statuses && response.statuses.length > 0 && response.statuses[0].id) { var id = response.statuses[0].id; // Extract username and domain from the URL var urlParts = parseURL(search); var pathParts = urlParts.pathname.split("/").filter(function(part) { return part !== ""; }); var username = pathParts[0]; var domain = urlParts.hostname; // Construct the new URL var newUrl = pbUrl + "/" + username + "@" + domain + "/" + id; // Output the new URL $("#result").html("New URL: <a id='newUrlLink' href='" + newUrl + "'>" + newUrl + "</a>"); // Automatically open the new URL in a new tab $("#newUrlLink")[0].click(); } else { $("#result").html("Please enter a URL<br>cURL Result: " + JSON.stringify(response) + "<br>" + url + "<br><a target='_blank' href='https://codepen.io/ryedai1/full/WNYZBya'>Lookup</a>"); } }, error: function(xhr, status, error) { $("#result").html("Error: " + error); }, complete: function() { // Re-enable form elements $("#apikey").prop("disabled", false); $("#pbUrl").prop("disabled", false); $("#url").prop("disabled", false); $("#submit").prop("disabled", false); } }); } // Helper function to parse URL function parseURL(url) { var parser = document.createElement("a"); parser.href = url; return parser; } // Submit form event handler $("#apiForm").submit(function(event) { event.preventDefault(); // Prevent default form submission // Retrieve form values var apiKey = $("#apikey").val(); var pbUrl = $("#pbUrl").val(); var search = $("#url").val(); // Perform AJAX request performAjaxRequest(apiKey, pbUrl, search); }); // Clear button event handler $("#clearButton").click(function() { // Clear input values $("#apikey").val(""); $("#pbUrl").val(""); $("#url").val(""); // Clear result container $("#result").html(""); }); }); </script> </body> </html> _____________________________ Fetch popular mastodon posts -------------------------- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style> .container { display: flex; } .post-box { border: 1px solid #ccc; padding: 10px; margin-right: 10px; display: flex; align-items: center; width: 500px; height: 250px; } .post-avatar { width: 80px; height: 80px; margin-right: 10px; border-radius: 50%; object-fit: cover; } .post-content { font-size: 14px; margin-bottom: 5px; overflow: hidden; text-overflow: ellipsis; max-height: 200px; max-width: 100%; white-space: normal; } .post-link { font-size: 12px; color: blue; } </style> <div class="container"></div> <script> $(document).ready(function() { var instances = ['kopimi.space', 'phpc.social', 'urusai.social', 'mastodon.social']; var totalPostsPerInstance = 10; var container = $('.container'); instances.forEach(function(instance) { var apiUrl = 'https://' + instance + '/api/v1/timelines/public'; var params = { 'local': true, 'only_media': false, 'limit': totalPostsPerInstance, 'max_id': null }; var sortedPosts = []; while (sortedPosts.length < totalPostsPerInstance) { var queryString = $.param(params); var requestUrl = apiUrl + '?' + queryString; $.ajax({ url: requestUrl, async: false, dataType: 'json', success: function(response) { var posts = response; if (posts) { posts.forEach(function(post) { var content = post.content; var favouritesCount = post.favourites_count; var boostsCount = post.reblogs_count; var url = post.url; if (!post.account.bot) { if (favouritesCount >= 2 || boostsCount >= 2) { var replyCount = post.replies_count; sortedPosts.push({ 'content': content, 'favouritesCount': favouritesCount, 'boostsCount': boostsCount, 'replyCount': replyCount, 'url': url, 'avatar': post.account.avatar_static }); } } if (sortedPosts.length >= totalPostsPerInstance) { return false; } }); } else { console.error('Error retrieving posts from ' + instance + '.'); return false; } var lastPost = posts[posts.length - 1]; params.max_id = lastPost.id; }, error: function() { console.error('Error retrieving posts from ' + instance + '.'); return false; } }); } sortedPosts.sort(function(a, b) { var aCount = Math.max(a.favouritesCount, a.boostsCount); var bCount = Math.max(b.favouritesCount, b.boostsCount); return bCount - aCount; }); sortedPosts.forEach(function(post) { var content = post.content; var favouritesCount = post.favouritesCount; var boostsCount = post.boostsCount; var replyCount = post.replyCount; var postUrl = post.url; var avatarUrl = post.avatar; var postBox = $('<div class="post-box"></div>'); var postAvatar = $('<img class="post-avatar" src="' + avatarUrl + '" alt="User Avatar"><br>'); var postContent = $('<div class="post-content">' + content + '</div>'); var counts = $('<div class="counts"></div>'); var favouritesSpan = $('<span>F: ' + favouritesCount + '</span><br>'); var boostsSpan = $('<span>B: ' + boostsCount + '</span><br>'); var repliesSpan = $('<span>R: ' + replyCount + '</span><br>'); var postLink = $('<div class="post-link"><a target="_blank" href="' + postUrl + '">View Post</a></div>'); counts.append(favouritesSpan, boostsSpan, repliesSpan); postBox.append(postAvatar, postContent, counts, postLink); container.append(postBox); }); }); }); </script> __________________________________________ Mastodon Instance Cycle: -------------------------------------------- <input type="checkbox" id="cycleCheckbox" onchange="toggleCycle()" /> <script> let canFire = true; let intervalId; function toggleCycle() { const checkbox = document.getElementById('cycleCheckbox'); if (checkbox.checked) { // Start the cycle intervalId = setInterval(() => { if (!canFire) return; const elements = [...document.querySelectorAll('#mtdlink')]; if (elements.length > 0) { const randomIndex = Math.floor(Math.random() * elements.length); elements[randomIndex].click(); } canFire = false; setTimeout(() => { canFire = true; }, 20000); }, 1000); } else { // Stop the cycle clearInterval(intervalId); } } </script> <!--renderer--> •<a href="#" onclick="changeEndpoint('https://mastodon.social')" id="mtdlink">mastodon.social</a> •<a href="#" onclick="changeEndpoint('https://urusai.social')" id="mtdlink">urusai.social</a> •<a href="#" onclick="changeEndpoint('https://phpc.social')" id="mtdlink">phpc.social</a> •<a href="#" onclick="changeEndpoint('https://pb.todon.de')"id="mtdlink">pb.todon.de</a> •<a href="#" onclick="changeEndpoint('https://kopimi.space')" id="mtdlink">kopimi.space</a> <div id="container"><div id="instance-data" class="example"></div></div> <style> #container { background-size: cover; background-position: center; background-repeat: no-repeat; } #instance-data { color: black; text-shadow: 2px 2px 8px #ffffff; //} @keyframes colorCycle { 0% { color: #7f00ff; text-shadow: 2px 2px 4px #7f00ff; } 50% { color: transparent; } 100% { color: #7f00ff; text-shadow: 2px 2px 4px #7f00ff; } } .example { animation: colorCycle 18s infinite; } </style> </head> <body onload="fetchInstanceData('https://urusai.social')"> <script> function fetchInstanceData(endpoint) { const url = `${endpoint}/api/v1/instance`; const instanceDataElement = document.getElementById('instance-data'); const containerElement = document.getElementById('container'); fetch(url) .then(response => response.json()) .then(instanceData => { // Extract specific fields const uri = instanceData.uri; const title = instanceData.title; const shortDescription = instanceData.short_description; const description = instanceData.description; const userCount = instanceData.stats.user_count; const statusCount = instanceData.stats.status_count; const domainCount = instanceData.stats.domain_count; const streamingApiUrl = instanceData.urls.streaming_api; const thumbnail = instanceData.thumbnail; const email = instanceData.email; const registrations = instanceData.registrations; instanceDataElement.innerHTML = ` <b><a target="_blank" href="https://${uri}" style="color: pink">${uri}</a></b><br> ${title} (${email})<br> •${shortDescription}<br> <hr>${description}<hr> <b>UserCount:</b> ${userCount} Statuses: ${statusCount} <b>Domains:</b> ${domainCount} <b>Registration possible:</b> <u>${registrations}</u><br>- `; containerElement.style.backgroundImage = `url(${thumbnail})`; }) } function changeEndpoint(endpoint) { fetchInstanceData(endpoint); } </script> </body> </html> ____________________________ Display code text file with -&_ delims orderly: ------------------------------------------------- <script> window.addEventListener("DOMContentLoaded", () => { const url = document.getElementById("dropdownMenu").value; changeDropdownSelection(url); }); </script> <head> <style> .extracted{margin-bottom:10px}.title{background-color:#f1f1f1;padding:10px;cursor:pointer;font-weight:700}.content{display:none;padding:10px;background-color:#fff;position:relative}.content.show{display:block}.copy-button{position:absolute;top:5px;right:5px;padding:5px 10px;border:none;background-color:#ddd;cursor:pointer} </style> </head> <body> <div class="dropdown"> <select id="dropdownMenu" onchange="changeDropdownSelection()"> <option value="/other/Computerstuff/Commands/Autohotkey/Commands.txt">Autohotkey</option> <option value="/other/Computerstuff/Commands/Android-Keyevents.txt">AndroidKeyevents</option> <option value="/other/Computerstuff/Commands/DOS/Commands.txt">DOS</option> <option value="/other/Computerstuff/Commands/FFMPEG_Commands.txt">FFMPEG</option> <option value="/other/Computerstuff/Commands/Commands_ImageMagick.txt">Imagemagick</option> <option value="/other/Computerstuff/Commands/Sox_CMDS.txt">Sox</option> <option value="/other/Computerstuff/Commands/HTML_Codes.txt">HTML</option> <option value="/other/Computerstuff/Commands/PHP.txt">PHP</option> <option value="/other/Computerstuff/Commands/Python.txt">Python</option> </select> </div> <div id="output"></div> <script> function toggleContent(titleElement) { const contentElement = titleElement.nextElementSibling; contentElement.classList.toggle("show"); } function copyContent(contentElement) { const text = contentElement.innerText.trim(); navigator.clipboard.writeText(text) .then(() => { console.log('Content copied to clipboard:', text); }) .catch((error) => { console.error('Failed to copy content to clipboard:', error); }); } function changeDropdownSelection() { const dropdown = document.getElementById('dropdownMenu'); const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); const fileTextParam = urlParams.get('filetext'); if (fileTextParam !== null) { dropdown.value = fileTextParam; } const selectedValue = dropdown.value; fetch(selectedValue) .then((response) => response.text()) .then((data) => { const container = document.getElementById('output'); container.innerHTML = ''; const lines = data.split('\n'); const filteredLines = []; for (let i = 0; i < lines.length; i++) { if (lines[i].includes('----- ----')) { //remove space to make work if (i > 0) { filteredLines.push(lines[i - 1]); } } } const contentLines = data.split(/------ ---+/); //remove space to make work console.log("Change data.split(/------ ---+/ to (/----"); contentLines.shift(); filteredLines.forEach((line, index) => { const extractedElement = document.createElement("div"); extractedElement.className = "extracted"; const titleElement = document.createElement("div"); titleElement.className = "title"; titleElement.innerText = line; titleElement.addEventListener("click", () => toggleContent(titleElement)); extractedElement.appendChild(titleElement); const contentElement = document.createElement("div"); contentElement.className = "content"; contentElement.innerText = contentLines[index].trim(); extractedElement.appendChild(contentElement); const copyButton = document.createElement("button"); copyButton.innerText = "Copy"; copyButton.className = "copy-button"; copyButton.addEventListener("click", () => copyContent(contentElement)); contentElement.appendChild(copyButton); container.appendChild(extractedElement); }); }) .catch((error) => { console.error(error); }); } </script> ====CodeDisplayVer=== PCFET0NUWVBFIGh0bWw+CjxodG1sPgo8aGVhZD4KICA8c3R5bGU+CiAgICAuZXh0cmFjdGVkLWNvbnRlbnQgewogICAgICBtYXJnaW4tYm90dG9tOiAxMHB4OwogICAgICBwYWRkaW5nOiA1cHg7CiAgICAgIGJvcmRlcjogMXB4IHNvbGlkICNjY2M7CiAgICAgIGJhY2tncm91bmQtY29sb3I6ICNmOWY5Zjk7CiAgICB9CgogICAgLnRpdGxlIHsKICAgICAgZm9udC13ZWlnaHQ6IDcwMDsKICAgICAgYmFja2dyb3VuZC1jb2xvcjogI2NjYzsKICAgICAgcGFkZGluZzogNXB4OwogICAgICBtYXJnaW4tYm90dG9tOiA1cHg7CiAgICAgIGN1cnNvcjogcG9pbnRlcjsKICAgIH0KCiAgICAuY29udGVudCB7CiAgICAgIGRpc3BsYXk6IG5vbmU7CiAgICAgIHBhZGRpbmc6IDVweDsKICAgIH0KCiAgICAuY29udGVudC5zaG93IHsKICAgICAgZGlzcGxheTogYmxvY2s7CiAgICB9CgogICAgLmRyb3Bkb3duIHsKICAgICAgcG9zaXRpb246IHJlbGF0aXZlOwogICAgICBkaXNwbGF5OiBpbmxpbmUtYmxvY2s7CiAgICB9CgogICAgLmRyb3Bkb3duLWNvbnRlbnQgewogICAgICBkaXNwbGF5OiBub25lOwogICAgICBwb3NpdGlvbjogYWJzb2x1dGU7CiAgICAgIGJhY2tncm91bmQtY29sb3I6ICNmOWY5Zjk7CiAgICAgIG1pbi13aWR0aDogMTYwcHg7CiAgICAgIGJveC1zaGFkb3c6IDBweCA4cHggMTZweCAwcHggcmdiYSgwLCAwLCAwLCAwLjIpOwogICAgICB6LWluZGV4OiAxOwogICAgfQoKICAgIC5kcm9wZG93bjpob3ZlciAuZHJvcGRvd24tY29udGVudCB7CiAgICAgIGRpc3BsYXk6IGJsb2NrOwogICAgfQogIDwvc3R5bGU+CiAgPHNjcmlwdD4KICAgIGZ1bmN0aW9uIHRvZ2dsZUNvbnRlbnQoZWxlbWVudCkgewogICAgICBjb25zdCBjb250ZW50RWxlbWVudCA9IGVsZW1lbnQubmV4dEVsZW1lbnRTaWJsaW5nOwogICAgICBjb250ZW50RWxlbWVudC5jbGFzc0xpc3QudG9nZ2xlKCJzaG93Iik7CiAgICB9CgogICAgZnVuY3Rpb24gcGFyc2VDb250ZW50KGRhdGEsIHRpdGxlcykgewogICAgICBjb25zdCBwYXR0ZXJuID0gLy0tLS0tLSguKj8pX19fX18vZ3M7CiAgICAgIGNvbnN0IG1hdGNoZXMgPSBbLi4uZGF0YS5tYXRjaEFsbChwYXR0ZXJuKV07CiAgICAgIGNvbnN0IG91dHB1dENvbnRhaW5lciA9IGRvY3VtZW50LmdldEVsZW1lbnRCeUlkKCJvdXRwdXQiKTsKICAgICAgb3V0cHV0Q29udGFpbmVyLmlubmVySFRNTCA9ICIiOwogICAgICBmb3IgKGxldCBpID0gMDsgaSA8IG1hdGNoZXMubGVuZ3RoOyBpKyspIHsKICAgICAgICBjb25zdCBtYXRjaCA9IG1hdGNoZXNbaV07CiAgICAgICAgY29uc3QgZXh0cmFjdGVkQ29udGVudCA9IG1hdGNoWzFdLnRyaW0oKTsgLy8gVHJpbSBhbnkgbGVhZGluZy90cmFpbGluZyB3aGl0ZXNwYWNlCiAgICAgICAgY29uc3QgZXh0cmFjdGVkRWxlbWVudCA9IGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoImRpdiIpOwogICAgICAgIGV4dHJhY3RlZEVsZW1lbnQuY2xhc3NOYW1lID0gImV4dHJhY3RlZC1jb250ZW50IjsKICAgICAgICBjb25zdCB0aXRsZUVsZW1lbnQgPSBkb2N1bWVudC5jcmVhdGVFbGVtZW50KCJkaXYiKTsKICAgICAgICB0aXRsZUVsZW1lbnQuY2xhc3NOYW1lID0gInRpdGxlIjsKICAgICAgICB0aXRsZUVsZW1lbnQuaW5uZXJUZXh0ID0gdGl0bGVzW2ldOwogICAgICAgIHRpdGxlRWxlbWVudC5hZGRFdmVudExpc3RlbmVyKCJjbGljayIsICgpID0+IHRvZ2dsZUNvbnRlbnQodGl0bGVFbGVtZW50KSk7CiAgICAgICAgZXh0cmFjdGVkRWxlbWVudC5hcHBlbmRDaGlsZCh0aXRsZUVsZW1lbnQpOwogICAgICAgIGNvbnN0IGNvbnRlbnRFbGVtZW50ID0gZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgiZGl2Iik7CiAgICAgICAgY29udGVudEVsZW1lbnQuY2xhc3NOYW1lID0gImNvbnRlbnQiOwogICAgICAgIGNvbnRlbnRFbGVtZW50LmlubmVyVGV4dCA9IGV4dHJhY3RlZENvbnRlbnQ7CiAgICAgICAgZXh0cmFjdGVkRWxlbWVudC5hcHBlbmRDaGlsZChjb250ZW50RWxlbWVudCk7CiAgICAgICAgb3V0cHV0Q29udGFpbmVyLmFwcGVuZENoaWxkKGV4dHJhY3RlZEVsZW1lbnQpOwogICAgICB9CiAgICB9CgogICAgYXN5bmMgZnVuY3Rpb24gZmV0Y2hBbmRQYXJzZSh1cmwpIHsKICAgICAgdHJ5IHsKICAgICAgICBjb25zdCByZXNwb25zZSA9IGF3YWl0IGZldGNoKHVybCk7CiAgICAgICAgaWYgKCFyZXNwb25zZS5vaykgewogICAgICAgICAgdGhyb3cgbmV3IEVycm9yKCJOZXR3b3JrIHJlc3BvbnNlIHdhcyBub3Qgb2siKTsKICAgICAgICB9CiAgICAgICAgY29uc3QgZGF0YSA9IGF3YWl0IHJlc3BvbnNlLnRleHQoKTsKICAgICAgICBjb25zdCBsaW5lcyA9IGRhdGEuc3BsaXQoIlxuIik7CiAgICAgICAgY29uc3QgZmlsdGVyZWRMaW5lcyA9IFtdOwogICAgICAgIGZvciAobGV0IGkgPSAwOyBpIDwgbGluZXMubGVuZ3RoOyBpKyspIHsKICAgICAgICAgIGlmIChsaW5lc1tpXS5pbmNsdWRlcygiLS0tLS0tLS0tIikpIHsKICAgICAgICAgICAgaWYgKGkgPiAwKSB7CiAgICAgICAgICAgICAgZmlsdGVyZWRMaW5lcy5wdXNoKGxpbmVzW2kgLSAxXSk7CiAgICAgICAgICAgIH0KICAgICAgICAgIH0KICAgICAgICB9CiAgICAgICAgcGFyc2VDb250ZW50KGRhdGEsIGZpbHRlcmVkTGluZXMpOwogICAgICB9IGNhdGNoIChlcnJvcikgewogICAgICAgIGNvbnNvbGUuZXJyb3IoZXJyb3IpOwogICAgICB9CiAgICB9CgogICAgZnVuY3Rpb24gY2hhbmdlRHJvcGRvd25TZWxlY3Rpb24oKSB7CiAgICAgIGNvbnN0IGRyb3Bkb3duID0gZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoImRyb3Bkb3duTWVudSIpOwogICAgICBjb25zdCBzZWxlY3RlZE9wdGlvbiA9IGRyb3Bkb3duLm9wdGlvbnNbZHJvcGRvd24uc2VsZWN0ZWRJbmRleF07CiAgICAgIGNvbnN0IHVybCA9IHNlbGVjdGVkT3B0aW9uLnZhbHVlOwogICAgICBmZXRjaEFuZFBhcnNlKHVybCk7CiAgICB9CiAgPC9zY3JpcHQ+CjwvaGVhZD4KPGJvZHk+CiAgPGRpdiBjbGFzcz0iZHJvcGRvd24iPgogICAgPHNlbGVjdCBpZD0iZHJvcGRvd25NZW51IiBvbmNoYW5nZT0iY2hhbmdlRHJvcGRvd25TZWxlY3Rpb24oKSI+CiAgICAgIDxvcHRpb24gdmFsdWU9Im90aGVyL0NvbXB1dGVyc3R1ZmYvQ29tbWFuZHMvQXV0b2hvdGtleS9Db21tYW5kcy50eHQiPkF1dG9ob3RrZXk8L29wdGlvbj4KICAgICAgPG9wdGlvbiB2YWx1ZT0ib3RoZXIvQ29tcHV0ZXJzdHVmZi9Db21tYW5kcy9ET1MvQ29tbWFuZHMudHh0Ij5ET1M8L29wdGlvbj4KICAgICAgPG9wdGlvbiB2YWx1ZT0ib3RoZXIvQ29tcHV0ZXJzdHVmZi9Db21tYW5kcy9GRk1QRUclMjBDb21tYW5kcy50eHQiPkZGTVBFRzwvb3B0aW9uPgogICAgICA8b3B0aW9uIHZhbHVlPSJvdGhlci9Db21wdXRlcnN0dWZmL0NvbW1hbmRzL0NvbW1hbmRzX0ltYWdlTWFnaWNrLnR4dCI+SW1hZ2VtYWdpY2s8L29wdGlvbj4KICAgICAgPG9wdGlvbiB2YWx1ZT0ib3RoZXIvQ29tcHV0ZXJzdHVmZi9Db21tYW5kcy9Tb3hfQ01EUy50eHQiPlNveDwvb3B0aW9uPgogICAgICA8b3B0aW9uIHZhbHVlPSJvdGhlci9Db21wdXRlcnN0dWZmL0NvbW1hbmRzL0hUTUxfQ29kZXMudHh0Ij5IVE1MPC9vcHRpb24+CiAgICAgIDxvcHRpb24gdmFsdWU9Im90aGVyL0NvbXB1dGVyc3R1ZmYvQ29tbWFuZHMvUEhQLnR4dCI+UEhQPC9vcHRpb24+CiAgICAgIDxvcHRpb24gdmFsdWU9Im90aGVyL0NvbXB1dGVyc3R1ZmYvQ29tbWFuZHMvUHl0aG9uLnR4dCI+UHl0aG9uPC9vcHRpb24+CiAgICAgIDxvcHRpb24gdmFsdWU9Im90aGVyL0NvbXB1dGVyc3R1ZmYvQ29tbWFuZHMvQW5kcm9pZC1LZXlldmVudHMudHh0Ij5BbmRyb2lkIEtleWV2ZW50czwvb3B0aW9uPgogICAgPC9zZWxlY3Q+CiAgPC9kaXY+CiAgPGRpdiBpZD0ib3V0cHV0Ij48L2Rpdj4KPC9ib2R5Pgo8L2h0bWw+ _______________________________ Table fetch specific entries: --------------------------------------- <div class="table-container"></div> <style> .table-container { display: inline-block; } table { border-collapse: collapse; } tr { border-bottom: 2px solid #000; border-top: 2px solid #000; } td { border-right: 2px solid #000; border-left: 2px solid #000; } </style> <script> function fetchAndPopulateDataTD() { fetch('https://alceawis.de/other/extra/personal/personality/0apersonality.html') .then(response => response.text()) .then(data => { const tempDiv = document.createElement('div'); tempDiv.innerHTML = data; const table = tempDiv.querySelector('table'); const rows = table.querySelectorAll('tr'); const filteredRows = Array.from(rows).filter(row => { const cells = row.querySelectorAll('td'); return Array.from(cells).some(cell => cell.innerHTML.includes('Favorite')); }); const displayDiv = document.querySelector('.table-container'); displayDiv.innerHTML = ''; const filteredTable = document.createElement('table'); filteredRows.forEach(row => { const clonedRow = row.cloneNode(true); filteredTable.appendChild(clonedRow); }); displayDiv.appendChild(filteredTable); }) .catch(error => { console.error('Error:', error); }); } fetchAndPopulateDataTD(); </script> ________________________ Mastodon Keyword over time: -------------------------------------- <form onsubmit="openInNewTab(event)"> <label for="dropdown"></label> <select id="dropdown" name="endpoint"> <option value="https://urusai.social/api/v1/accounts/111417582756052979/statuses">@alcea@urusai.social</option> <option value="https://pb.todon.de/api/v1/accounts/109629985010224381/statuses">@alcea@pb.todon</option> <option value="https://mastodon.social/api/v1/accounts/109977878421486714/statuses">@ryedai@mastodon.social</option> <option value="https://mstdn.animexx.de/api/v1/accounts/111676830721936824/statuses">@alcea@animexx</option> </select> <label for="textfield">Enter a keyword:</label> <input type="text" id="textfield" name="keyword"> <input type="submit" value="Submit"> </form> <script> function openInNewTab(event) { event.preventDefault(); var endpoint = document.getElementById("dropdown").value; var keyword = document.getElementById("textfield").value; var url = "" + "?endpoint=" + encodeURIComponent(endpoint) + "&keyword=" + encodeURIComponent(keyword); window.open(url, "_blank"); // Open the URL in a new tab or window } </script><hr> <a target="_blank" href="?endpoint=https://urusai.social/api/v1/accounts/111417582756052979/statuses&keyword=koyu" style=color:blue>title</a><br> <!DOCTYPE html> <html> <head> <title>Line Chart Example</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <!--<div id="entities"></div>--> <canvas id="lineChart"></canvas> <script> $(document).ready(function() { var endpoint = 'https://pb.todon.de/api/v1/accounts/109629985010224381/statuses'; // Get the value of the "endpoint" and "keyword" query string parameters var urlParams = new URLSearchParams(window.location.search); var customEndpoint = urlParams.get('endpoint'); if (customEndpoint) { endpoint = customEndpoint; } var keyword = urlParams.get('keyword'); var entities = []; fetchEntities(); function fetchEntities() { var url = endpoint; if (entities.length > 0) { var linkHeader = '<' + endpoint + '?max_id=' + entities[entities.length - 1].id + '>; rel="next"'; $.ajaxSetup({ headers: { 'Link': linkHeader } }); } $.ajax({ url: url, type: 'GET', dataType: 'json', headers: { 'Authorization': 'Bearer token' }, success: function(response, textStatus, xhr) { var newEntities = response; for (var i = 0; i < newEntities.length; i++) { var entity = newEntities[i]; entities.push(entity); } var linkHeader = xhr.getResponseHeader('Link'); var nextLink = extractLinkUrl(linkHeader, 'next'); if (entities.length >= 200) { // Render the fetched entities renderEntities(); // Create the line chart createLineChart(); } else if (nextLink) { // Fetch the next set of entities endpoint = nextLink; fetchEntities(); } else { console.log('Finished fetching 200 entities'); // Render the fetched entities renderEntities(); // Create the line chart createLineChart(); } }, error: function(xhr, status, error) { console.log('Error: ' + error); } }); } function extractLinkUrl(linkHeader, rel) { var links = linkHeader.split(','); for (var i = 0; i < links.length; i++) { var link = links[i].trim(); var regex = /<([^>]+)>;\s*rel="([^"]+)"/g; var match = regex.exec(link); if (match && match[2] === rel) { return match[1]; } } return null; } function renderEntities() { for (var i = 0; i < entities.length; i++) { var entity = entities[i]; // Render the URL and date on the page var entityHtml = '<p>'; entityHtml += 'URL: <a target=_blank href="' + entity.url + '">' + entity.url + '</a><br>'; entityHtml += 'Date: ' + entity.created_at + '<br>'; entityHtml += 'Toot: ' + entity.content + '<br>'; entityHtml += '</p>'; $('#entities').append(entityHtml); } } function createLineChart() { var labels = []; var dataPoints = []; for (var i = 0; i < entities.length; i++) { var entity = entities[i]; labels.push(entity.created_at); var keywordCount = countKeywordOccurrences(entity.content, keyword); dataPoints.push(keywordCount); } var ctx = document.getElementById('lineChart').getContext('2d'); var lineChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: 'Keyword "' + keyword + '" Occurrences - ' + endpoint, data: dataPoints, borderColor: 'blue', fill: false }] }, options: { responsive: true, scales: { x: { display: true, reverse: true, // Invert the x-axis title: { display: true, text: 'Date' } }, y: { display: true, title: { display: true, text: 'Keyword "' + keyword + '" Occurrences' } } } } }); } function countKeywordOccurrences(text, keyword) { var regex = new RegExp(keyword, 'gi'); var matches = text.match(regex); if (matches) { return matches.length; } return 0; } }); </script> </body> </html> _________________________ JS inbrowser zip extractor: ----------------------------------- <!DOCTYPE html> <html> <head> <title>Zip Renderer</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.6.0/jszip.min.js"></script> <script> function renderZipFile() { var zipFileName = document.getElementById("zipFileName").value; fetch(zipFileName) .then(function(response) { return response.arrayBuffer(); }) .then(function(buffer) { return JSZip.loadAsync(buffer); }) .then(function(zip) { var folders = []; var files = []; var linksWithSecondSlash = []; zip.forEach(function(relativePath, zipEntry) { if (zipEntry.dir) { folders.push(relativePath); } else { files.push({ relativePath: relativePath, zipEntry: zipEntry }); } }); folders.sort(); files.sort(function(a, b) { return a.relativePath.localeCompare(b.relativePath); }); files.forEach(function(file) { var link = file.relativePath; if (link.split('/').length > 2) { linksWithSecondSlash.push(link); } else { renderFile(file.zipEntry); } }); linksWithSecondSlash.forEach(function(link) { var zipEntry = zip.file(link); if (zipEntry) { renderFile(zipEntry); } }); folders.forEach(function(folder) { renderFolder(folder); }); }) .catch(function(error) { console.error('Error rendering zip file:', error); }); } function renderFolder(folder) { var folderElement = document.createElement('p'); folderElement.textContent = folder; document.body.appendChild(folderElement); } function renderFile(zipEntry) { zipEntry.async('blob').then(function(blob) { var url = URL.createObjectURL(blob); var fileElement = document.createElement('a'); fileElement.href = url; fileElement.download = zipEntry.name; fileElement.textContent = zipEntry.name; fileElement.target = "_blank"; document.body.appendChild(fileElement); document.body.appendChild(document.createElement('br')); }); } </script> </head> <body> <label for="zipFileName">Zip File Name:</label> <input type="text" id="zipFileName" name="zipFileName" value="https://ry3yr.github.io/alceawis.de.zip"> <button onclick="renderZipFile()">Render Zip</button> </body> </html> _______________________ Change all of a certain link on page: ------------------------------------------------ <script> document.addEventListener('DOMContentLoaded', function() { var links = document.querySelectorAll('a[href^="https://m.youtube.com"]'); for (var i = 0; i < links.length; i++) { var link = links[i]; link.href = link.href.replace('https://m.youtube.com', 'https://super8.absturztau.be'); } }); </script> <a href="https://m.youtube.com/watch?v=01bwEdQg6EY">EternalSnow</a> _____________________________ htaccess enable caching: ------------------------------- # Enable the mod_expires module ExpiresActive On # Cache resources with specified file extensions ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType application/javascript "access plus 1 month" ExpiresByType text/css "access plus 1 month" # Set default expiration for other resources ExpiresDefault "access plus 1 week" ____________________ Currently binged Album: --------------------------------- <div id="output"></div><div id="old"></div> <script> window.addEventListener('DOMContentLoaded', (event) => { fetch('https://ry3yr.github.io/Dayalbum.js') .then(response => response.text()) .then(fileContent => { var lines = fileContent.split("\n"); var topLine = lines[0]; document.getElementById("output").innerHTML = "<b>CurrBingedAlbum</>: " + topLine; var lines = fileContent.split("\n"); var randomIndex = Math.floor(Math.random() * lines.length); var randomLine = lines[randomIndex]; document.getElementById("old").innerHTML = "<span style='color: gray; font-size: 12px;'>(Old: " + randomLine + "</span>" + ")"; }); }); </script> _____________________ Keep specific imgs despite low bandwith querystrings: ---------------------------------------- <script> if (window.location.href.includes("lowbandwidth")) { var style = document.createElement("style"); style.innerHTML = `object, img:not(#important) {display: none !important;}`; document.head.appendChild(style); } </script> Images display/not depending on "?mode=<a target="_blank" href="?mode=lowbandwidth" style=color:blue>lowbandwidth</a>" querystring:<br> keep (id="important"): [<img src="https://alcea-wisteria.de/PHP/0demo/2023-07-09-FetchMastodonAva/alcea/alcea_2024-02-08.png" id="important" style="height: 35px;">]<br><br> hide (id="null"): [<img src="https://alcea-wisteria.de/PHP/0demo/2023-07-09-FetchMastodonAva/alcea/alcea_2024-02-08.png" id="null" style="height: 35px;">] _______________________ Shoutcast Radio Stream: ----------------------------------------- <a target="_blank" href="http://fmstream.org/index.php?c=D" style=color:blue>Kartoffelstations</a> <br><hr><br> <style> body { font-family: Arial, sans-serif; margin: 20px; } label { font-weight: bold; } input[type="text"], input[type="file"], button { margin-bottom: 10px; } #player { margin-top: 20px; background-color: #f5f5f5; padding: 20px; border-radius: 8px; } audio { width: 100%; } #trackInfo { margin-top: 20px; font-weight: bold; } </style> </head> <body> <button onclick="queryURL()">[NowPlaying]</button> <div id="response"></div> <br> <br> [ <a href="#" onclick="document.getElementById('urlInput').value ='https://stream.antenne.de/antenne/stream/mp3'; return false;">Antenne</a> <a href="#" onclick="document.getElementById('urlInput').value = 'https://stream.bigfm.de/bw/mp3-128'; return false;">BigFM</a> <a href="#" onclick="document.getElementById('urlInput').value = 'https://liveradio.swr.de/sw890cl/swr3/play.aac'; return false;">SWR3</a> ]<br> <input type="text" id="urlInput" value="https://stream.antenne.de/antenne/stream/mp3"> <br> <button onclick="renderShoutcast()">[▷Play]</button> <br> <div id="player"></div> <div id="trackInfo"></div> <script> var audioElement = null; function renderShoutcast() { var urlInput = document.getElementById("urlInput").value; var playerDiv = document.getElementById("player"); // Clear existing player while (playerDiv.firstChild) { playerDiv.removeChild(playerDiv.firstChild); } audioElement = document.createElement("audio"); audioElement.src = urlInput; audioElement.controls = true; playerDiv.appendChild(audioElement); // Add event listener for the 'canplay' event audioElement.addEventListener('canplay', function() { audioElement.play(); var button = document.querySelector("[onclick='queryURL()']"); button.click(); //click queryURLButton }); } // Handle file upload var fileInput = document.getElementById('fileInput'); fileInput.addEventListener('change', function(event) { var file = event.target.files[0]; var reader = new FileReader(); reader.onload = function(event) { var url = event.target.result; document.getElementById('urlInput').value = url; renderShoutcast(); }; reader.readAsDataURL(file); }); </script> <!---Get Nowplaying---> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> function queryURL() { var url = $('#urlInput').val(); var requestURL = 'https://alcea-wisteria.de/PHP/0demo/2024-02-09-ShoutcaseMetadataextract/querystringextract.php?streamurl=' + url; fetch(requestURL) .then(function(response) { if (!response.ok) { throw new Error('Network response was not ok'); } return response.text(); }) .then(function(data) { $('#response').text(data); }) .catch(function(error) { $('#response').text('Error occurred while fetching data: ' + error); }); } </script> <details><summary>file</summary><input type="file" id="fileInput"></details> <details><summary>PHPTitlefetch</summary> <plaintext> <?php function getStreamMetadata() { if (isset($_GET['streamurl'])) { $streamUrl = $_GET['streamurl']; $needle = 'StreamTitle='; $ua = 'Dailymate Radio/1.0'; $opts = ['http' => ['method' => 'GET', 'header' => 'Icy-MetaData: 1', 'user_agent' => $ua] ]; $context = stream_context_create($opts); $icyMetaIntFound = false; $icyInterval = -1; $offset = 0; if(($headers = get_headers($streamUrl, 0, $context))) { foreach($headers as $h) { if(!(strpos(strtolower($h), 'icy-metaint:') === false)) { $icyMetaIntFound = true; $icyInterval = explode(':', $h)[1]; break; } } } if(!$icyMetaIntFound) { echo "icy-metaint header not exists!"; return; } if($stream = fopen($streamUrl, 'r', false, $context)) { while($buffer = stream_get_contents($stream, $icyInterval, $offset)) { if(strpos($buffer, $needle) !== false) { fclose($stream); $title = explode($needle, $buffer)[1]; return substr($title, 1, strpos($title, ';') - 2); } $offset += $icyInterval; } } } else { // The 'streamurl' parameter is not set } } echo getStreamMetadata(); ?> __________________________ Radio Song Time Url constructor: -------------------------------------------- <a target="_blank" href="?baseurl=https://www.antenne.de/pramm/song-suche?date=" style=color:blue>Changestation</a><br> <script> function openSongSearchResults() { var parameterUrl = new URL(window.location.href); var baseurl = parameterUrl.searchParams.get("baseurl"); if (baseurl == null) { baseurl = "https://www.antenne.de/programm/song-suche"; } var year = document.getElementById("yearInput").value; var month = document.getElementById("monthInput").value; var day = document.getElementById("dayInput").value; var hours = document.getElementById("hoursInput").value; var minutes = document.getElementById("minutesInput").value; var date = year + '-' + month + '-' + day; var time = hours + '' + minutes; var url = baseurl + "?date=" + date + "&channel=live&time=" + time; window.open(url, "_blank"); } function getCurrentDateTime() { var currentDate = new Date(); var year = currentDate.getFullYear(); var month = String(currentDate.getMonth() + 1).padStart(2, '0'); var day = String(currentDate.getDate()).padStart(2, '0'); var hours = String(currentDate.getHours()).padStart(2, '0'); var minutes = String(currentDate.getMinutes()).padStart(2, '0'); document.getElementById("yearInput").value = year; document.getElementById("monthInput").value = month; document.getElementById("dayInput").value = day; document.getElementById("hoursInput").value = hours; //document.getElementById("minutesInput").value = minutes; } </script> <body onload="getCurrentDateTime()"> <h1>RadioSongSearch</h1> <label for="yearInput">Year:</label> <input type="text" id="yearInput"> <label for="monthInput">Month:</label> <input type="text" id="monthInput"> <label for="dayInput">Day:</label> <input type="text" id="dayInput"> <label for="hoursInput">Time:</label> <input type="text" id="hoursInput"> <label for="minutesInput">Minutes:</label> <input type="text" id="minutesInput"> <br> <button onclick="openSongSearchResults()">Search</button> </body> ___________________________ Random game (dekudeals & steam json) picker: ----------------------------------------- <div id="collection-links"></div> <script> function fetchData() { fetch('https://ry3yr.github.io/collection.json') .then(response => response.json()) .then(data1 => { const randomIndex1 = Math.floor(Math.random() * data1.items.length); const randomEntry1 = data1.items[randomIndex1]; fetch('https://ry3yr.github.io/steam_library.json') .then(response => response.json()) .then(data2 => { const games = data2.response.games; const randomIndex2 = Math.floor(Math.random() * games.length); const randomGame = games[randomIndex2]; const randomEntry = Math.random() < 0.5 ? randomEntry1.name + ' (NintendoSwitch)' : randomGame.name + ' (Steam)'; document.getElementById('collection-links').innerHTML = `<p>${randomEntry} <a href="javascript:fetchData()">[Rerun]</a></p>`; }); }); } fetchData(); </script> _______________________ MAL / MyAnimeList Table parser (xml export: https://myanimelist.net/panel.php?go=export) ------------------------------- <script> fetch("https://ry3yr.github.io/mal.xml") .then(response => response.text()) .then(xmlString => { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlString, "text/xml"); const table = document.createElement("table"); const animeList = xmlDoc.getElementsByTagName("anime"); const animeData = []; for (let i = 0; i < animeList.length; i++) { const anime = animeList[i]; const seriesTitle = anime.getElementsByTagName("series_title")[0].textContent; const seriesType = anime.getElementsByTagName("series_type")[0].textContent; const seriesEpisodes = parseInt(anime.getElementsByTagName("series_episodes")[0].textContent); const myScore = parseFloat(anime.getElementsByTagName("my_score")[0].textContent); const myStatus = anime.getElementsByTagName("my_status")[0].textContent; animeData.push({ seriesTitle, seriesType, seriesEpisodes, myScore, myStatus }); } const createTable = () => { table.innerHTML = ""; const headerRow = document.createElement("tr"); const headers = [ { label: "Title", key: "seriesTitle" }, { label: "Type", key: "seriesType" }, { label: "Episodes", key: "seriesEpisodes" }, { label: "Score", key: "myScore" }, { label: "Status", key: "myStatus" } ]; headers.forEach(header => { const headerCell = document.createElement("th"); headerCell.textContent = header.label; headerCell.addEventListener("click", () => sortTable(header.key)); headerRow.appendChild(headerCell); }); table.appendChild(headerRow); animeData.forEach(data => { const row = document.createElement("tr"); headers.forEach(header => { const cell = document.createElement("td"); if (header.key === "seriesTitle") { const link = document.createElement("a"); link.href = `https://myanimelist.net/search/all?q=${encodeURIComponent(data[header.key])}`; link.target = "_blank"; link.textContent = data[header.key]; cell.appendChild(link); } else { cell.textContent = data[header.key]; } row.appendChild(cell); }); table.appendChild(row); }); document.body.appendChild(table); }; let sortKey = ""; let sortAscending = true; const sortTable = key => { if (sortKey === key) { sortAscending = !sortAscending; } else { sortKey = key; sortAscending = true; } animeData.sort((a, b) => { const valueA = a[key]; const valueB = b[key]; let comparison = 0; if (valueA > valueB) { comparison = 1; } else if (valueA < valueB) { comparison = -1; } return sortAscending ? comparison : -comparison; }); createTable(); }; createTable(); }) .catch(error => { console.error("Error loading mal.xml:", error); }); </script> ______________________________ Random mtd tag fetch (jukebox): ----------------------------------------- <a href="?tag=https://urusai.social/api/v1/timelines/tag/RamblingsAlcea">xmpl<a><br> <div id="entryContainer"></div> <script> async function displayRandomEntry() { const urlParams = new URLSearchParams(window.location.search); const tag = urlParams.get("tag"); let randomInstanceUrl; if (tag) { randomInstanceUrl = `${tag}`; } else { const instances = [ "https://urusai.social/api/v1/timelines/tag/CurrListeningAlcea", "https://mastodon.social/api/v1/timelines/tag/CurrListeningRyeDai", "https://pb.todon.de/api/v1/timelines/tag/CurrListeningAlcea" ]; randomInstanceUrl = instances[Math.floor(Math.random() * instances.length)]; } try { const response = await fetch(randomInstanceUrl); const data = await response.json(); const randomEntry = data[Math.floor(Math.random() * data.length)]; //let entryContent = randomEntry.content.replace(/<br(\s*\/)?>/g, "").replace(/<\/?p>/g, ""); let entryContent = randomEntry.content; const entryContainer = document.getElementById("entryContainer"); if (entryContainer) { const entryLink = document.createElement("a"); entryLink.href = randomEntry.url; entryLink.target = "_blank"; entryLink.textContent = "->"; entryContainer.innerHTML = entryContent; entryContainer.appendChild(entryLink); } else { console.log("Entry container not found."); } } catch (error) { console.error("Error fetching the entry:", error); } } displayRandomEntry(); </script> __________________________ Youtube Link relay: -------------------------- <a target="_blank" href="?v=0SQ-TJKPPIg&t=1m02s" style="color:blue">Xmple</a><br><br> <script> const urlParams = new URLSearchParams(window.location.search); const videoId = urlParams.get('v'); const timestamp = urlParams.get('t') || '0m0s'; if (videoId) { const youtubeLink = `https://www.youtube.com/watch?v=${videoId}&t=${timestamp}`; // window.open(youtubeLink); window.location.href = youtubeLink; } else { // Handle the case when the video ID is empty console.log("Video ID is empty. Redirecting stopped."); } </script> <details> <u>Parameters:</u><br> <b>v</b>: VideoId<br> <b>t</b>: 00m00s <br> <br>Example:<br> ?v=0SQ-TJKPPIg&t=1m02s </details> <hr> <script> function generateLink() { var url = document.getElementById("youtube-url").value; var videoId = extractVideoId(url); var link = window.location.origin + "/yt?v=" + videoId; var minutes = document.getElementById("minutes").value; var seconds = document.getElementById("seconds").value; if (minutes && seconds) { var timeQuery = "&t=" + minutes + "m" + seconds + "s"; link += timeQuery; var ytlink = "https://m.youtube.com/watch?v=" + videoId + timeQuery; } document.getElementById("generated-link").textContent = link; document.getElementById("generated-ytlink").textContent = ytlink; } function extractVideoId(url) { var videoId = ""; var regex = /[?&]v=([^&#]*)/i; var match = regex.exec(url); if (match && match[1]) { videoId = match[1]; } return videoId; } </script> </head> <body> <label for="youtube-url">Enter YouTube URL:</label> <input type="text" id="youtube-url" placeholder="https://www.youtube.com/watch?v=..."> <br><br> <label for="minutes">Minutes:</label> <input type="text" id="minutes"> <label for="seconds">Seconds:</label> <input type="text" id="seconds"> <br><br> <button onclick="generateLink()">Generate Link</button> <p id="generated-link"></p> <p>YouTube Link: <span id="generated-ytlink"></span></p> ________________ Link that only shows while (not iframed) -------------------------- <style>.hide-iframed { display: none; }</style> <script> function isInIframe() { try { return window.self !== window.top; } catch (e) { return true; } } window.onload = () => { if (!isInIframe()) { document.querySelector('.hide-iframed').style.display = 'inline'; } }; </script> <a target="_blank" href="https://mega.nz/folder/wcgUXCDA#JtOYw-xbBRy4FtBJ2Cnf0A" class="hide-iframed">Mega</a> ____________________________ Fetch 15 newest Channel Youtube Videos (api) ------------------------------------------- <script> const API_KEY = 'APIKey'; const CHANNEL_ID = 'UCmIpOnd5BVx5Si2hp0WNKZw'; const MAX_RESULTS = 15; function fetchVideos() { fetch( `https://www.googleapis.com/youtube/v3/search?key=${API_KEY}&channelId=${CHANNEL_ID}&part=snippet,id&order=date&maxResults=${MAX_RESULTS}` ) .then((response) => response.json()) .then((data) => { data.items.forEach((item) => { const videoId = item.id.videoId; const title = item.snippet.title; const link = document.createElement('a'); link.href = `https://www.youtube.com/watch?v=${videoId}`; link.textContent = title; link.target = '_blank'; // Add target="_blank" to open the link in a new tab document.body.appendChild(link); const lineBreak = document.createElement('br'); document.body.appendChild(lineBreak); const additionalLineBreak = document.createElement('br'); document.body.appendChild(additionalLineBreak); }); }) .catch((error) => { console.error('Error fetching videos:', error); }); } fetchVideos(); </script> ___________________________ Fetch and display random table entry: -------------------------------- <div class="random-row-container"></div><button onclick="fetchAndPopulateData()">me</button> <style>.random-row-container {display: inline-block;} button {display: inline-block;vertical-align: top;}</style> <script> function fetchAndPopulateData() { fetch('https://alceawis.de/other/extra/personal/personality/0apersonality.html') .then(response => response.text()) .then(data => { const tempDiv = document.createElement('div'); tempDiv.innerHTML = data; const table = tempDiv.querySelector('table'); const rows = table.querySelectorAll('tr'); const randomRowIndex = Math.floor(Math.random() * rows.length); const randomRow = rows[randomRowIndex]; const displayDiv = document.querySelector('.random-row-container'); displayDiv.innerHTML = ''; const tableElement = document.createElement('table'); const newRow = tableElement.insertRow(); randomRow.querySelectorAll('td').forEach((cell, index) => { const newCell = newRow.insertCell(); newCell.innerHTML = cell.innerHTML; newCell.style.border = '1px solid #000'; newCell.style.padding = '5px 10px'; newCell.style.margin = '2px'; newCell.style.whiteSpace = 'nowrap'; }); displayDiv.appendChild(tableElement); }) .catch(error => { //fetchAndPopulateData(); console.error('Error:', error); }); } // Fetch data on page load //fetchAndPopulateData(); </script> ____________________ Table Bio Info Chart / Card: ------------------------------- <style> body { font-family: Arial, sans-serif; background-color: #f7f7f7; margin: 0; padding: 20px; } h1 { text-align: center; color: #333; } table { border-collapse: collapse; width: 50%; margin: 0 auto; background-color: #fff; border: 1px solid #ddd; } th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; } tr:nth-child(even) { background-color: #f2f2f2; } </style> <script> function calculateAge() { var birthDate = new Date('1991-01-18'); var today = new Date(); var age = today.getFullYear() - birthDate.getFullYear(); var monthDiff = today.getMonth() - birthDate.getMonth(); if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) { age--; } if (age > 100) { age = "100+"; } var birthDateString = birthDate.toLocaleDateString(); var ageString = '(' + age + ')'; var combinedString = birthDateString + ' ' + ageString; document.getElementById('birthdate-age').textContent = combinedString; } </script> </head> <body onload="calculateAge()"> <h1>Personal Information</h1> <table> <tr> <th>Info</th> <th></th> </tr> <tr> <td>Birthday &amp; Age</td> <td id="birthdate-age"></td> </tr> <tr> <td>Blood Type</td> <td>C</td> </tr> <tr> <td>Favorite Colors</td> <td>Red, Blue</td> </tr> <tr> <td>...</td> <td>.</td> </tr> </table> </body> </html> ____________________ Chart query (from txt & value at end) querystring ver -------------------------------------------------- <details> <a target="_blank" href="?lineslice=6&fetchTarget=mbti.txt&targeturl=https://jung" style=color:blue>mbti</a> <a target="_blank" href="?lineslice=6&fetchTarget=bigfive.txt&targeturl=https://bigfive" style=color:blue>biugfive</a> </details> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <body> <h1 id="highestPercentage"></h1> <h2 id="entryCount"></h2> <h3 id="mostFrequentValue"></h3> <canvas id="chart"></canvas> <script> const urlParams = new URLSearchParams(window.location.search); const lineSliceParam = urlParams.get('lineslice') || '6'; const targetUrl = urlParams.get('targeturl') || 'https://www.web.de'; const fetchTarget = urlParams.get('fetchTarget') || 'mbti.txt'; fetch(fetchTarget) .then(response => response.text()) .then(data => { const lines = data.split('\n'); const frequencies = {}; lines.forEach(line => { const lastSixCharacters = line.slice(-lineSliceParam); if (frequencies[lastSixCharacters]) { frequencies[lastSixCharacters]++; } else { frequencies[lastSixCharacters] = 1; } }); const sortedFrequencies = Object.entries(frequencies).sort((a, b) => b[1] - a[1]); const labels = sortedFrequencies.map(entry => entry[0]); const values = sortedFrequencies.map(entry => entry[1]); const highestFrequency = values[0]; const totalFrequencies = values.reduce((acc, val) => acc + val, 0); const highestPercentage = ((highestFrequency / totalFrequencies) * 100).toFixed(2); const highestPercentageElement = document.getElementById('highestPercentage'); highestPercentageElement.innerHTML = `<a target="_blank" href="${targetUrl}/${labels[0].toLowerCase()}.html">${labels[0]} %${highestPercentage}</a>`.replace(/[()]/g, ''); const entryCountElement = document.getElementById('entryCount'); entryCountElement.textContent = `${highestFrequency} entries vs ${lines.length} total lines`; const mostFrequentValueElement = document.getElementById('mostFrequentValue'); const ctx = document.getElementById('chart').getContext('2d'); new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: 'Frequency', data: values, backgroundColor: 'rgba(75, 192, 192, 0.6)', borderColor: 'rgba(75, 192, 192, 1)', borderWidth: 1 }] }, options: { responsive: true, scales: { y: { beginAtZero: true, precision: 0 } } } }); }) .catch(error => console.log(error)); </script> </body> ____________________ MBTI Probability crunch: -------------- <!DOCTYPE html> <html> <head> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> </head> <body> <h1 id="highestPercentage"></h1> <h2 id="entryCount"></h2> <h3 id="mostFrequentValue"></h3> <canvas id="chart"></canvas> <script> fetch('/other/extra/personal/personality/mbti.txt') .then(response => response.text()) .then(data => { const lines = data.split('\n'); const frequencies = {}; lines.forEach(line => { const lastSixCharacters = line.slice(-6); if (frequencies[lastSixCharacters]) { frequencies[lastSixCharacters]++; } else { frequencies[lastSixCharacters] = 1; } }); const sortedFrequencies = Object.entries(frequencies).sort((a, b) => b[1] - a[1]); const labels = sortedFrequencies.map(entry => entry[0]); const values = sortedFrequencies.map(entry => entry[1]); const highestFrequency = values[0]; const totalFrequencies = values.reduce((acc, val) => acc + val, 0); const highestPercentage = ((highestFrequency / totalFrequencies) * 100).toFixed(2); const highestPercentageElement = document.getElementById('highestPercentage'); highestPercentageElement.textContent = `${labels[0]} %${highestPercentage}`; const entryCountElement = document.getElementById('entryCount'); entryCountElement.textContent = `${highestFrequency} entries vs ${lines.length} total lines`; const mostFrequentValueElement = document.getElementById('mostFrequentValue'); //mostFrequentValueElement.textContent = `Most frequent of {labels[0]}`; const ctx = document.getElementById('chart').getContext('2d'); new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: 'Frequency', data: values, backgroundColor: 'rgba(75, 192, 192, 0.6)', borderColor: 'rgba(75, 192, 192, 1)', borderWidth: 1 }] }, options: { responsive: true, scales: { y: { beginAtZero: true, precision: 0 } } } }); }) .catch(error => console.log(error)); </script> ______________________ Load HTML Content on button press: ----------------------------------------------- <script> function loadBase64HTML() { var base64HTML = "PGh0bWw+PGJvZHk+VGhpcyBpcyBhIGJhc2U2NC1lbmNvZGVkIEhUTUwgY29kZSBpbiBhIG51bWJlciBvZiBhIGRpdmlkZSBkYXRhPC9ib2R5PjwvaHRtbD4="; var decodedHTML = atob(base64HTML); var contentContainer = document.getElementById('contentContainer'); contentContainer.innerHTML = decodedHTML; } </script> <button onclick="loadBase64HTML()">Load HTML</button> <div id="contentContainer"></div> __________________________ Right sideopening drawer ------------------------------ <!----Android--> <style>.container{position:relative;display:inline-block}.hidden-div{display:none;position:absolute;top:0;left:100%;padding:0px;background-color:transparent}</style> <div class="container"><img src="https://www.freepnglogos.com/uploads/android-logo-png/android-logo-0.png" alt="Android" onclick="!function(){var e=document.getElementById('hiddenDiv');e.style.display='none'===e.style.display?'block':'none'}()" width="45" height="45"><div id="hiddenDiv" class="hidden-div"> <div style="display: flex;"> <a target="_blank" href="jp.ne.ibis.ibispaintx.app"><img src="https://img.icons8.com/color/452/ibis-paint-x.png" width="45" height="45"></a> <a target="_blank" href="org.ffmpeg.gui"><img src="https://cdn.icon-icons.com/icons2/3053/PNG/512/ffmpeg_macos_bigsur_icon_190192.png" width="45" height="45"></a> <a target="_blank" href="nextapp.fx"><img src="https://www.svgrepo.com/show/504367/fx-file-explorer.svg" width="45" height="45"></a> <a target="_blank" href="com.simplemobiletools.gallery.pro"><img src="https://i.ibb.co/2ShMS3m/simplegallery.png" width="45" height="45"></a> <a target="_blank" href="com.bokhary.lazyboard"><img src="https://i.ibb.co/M8TQFwF/Lazyboard.png" width="45" height="45"></a> </div></div></div> _______________________________ Birthday reminder: ----------------------------- <div id="outputbday"></div> <script> fetchBirthday(); function fetchBirthday() { fetch('https://ry3yr.github.io/bdays.txt') .then(response => response.text()) .then(data => { const lines = data.split('\n'); const randomIndex = Math.floor(Math.random() * lines.length); const randomLine = lines[randomIndex]; const [date, name] = randomLine.split('*').map(entry => entry.trim()); const daysTillBday = daysUntilBirthday(date); const age = calculateAge(date); displayBirthdayInfo(name, daysTillBday, age); }) .catch(error => { console.error('Error:', error); }); } function daysUntilBirthday(birthday) { const today = new Date(); const nextBirthday = new Date(today.getFullYear(), new Date(birthday).getMonth(), new Date(birthday).getDate()); if (nextBirthday < today) { nextBirthday.setFullYear(today.getFullYear() + 1); } const timeDiff = nextBirthday.getTime() - today.getTime(); const daysUntil = Math.ceil(timeDiff / (1000 * 3600 * 24)); const isLeapYear = (year) => (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)); const year = nextBirthday.getFullYear(); const daysInYear = isLeapYear(year) ? 366 : 365; return daysUntil; } function calculateAge(birthday) { const today = new Date(); const birthDate = new Date(birthday); let age = today.getFullYear() - birthDate.getFullYear(); const monthDiff = today.getMonth() - birthDate.getMonth(); const dayDiff = today.getDate() - birthDate.getDate(); if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) { age--; } return age; } function displayBirthdayInfo(name, days, age) { const outputDiv = document.getElementById('outputbday'); if (Number.isNaN(days)) { fetchBirthday(); // Retry fetching a valid birthday } else { const currentDate = new Date(); const year = currentDate.getFullYear(); const isLeapYear = (year) => (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)); const daysInYear = isLeapYear(year) ? 366 : 365; if (days === 0) { outputDiv.innerHTML = `Today is <b>${name}</b>'s Birthday! (Age: ${age}) <a target="_blank" href="https://alceawis.de/bdays.txt" style="color:gray">(s)</a>`; } else if (days === daysInYear) { outputDiv.innerHTML = `Today is <b>${name}</b>'s Birthday! (Age: ${age}) <a target="_blank" href="https://alceawis.de/bdays.txt" style="color:gray">(s)</a>`; } else { outputDiv.innerHTML = `[${name}] <b>${days}</b> day(s) till birthday. (Age: ${age}) <a target="_blank" href="https://alceawis.de/bdays.txt" style="color:gray">(s)</a>`; } } } </script> ________________________ Color Links on buttonpress if querystring exists _______________________ ?user=user<br><br> <button id="showLinksButton" style="border: none;">Show Links</button> <script> document.getElementById('showLinksButton').addEventListener('click', function() { var urlParams = new URLSearchParams(window.location.search); if (urlParams.get('user') === 'user') { var links = document.querySelectorAll('a#transp'); for (var i = 0; i < links.length; i++) { links[i].style.color = 'red'; } } else { alert('Sorry, you do not have permission.'); } }); </script><br> <a id="transp" target="_blank" href="https://alcea-wisteria.de/PHP/0demo/2024-01-14-Lastplyed/lastplayed.php?gamename=${item.name}" style="color: transparent;">LinkyLink</a> ________________________ Render textfile in style: ------------------------- name https://link1 name2 https://link2 <script> fetch('https://alcea-wisteria.de/PHP/xnotes/xnotes.txt') .then(response => response.text()) .then(data => { const lines = data.trim().split('\n'); lines.forEach(line => { const [title, url] = line.split(' https://'); const fullUrl = 'https://' + url; const link = document.createElement('a'); link.href = fullUrl; link.target = '_blank'; link.textContent = title; document.body.appendChild(link); document.body.appendChild(document.createElement('br')); }); }) .catch(error => { console.log('Error fetching data:', error); }); </script> ____________________________ Hide onpage links based on querystring ------------------------------------------------- "note" querystring value determines which links stay<br> "?note=FAQ" keeps all links with FAQ in them and hides the rest<br><br> <!-----FilterLinks-with-note-querystring--> <style> .hidden { display: none; } </style> <script> // Get the value of the "note" query string parameter from the URL const urlParams = new URLSearchParams(window.location.search); const noteValue = urlParams.get("note"); // Get all the anchor tags (URLs) on the page const links = document.getElementsByTagName("a"); // Loop through each link and hide the ones that don't have the note value in their title for (let i = 0; i < links.length; i++) { const link = links[i]; const linkTitle = link.textContent; if (noteValue && linkTitle && !linkTitle.toLowerCase().includes(noteValue.toLowerCase())) { link.classList.add("hidden"); } } </script> (source: https://codepen.io/ryedai1/pen/Yzgqwaq ) ______________________________ Audio on link hover/click --------------------------------------- <!----view-source:https://molars.neocities.org/--> <script> // Mouseover/ Click sound effect- by JavaScript Kit (www.javascriptkit.com) // Visit JavaScript Kit at http://www.javascriptkit.com/ for full source code //** Usage: Instantiate script by calling: var uniquevar=createsoundbite("soundfile1", "fallbackfile2", "fallebacksound3", etc) //** Call: uniquevar.playclip() to play sound var html5_audiotypes={ //define list of audio file extensions and their associated audio types. Add to it if your specified audio file isn't on this list: "mp3": "audio/mpeg", "mp4": "audio/mp4", "ogg": "audio/ogg", "wav": "audio/wav"} function createsoundbite(sound){ var html5audio=document.createElement('audio') if (html5audio.canPlayType){ //check support for HTML5 audio for (var i=0; i<arguments.length; i++){ var sourceel=document.createElement('source') sourceel.setAttribute('src', arguments[i]) if (arguments[i].match(/\.(\w+)$/i)) sourceel.setAttribute('type', html5_audiotypes[RegExp.$1]) html5audio.appendChild(sourceel)} html5audio.load() html5audio.playclip=function(){ html5audio.pause() html5audio.currentTime=0 html5audio.play()} return html5audio} else{ return {playclip:function(){throw new Error("Your browser doesn't support HTML5 audio unfortunately")}}}} //Initialize two sound clips with 1 fallback file each: var mouseoversound=createsoundbite("https://a.tumblr.com/tumblr_ojrn7aGBii1w2e2oyo1.mp3") var clicksound=createsoundbite("https://a.tumblr.com/tumblr_ojrmy55yUN1w2e2oyo1.mp3") </script> <script> document.getElementById("img").addEventListener("click", function(){ document.getElementById("audio").play(); }); </script> <div> <div class="sidebar"> <img src=""> <a href="#" onmouseover="mouseoversound.playclip()" onclick="clicksound.playclip()">about us</a><br> <img src=""><a href="#" onmouseover="mouseoversound.playclip()" onclick="clicksound.playclip()"> resources</a><br> <img src=""><a href="#" onmouseover="mouseoversound.playclip()" onclick="clicksound.playclip()"> graphics</a><br> <img src=""> <a href="#" onmouseover="mouseoversound.playclip()" onclick="clicksound.playclip()">interests</a><br> <img src=""> <a href="#" onmouseover="mouseoversound.playclip()" onclick="clicksound.playclip()">socials</a><br> _________________________ 45degree / SouthEast animate (section) backgroundscroll: --------------------------------------------------- <style>.tile-sectionsteam {background-image: url('https://alceawis.de/other/images/bg/steambg.gif');background-repeat: repeat;background-size: 34px;animation: scroll45deg 2s linear infinite;}@keyframes scroll45deg {0% {background-position: 0 0;}100% {background-position: 34px 34px;}}</style> <div class="tile-sectionsteam"> Text<br><br><br><br><br><br><br><br><br><br><br><br> </div> ________________________________ html code listview writer: --------------------------- <style> .smart-hover:hover::after { content: attr(title); } </style> <script> function generateHTML() { // Get input values const url = document.getElementById('urlInput').value; const name = document.getElementById('nameInput').value; const imageLink = document.getElementById('imageInput').value; const description = document.getElementById('descriptionInput').value; // Create the link element const link = document.createElement('a'); link.href = url; link.target = '_blank'; // Create the image element const image = document.createElement('img'); image.src = imageLink; image.style.width = '45px'; const span = document.createElement('span'); span.classList.add('smart-hover'); span.title = ' •' + description; const nameElement = document.createElement('u'); nameElement.innerText = name; span.appendChild(nameElement); link.appendChild(image); link.appendChild(span); // Get the generated HTML code const generatedHTML = '<a target="_blank" href="' + url + '"><img src="' + imageLink + '" style="width:45px;"></img></a><span class="smart-hover" title=" •' + description + '"> <u>' + name + '</u></span><style>.smart-hover:hover::after{content:attr(title);}</style><br>'; const outputHTML = document.getElementById('outputHTML'); outputHTML.innerHTML = generatedHTML; const outputText = document.getElementById('outputText'); outputText.value = generatedHTML; } </script> </head> <body> <form> <label for="urlInput">URL:</label> <input type="text" id="urlInput" oninput="generateHTML()"><br> <label for="nameInput">Name:</label> <input type="text" id="nameInput" oninput="generateHTML()"><br> <label for="imageInput">Image Link:</label> <input type="text" id="imageInput" oninput="generateHTML()"><br> <label for="descriptionInput">Description:</label> <input type="text" id="descriptionInput" oninput="generateHTML()"><br> </form> <div id="outputHTML"></div> <textarea id="outputText" rows="10" cols="50" readonly></textarea </body> </html> __________________ HalfSize <hr> (50%<hr>) ---------------------- <hr style="width:50%;float:left;"> ___________________________ ZeroWidth Joiner between inputs (for mastodon emojis ): ------------------------------------------- <div id="textboxes"> <input type="text" id="textbox1" placeholder="Enter text 1"> <button onclick="removeTextbox(1)">-</button> <br> <input type="text" id="textbox2" placeholder="Enter text 2"> <button onclick="removeTextbox(2)">-</button> <br> </div> <button onclick="addTextbox()">+</button> <br> <button onclick="copyText()">Copy</button> <script> var textboxCount = 2; function addTextbox() { textboxCount++; var newTextbox = document.createElement("input"); newTextbox.setAttribute("type", "text"); newTextbox.setAttribute("id", "textbox" + textboxCount); newTextbox.setAttribute("placeholder", "Enter text " + textboxCount); var removeButton = document.createElement("button"); removeButton.innerHTML = "-"; removeButton.onclick = function() { removeTextbox(textboxCount); }; var container = document.getElementById("textboxes"); container.appendChild(newTextbox); container.appendChild(removeButton); container.appendChild(document.createElement("br")); } function removeTextbox(index) { var textbox = document.getElementById("textbox" + index); var removeButton = textbox.nextElementSibling; var lineBreak = removeButton.nextElementSibling; textbox.remove(); removeButton.remove(); lineBreak.remove(); } function copyText() { var joinedText = ""; for (var i = 1; i <= textboxCount; i++) { var textbox = document.getElementById("textbox" + i); joinedText += textbox.value + "\u200D"; } var tempInput = document.createElement("input"); tempInput.setAttribute("type", "text"); tempInput.setAttribute("value", joinedText); document.body.appendChild(tempInput); tempInput.select(); document.execCommand("copy"); document.body.removeChild(tempInput); alert("Text copied to clipboard: " + joinedText); } </script> <!--<input type="text" id="textbox1" placeholder="Enter text 1">+ <input type="text" id="textbox2" placeholder="Enter text 2"> <button onclick="copyText()">Copy</button> <script> function copyText() { var text1 = document.getElementById("textbox1").value; var text2 = document.getElementById("textbox2").value; var joinedText = text1 + "\u200D" + text2; var tempInput = document.createElement("input"); tempInput.setAttribute("type", "text"); tempInput.setAttribute("value", joinedText); document.body.appendChild(tempInput); tempInput.select(); document.execCommand("copy"); document.body.removeChild(tempInput); alert("Text copied to clipboard: " + joinedText); } </script>--> ___________________________ Simple detail spoiler: ---------------------------------- <details><summary>name</summary> text </details> ______________________ HTML Midi Sheetmusic render: -------------------------------------------------- <!DOCTYPE html> <html> <head> <title>Staff View</title> <script src="https://cdn.jsdelivr.net/npm/tone@14.7.58"></script> <script src="https://cdn.jsdelivr.net/npm/@magenta/music@1.23.1/es6/core.js"></script> <script src="https://cdn.jsdelivr.net/npm/focus-visible@5"></script> <script src="https://cdn.jsdelivr.net/npm/html-midi-player@1.5.0"></script> </head> <body> <div> <label for="midiUrl">Enter MIDI URL:</label> <input type="text" id="midiUrl" /> <button onclick="loadMidi()">Load MIDI</button> </div> <midi-player id="player" src="https://alceawis.de/other/music/midi/piano/ygovrains_-_Sad_Reminiscence.mid" sound-font visualizer="#myStaffVisualizer"> </midi-player> <midi-visualizer type="staff" id="myStaffVisualizer" src="https://alceawis.de/other/music/midi/piano/ygovrains_-_Sad_Reminiscence.mid"> </midi-visualizer> <script> function loadMidi() { const midiUrlInput = document.getElementById('midiUrl'); const midiUrl = midiUrlInput.value; const player = document.getElementById('player'); const visualizer = document.getElementById('myStaffVisualizer'); player.setAttribute('src', midiUrl); visualizer.setAttribute('src', midiUrl); } document.addEventListener('DOMContentLoaded', function () { loadMidi(); }); </script> </body> </html> <!--<!DOCTYPE html> <html> <head> <title>Staff View</title> <script src="https://cdn.jsdelivr.net/npm/tone@14.7.58"></script> <script src="https://cdn.jsdelivr.net/npm/@magenta/music@1.23.1/es6/core.js"></script> <script src="https://cdn.jsdelivr.net/npm/focus-visible@5"></script> <script src="https://cdn.jsdelivr.net/npm/html-midi-player@1.5.0"></script> </head> <body> <midi-player id="player" src="https://alceawis.de/other/music/midi/piano/ygovrains_-_Sad_Reminiscence.mid" sound-font visualizer="#myStaffVisualizer"> </midi-player> <midi-visualizer type="staff" id="myStaffVisualizer" src="https://alceawis.de/other/music/midi/piano/ygovrains_-_Sad_Reminiscence.mid"> </midi-visualizer> </body> </html>--> ___________________________ YearWeekDayHour Progress bar: ----------------------------------- <style> .progress-container { display: flex; align-items: center; margin-bottom: -23px; margin-right: 0px; } .progress-bar { width: 234px; height: 16px; border: 1px solid #ccc; background-color: #fff; border-radius: 43px; overflow: hidden; position: relative; } .progress-bar-fill { height: 100%; background-color: #4caf50; } .progress-label { position: absolute; top: 0; left: 50%; transform: translateX(-50%); color: #000; //font-weight: italic; } .progress-text { margin-left: 10px; } .year-progress-bar, .week-progress-bar, .day-progress-bar, .day2-progress-bar { background-color: #fff; } .year-progress-label, .week-progress-label, .day-progress-label, .day2-progress-label { color: #000; } </style> <body> <div class="progress-container"> <div class="progress-bar" id="year-progress-bar"> <div class="progress-bar-fill" id="year-progress-bar-fill"></div> <div class="progress-label" id="year-progress-label"></div> </div> <p class="progress-text" id="year-progress-text"></p> </div> <div class="progress-container"> <div class="progress-bar" id="week-progress-bar"> <div class="progress-bar-fill" id="week-progress-bar-fill"></div> <div class="progress-label" id="week-progress-label"></div> </div> <p class="progress-text" id="week-progress-text"></p> </div> <div class="progress-container"> <div class="progress-bar" id="day-progress-bar"> <div class="progress-bar-fill" id="day-progress-bar-fill"></div> <div class="progress-label" id="day-progress-label"></div> </div> <p class="progress-text" id="day-progress-text"></p> </div> <div class="progress-container"> <div class="progress-bar" id="hour-progress-bar"> <div class="progress-bar-fill" id="hour-progress-bar-fill"></div> <div class="progress-label" id="hour-progress-label"></div> </div> <p class="progress-text" id="hour-progress-text"></p> </div> <script> function updateProgressBar(progressBarId, fillId, labelId, textId, percentage, text) { document.getElementById(fillId).style.width = percentage + "%"; document.getElementById(labelId).innerHTML = Math.round(percentage) + "%"; document.getElementById(textId).innerHTML = text; } var currentDate = new Date(); var currentYear = currentDate.getFullYear(); var startDate = new Date(currentYear, 0, 1); var endDate = new Date(currentYear + 1, 0, 1); var daysPassed = Math.floor((currentDate - startDate) / (1000 * 60 * 60 * 24)); var daysPassed = daysPassed +1; //fix the current day not being taken into account !! var totalDays = Math.floor((endDate - startDate) / (1000 * 60 * 60 * 24)); var yearPercentage = (daysPassed / totalDays) * 100; var currentDayOfWeek = currentDate.getDay(); if (currentDayOfWeek === 0) { currentDayOfWeek = 7; } var totalDaysOfWeek = 7; var weekPercentage = (currentDayOfWeek / totalDaysOfWeek) * 100; var currentDayOfMonth = currentDate.getDate(); var totalDaysOfMonth = new Date(currentYear, currentDate.getMonth() + 1, 0).getDate(); var dayPercentage = (currentDayOfMonth / totalDaysOfMonth) * 100; var currentHourOfDay = currentDate.getHours(); var totalHoursOfDay = 24; var hourPercentage = (currentHourOfDay / totalHoursOfDay) * 100; updateProgressBar("year-progress-bar", "year-progress-bar-fill", "year-progress-label", "year-progress-text", yearPercentage, "Days in (" + currentYear + "): " + daysPassed + "/" + totalDays); updateProgressBar("week-progress-bar", "week-progress-bar-fill", "week-progress-label", "week-progress-text", weekPercentage, "Days of the week: " + currentDayOfWeek + "/" + totalDaysOfWeek); updateProgressBar("day-progress-bar", "day-progress-bar-fill", "day-progress-label", "day-progress-text", dayPercentage, "Days of the month: " + currentDayOfMonth + "/" + totalDaysOfMonth); updateProgressBar("hour-progress-bar", "hour-progress-bar-fill", "hour-progress-label", "hour-progress-text", hourPercentage, "Hours/day: " + currentHourOfDay + "/" + totalHoursOfDay); </script> </body> _________________________________________ Arbeitsagentur Jobcenter jobsearch: ---------------------------------------------------------- <script> function searchJobs() { var params = {}; var angebotsart = document.getElementById('angebotsart').value; if (angebotsart) { params.angebotsart = angebotsart; } var wo = document.getElementById('wo').value; if (wo) { params.wo = wo; } var umkreis = document.getElementById('umkreis').value; if (umkreis) { params.umkreis = umkreis; } var was = document.getElementById('was').value; if (was) { params.was = was; } var zeitarbeitCheckbox = document.getElementById('zeitarbeit'); if (!zeitarbeitCheckbox.checked) { params.zeitarbeit = true; } var arbeitszeit = document.getElementById('arbeitszeit').value; if (arbeitszeit) { params.arbeitszeit = arbeitszeit; } var queryString = Object.keys(params).map(function(key) { return key + '=' + encodeURIComponent(params[key]); }).join('&'); var url = "https://www.arbeitsagentur.de/jobsuche/suche?" + queryString; var decodedUrl = decodeURIComponent(url); document.getElementById('url').innerHTML = '<a href="' + url + '" target="_blank">' + decodedUrl + '</a>'; window.open(url, "_blank"); } </script> </head> <body> <label for="was">Was:</label> <input type="text" id="was" placeholder="Jobtitel" value=""><br> <label for="angebotsart">Art:</label> <input type="text" id="angebotsart" placeholder="???"><br> <label for="wo">Wo:</label> <input type="text" id="wo" placeholder=""><br> <label for="umkreis">Umkreis:</label> <input type="text" id="umkreis" placeholder="25km"><br> <label for="arbeitszeit">Arbeitszeit:</label> <input type="text" id="arbeitszeit" placeholder="vz;tz;snw;ho;mj"><br> <label for="zeitarbeit">ZA:</label> <input type="checkbox" id="zeitarbeit"><br> <button onclick="searchJobs()">Search</button> <br> <br> <p>URL: <span id="url"></span></p> </body> </html> _____________________________________ DisplayYoutube channel playlists: ----------------------- <ul id="playlists"></ul> <script> // YouTube API Key var api_key = 'apikey'; // Replace with your own YouTube Data API key // YouTube Channel ID var channel_id = new URLSearchParams(window.location.search).get('channelid') || 'UCmIpOnd5BVx5Si2hp0WNKZw'; // Replace with the desired channel ID or use the default channel ID if not provided in the query string // Search term var search_term = new URLSearchParams(window.location.search).get('keyword') || ''; // Get the keyword from the query string or set it as an empty string if not provided // Retrieve playlists using YouTube Data API var playlistsContainer = document.getElementById('playlists'); function fetchPlaylists(pageToken) { var url = `https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=${channel_id}&maxResults=50&key=${api_key}`; // Add pageToken if provided if (pageToken) { url += `&pageToken=${pageToken}`; } // Make a GET request using Fetch API fetch(url) .then(response => response.json()) .then(data => { var playlists = data.items; if (playlists.length > 0) { playlists.forEach(playlist => { var playlistTitle = playlist.snippet.title; var playlistId = playlist.id; // Filter playlists based on the search term if (search_term === '' || playlistTitle.toLowerCase().includes(search_term.toLowerCase())) { var playlistLink = document.createElement('a'); playlistLink.href = `https://www.youtube.com/playlist?list=${playlistId}`; playlistLink.target = '_blank'; playlistLink.textContent = playlistTitle; var listItem = document.createElement('li'); listItem.appendChild(playlistLink); playlistsContainer.appendChild(listItem); } }); // Check if there are more playlists to fetch if (data.nextPageToken) { fetchPlaylists(data.nextPageToken); } } else { if (playlistsContainer.childElementCount === 0) { playlistsContainer.innerHTML = "<p>No playlists found for the channel with the provided criteria.</p>"; } } }) .catch(error => { console.error(error); }); } // Start fetching the playlists fetchPlaylists(); </script> </body> </html> ________________________________________ Querystring redirect protection: ------------------------------ <script> var time = 3 * 1; setInterval(function() { var seconds = time; var minutes = 0; if (seconds.toString().length == 1) { seconds = "0" + seconds; } if (minutes.toString().length == 1) { minutes = "0" + minutes; } document.getElementById("time").innerHTML = minutes + ":" + seconds; time--; if (time == 0) { var queryString = window.location.search; var params = new URLSearchParams(queryString); var encodedSgs = "c2F2ZWdhbWVz"; var decodedSgs = atob(encodedSgs); if (params.get(decodedSgs) !== null) { var encodedUrl = "aHR0cHM6Ly9teS5oaWRyaXZlLmNvbS9zaGFyZS8xZDNmazFhcW9i"; var decodedUrl = atob(encodedUrl); window.location.href = decodedUrl; } } }, 1000); </script> <div class="timer" onload="timer(1800)"> <div class="time"><strong>Redirecting in <span id="time">x seconds</span></strong></div> </div> __________________________________ Preview_cards extractor --------------------------------------- <body> <div id="previewCardImages"></div> <script> function extractPreviewCardLinks(responseText) { const pattern = /\/cache\/preview_cards\/images\/\d{3}\/\d{3}\/\d{3}\/original\/[a-f0-9]+\.(?:jpg|jpeg|png|gif)/gi; const matches = responseText.match(pattern); return matches || []; } function generateImageTags(imageUrls, domain) { let html = ''; imageUrls.forEach(imageUrl => { html += '<img src="' + domain + imageUrl + '" alt="Preview Card Image"><br>'; }); return html; } const url = 'https://mastodon.social/api/v1/accounts/109977878421486714/statuses'; fetch(url) .then(response => response.text()) .then(responseText => { const previewCards = extractPreviewCardLinks(responseText); const domain = 'https://files.mastodon.social'; const html = generateImageTags(previewCards, domain); document.getElementById('previewCardImages').innerHTML = html; }) .catch(error => { console.error('Error: Unable to fetch data.', error); }); </script> ___________________________ VanillaRSS -------------------------------- <script src="https://code.jquery.com/jquery-3.7.1.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-rss/4.3.0/jquery.rss.min.js"></script> <script> jQuery(function($) { $("#rss-feeds").rss("http://www.ost-center.com/derniers-osts-rss", { limit: 10, entryTemplate: '<div><a href="{url}" target="_blank">{title}</a>{shortBodyPlain}</div>' }); }); </script> </head> <body> <div id="rss-feeds"></div> _________________________ CORS Tester: --------------------- <!DOCTYPE html> <html> <head> <style> iframe { width: 500px; height: 300px; border: none; } </style> <script> function checkCORSStatus() { const url = document.getElementById('urlInput').value; const xhr = new XMLHttpRequest(); xhr.open('HEAD', url); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { const corsStatus = xhr.getResponseHeader('Access-Control-Allow-Origin'); const headers = xhr.getAllResponseHeaders(); const result = document.getElementById('result'); if (corsStatus) { result.innerHTML = '<strong>CORS is enabled for the URL.</strong><br>'; result.innerHTML += 'Access-Control-Allow-Origin: ' + corsStatus + '<br>'; } else { result.innerHTML = '<strong>CORS is not enabled for the URL.</strong><br>'; } result.innerHTML += '<br><strong>Response Headers:</strong><br>' + headers; } }; xhr.send(); const iframe = document.getElementById('iframe'); iframe.src = url; } </script> </head> <body> <div> <label for="urlInput">Enter URL:</label> <input type="text" id="urlInput" placeholder="https://example.com" /> <button onclick="checkCORSStatus()">Check CORS Status</button> </div> <div id="result"></div> <iframe id="iframe"></iframe> </body> </html> ______________________________ Render Steam Library: ------------------------------------ <a target="_blank" href="https://alcea-wisteria.de/PHP/0demo/2023-11-26-SteamLibraryFetch/steamfetch.php">Fetch</a><br><br> <br> <a target="_blank" href="https://steamcommunity.com/id/alceawisteria#https://steamcommunity.com/profiles/76561198119673186/games/?tab=all">[Alcea's Steam Library]</a> <style> .game { margin-bottom: 5px; display: flex; flex-direction: column; align-items: center; } .game h2 { margin-bottom: 0px; text-align: center; } .game img { width: 100%; height: 100%; object-fit: cover; } table { border-collapse: collapse; } table td, table th { padding: 0; border: none; } </style> </head> <body> <div id="game-container"></div> <script> function getQueryStringParameter(parameter) { var urlParams = new URLSearchParams(window.location.search); return urlParams.has(parameter); } fetch('https://ry3yr.github.io/steam_library.json') .then(function(response) { if (!response.ok) { throw new Error('Error loading JSON file: ' + response.status); } return response.json(); }) .then(function(data) { var games = data.response.games; // Sort games alphabetically if "alphabetical" query string parameter exists if (getQueryStringParameter('sort')) { games.sort(function(a, b) { return a.name.localeCompare(b.name); }); } var table = document.createElement('table'); var tableHead = document.createElement('thead'); var tableBody = document.createElement('tbody'); var headerRow = document.createElement('tr'); var nameHeader = document.createElement('th'); nameHeader.textContent = 'Game Name'; var appidHeader = document.createElement('th'); appidHeader.textContent = 'App ID'; var achievementsHeader = document.createElement('th'); achievementsHeader.textContent = 'Achievements'; // New header for achievements URL var playtimeHeader = document.createElement('th'); playtimeHeader.textContent = 'Playtime'; headerRow.appendChild(nameHeader); headerRow.appendChild(appidHeader); headerRow.appendChild(achievementsHeader); // Append the new header to the header row headerRow.appendChild(playtimeHeader); // Append the playtime header to the header row tableHead.appendChild(headerRow); table.appendChild(tableHead); games.forEach(function(game) { var row = document.createElement('tr'); var nameCell = document.createElement('td'); var appidCell = document.createElement('td'); var achievementsCell = document.createElement('td'); // New cell for achievements URL var playtimeCell = document.createElement('td'); var gameLink = document.createElement('a'); gameLink.href = 'https://store.steampowered.com/app/' + game.appid; gameLink.textContent = game.name; gameLink.target = '_blank'; // Open link in a new tab or window //nameCell.appendChild(gameLink); appidCell.textContent = game.appid; achievementsCell.innerHTML = `<a target="_blank" href="https://steamcommunity.com/id/alceawisteria/stats/${game.appid}/achievements/">Achievements</a> <a id="transp" target="_blank" href="https://alcea-wisteria.de/PHP/0demo/2024-01-14-Lastplayed/lastplayed.php?gamename=${game.name}" style="color: transparent;">→</a>`; playtimeCell.textContent = game.playtime_forever; var image = document.createElement('img'); image.src = `https://cdn.cloudflare.steamstatic.com/steam/apps/${game.appid}/header.jpg`; image.style.width = '200px'; image.style.height = '35px'; image.style.objectFit = 'cover'; var imageLink = document.createElement('a'); imageLink.href = gameLink.href; imageLink.target = '_blank'; imageLink.appendChild(image); var container = document.createElement('div'); container.classList.add('game'); container.appendChild(imageLink); container.appendChild(nameCell); row.appendChild(container); row.appendChild(appidCell); row.appendChild(achievementsCell); row.appendChild(playtimeCell); tableBody.appendChild(row); }); table.appendChild(tableBody); document.getElementById('game-container').appendChild(table); }) .catch(function(error) { console.error('Error loading/parsing JSON file:', error); }); </script> ______________________________ Print txt file to div (ascii-art): ---------------------- <style> #content { width: 2000px; height: 2000px; overflow: hidden; transform-origin: top left; } #content pre { white-space: pre-wrap; word-wrap: break-word; transform: scale(1); transform-origin: top left; } </style> </head> <body> <div id="content"></div> <script> const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); const txtUrl = urlParams.get('txt'); let fetchUrl = 'https://ry3yr.github.io/alceaasciipfp.txt'; if (txtUrl) { fetchUrl = txtUrl; } fetch(fetchUrl) .then(response => response.text()) .then(data => { console.log(data); const contentDiv = document.getElementById('content'); const lines = data.split('\n'); const redrawContent = (lineIndex) => { if (lineIndex >= lines.length) { return; } const line = lines[lineIndex]; const preElement = document.createElement('pre'); preElement.textContent = line; let rainbowColor; if (window.location.search.includes("rainbow")) { const lineIndex = 5; rainbowColor = `hsl(${lineIndex * 10}, 100%, 50%)`; } else { rainbowColor = "default-color"; } preElement.style.color = rainbowColor; contentDiv.appendChild(preElement); const scale = Math.min(contentDiv.offsetWidth / preElement.offsetWidth, contentDiv.offsetHeight / preElement.offsetHeight); preElement.style.transform = `scale(${scale})`; setTimeout(() => { redrawContent(lineIndex + 1); }, 200); }; redrawContent(0); }) .catch(error => { console.error('Error:', error); }); </script> </body> </html> __________________________________________________________ Mastodon Thread as comment system: ----------------------------------------------------------- <script type="module"> const styles = ` :root { --font-color: #5d686f; --font-size: 1.0rem; --block-border-width: 1px; --block-border-radius: 3px; --block-border-color: #ededf0; --block-background-color: #f7f8f8; --comment-indent: 40px; } #mastodon-comments-list { margin: 0 auto; } .mastodon-comment { background-color: var(--block-background-color); border-radius: var(--block-border-radius); border: var(--block-border-width) var(--block-border-color) solid; padding: 20px; margin-bottom: 1.5rem; display: flex; flex-direction: column; color: var(--font-color); font-size: var(--font-size); } .mastodon-comment p { margin-bottom: 0px; } .mastodon-comment .author { padding-top:0; display:flex; } .mastodon-comment .author a { text-decoration: none; } .mastodon-comment .author .avatar img { margin-right:1rem; min-width:60px; border-radius: 5px; } .mastodon-comment .author .details { display: flex; flex-direction: column; } .mastodon-comment .author .details .name { font-weight: bold; } .mastodon-comment .author .details .user { color: #5d686f; font-size: medium; } .mastodon-comment .author .date { margin-left: auto; font-size: small; } .mastodon-comment .content { margin: 15px 20px; } .mastodon-comment .attachments { margin: 0px 10px; } .mastodon-comment .attachments > * { margin: 0px 10px; } .mastodon-comment .attachments img { max-width: 100%; } .mastodon-comment .content p:first-child { margin-top:0; margin-bottom:0; } .mastodon-comment .status > div { display: inline-block; margin-right: 15px; } .mastodon-comment .status a { color: #5d686f; text-decoration: none; } .mastodon-comment .status .replies.active a { color: #003eaa; } .mastodon-comment .status .reblogs.active a { color: #8c8dff; } .mastodon-comment .status .favourites.active a { color: #ca8f04; } `; class MastodonComments extends HTMLElement { constructor() { super(); this.host = this.getAttribute("host"); this.user = this.getAttribute("user"); this.tootId = this.getAttribute("tootId"); this.commentsLoaded = false; const styleElem = document.createElement("style"); styleElem.innerHTML = styles; document.head.appendChild(styleElem); } connectedCallback() { this.innerHTML = ` <h2>Comments</h2> <noscript> <div id="error"> Please enable JavaScript to view the comments powered by the Fediverse. </div> </noscript> <p>You can use your Fediverse (i.e. Mastodon, among many others) account to reply to this <a class="link" href="https://${this.host}/@${this.user}/${this.tootId}">post</a>. </p> <p id="mastodon-comments-list"></p> `; const comments = document.getElementById("mastodon-comments-list"); const rootStyle = this.getAttribute("style"); if (rootStyle) { comments.setAttribute("style", rootStyle); } this.respondToVisibility(comments, this.loadComments.bind(this)); } escapeHtml(unsafe) { return (unsafe || "") .replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#039;"); } toot_active(toot, what) { var count = toot[what + "_count"]; return count > 0 ? "active" : ""; } toot_count(toot, what) { var count = toot[what + "_count"]; return count > 0 ? count : ""; } user_account(account) { var result = `@${account.acct}`; if (account.acct.indexOf("@") === -1) { var domain = new URL(account.url); result += `@${domain.hostname}`; } return result; } render_toots(toots, in_reply_to, depth) { var tootsToRender = toots .filter((toot) => toot.in_reply_to_id === in_reply_to) .sort((a, b) => a.created_at.localeCompare(b.created_at)); tootsToRender.forEach((toot) => this.render_toot(toots, toot, depth)); } render_toot(toots, toot, depth) { toot.account.display_name = this.escapeHtml(toot.account.display_name); toot.account.emojis.forEach((emoji) => { toot.account.display_name = toot.account.display_name.replace( `:${emoji.shortcode}:`, `<img src="${this.escapeHtml(emoji.static_url)}" alt="Emoji ${ emoji.shortcode }" height="20" width="20" />`, ); }); const mastodonComment = `<div class="mastodon-comment" style="margin-left: calc(var(--comment-indent) * ${depth})"> <div class="author"> <div class="avatar"> <img src="${this.escapeHtml( toot.account.avatar_static, )}" height=60 width=60 alt=""> </div> <div class="details"> <a class="name" href="${toot.account.url}" rel="nofollow">${ toot.account.display_name }</a> <a class="user" href="${ toot.account.url }" rel="nofollow">${this.user_account(toot.account)}</a> </div> <a class="date" href="${ toot.url }" rel="nofollow">${toot.created_at.substr( 0, 10, )} ${toot.created_at.substr(11, 8)}</a> </div> <div class="content">${toot.content}</div> <div class="attachments"> ${toot.media_attachments .map((attachment) => { if (attachment.type === "image") { return `<a href="${attachment.url}" rel="nofollow"><img src="${ attachment.preview_url }" alt="${this.escapeHtml(attachment.description)}" /></a>`; } else if (attachment.type === "video") { return `<video controls><source src="${attachment.url}" type="${attachment.mime_type}"></video>`; } else if (attachment.type === "gifv") { return `<video autoplay loop muted playsinline><source src="${attachment.url}" type="${attachment.mime_type}"></video>`; } else if (attachment.type === "audio") { return `<audio controls><source src="${attachment.url}" type="${attachment.mime_type}"></audio>`; } else { return `<a href="${attachment.url}" rel="nofollow">${attachment.type}</a>`; } }) .join("")} </div> <div class="status"> <div class="replies ${this.toot_active(toot, "replies")}"> <a href="${ toot.url }" rel="nofollow"><i class="fa fa-reply fa-fw"></i>${this.toot_count( toot, "replies", )}</a> </div> <div class="reblogs ${this.toot_active(toot, "reblogs")}"> <a href="${ toot.url }" rel="nofollow"><i class="fa fa-retweet fa-fw"></i>${this.toot_count( toot, "reblogs", )}</a> </div> <div class="favourites ${this.toot_active(toot, "favourites")}"> <a href="${ toot.url }" rel="nofollow"><i class="fa fa-star fa-fw"></i>${this.toot_count( toot, "favourites", )}</a> </div> </div> </div>`; var div = document.createElement("div"); div.innerHTML = typeof DOMPurify !== "undefined" ? DOMPurify.sanitize(mastodonComment.trim()) : mastodonComment.trim(); document .getElementById("mastodon-comments-list") .appendChild(div.firstChild); this.render_toots(toots, toot.id, depth + 1); } loadComments() { if (this.commentsLoaded) return; document.getElementById("mastodon-comments-list").innerHTML = "Loading comments from the Fediverse..."; let _this = this; fetch( "https://" + this.host + "/api/v1/statuses/" + this.tootId + "/context", ) .then((response) => response.json()) .then((data) => { if ( data["descendants"] && Array.isArray(data["descendants"]) && data["descendants"].length > 0 ) { document.getElementById("mastodon-comments-list").innerHTML = ""; _this.render_toots(data["descendants"], _this.tootId, 0); } else { document.getElementById("mastodon-comments-list").innerHTML = "<p>Not comments found</p>"; } _this.commentsLoaded = true; }); } respondToVisibility(element, callback) { var options = { root: null, }; var observer = new IntersectionObserver((entries, observer) => { entries.forEach((entry) => { if (entry.intersectionRatio > 0) { callback(); } }); }, options); observer.observe(element); } } customElements.define("mastodon-comments", MastodonComments); </script> <div id="comments_thread"></div> <mastodon-comments host="pb.todon.de" user="alcea" tootId="111359759683825226"></mastodon-comments> ____________________________________ Load external html into dom / cross: -------------------------------------------- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ var baseUrl = "https://ry3yr.github.io/mtdalceacomment"; $("#mtdcomm").load(baseUrl + ""); }); </script> <div class="formClass"> <div id="mtdcomm"> </div> </div> _____________________________ AdblockDetect: ------------------------ <!DOCTYPE html> <html> <head> <style> .message { display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); padding: 20px; background-color: #fff; border: 1px solid #ccc; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3); z-index: 9999; } .message.show { display: block; } </style> </head> <body> <p class="message">..</p> <script> fetch('https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js').then(() => { document.getElementsByClassName('message')[0].innerHTML = 'Adblock disabled.. Consider installing one !'; document.getElementsByClassName('message')[0].classList.add('no-ab'); document.getElementsByClassName('message')[0].classList.add('show'); }).catch(() => { document.getElementsByClassName('message')[0].innerHTML = 'Adblock detected! Good Job !<br>Party time !'; document.getElementsByClassName('message')[0].classList.add('ab'); document.getElementsByClassName('message')[0].classList.add('show'); }); document.addEventListener('click', function(event) { var message = document.getElementsByClassName('message')[0]; if (event.target !== message && !message.contains(event.target)) { message.classList.remove('show'); } }); </script> </body> </html> ______________________________________________ Advanced Mastodon & Akkoma Timeline / TL render (with querystring support): (complex6) ------------------------------------------------------------------------------------------------------------ <a href="?instance=mastodon.social&userid=109977878421486714">Ryedai</a> <a href="?instance=awau.social&userid=111347725791284150">AlceaAwau</a> <a href="?instance=pb.todon.de&userid=109629985010224381">Alcea</a> <a href="?instance=sapphic.engineer&userid=peng">[Akkoma]</a> <body> <div id="feed"></div> <script> function getQueryStringParams(url) { const params = {}; const urlParams = new URLSearchParams(url); for (const [key, value] of urlParams) { params[key] = value; } return params; } // Get the query parameters from the URL const queryParams = getQueryStringParams(window.location.search); const instance = queryParams.instance || "pb.todon.de"; const userid = queryParams.userid || "109629985010224381"; // Function to replace emoji shortcodes with images function replaceEmojis(content, customEmojis) { customEmojis.forEach(customEmoji => { const shortcode = customEmoji.shortcode; const url = customEmoji.url; const shortcodePattern = new RegExp(':' + shortcode + ':', 'g'); const emojiTag = '<img src="' + url + '" alt="' + shortcode + '" width="20px">'; content = content.replace(shortcodePattern, emojiTag); }); return content; } // Function to fetch data from the selected API URL function fetchData(apiUrl) { const accessToken = 'your-access-token'; fetch(apiUrl, { headers: { 'Authorization': 'Bearer ' + accessToken } }) .then(response => response.json()) .then(data => { // Clear the feed before appending new content document.getElementById('feed').innerHTML = ''; data.forEach(status => { let content = replaceEmojis(status.content, customEmojis); let media = ''; let avatar = ''; let tootLink = ''; // Check for YouTube video link const youtubeRegex = /https?:\/\/(www\.)?(m\.)?youtube\.com\/watch\?v=([a-zA-Z0-9_-]{11})/; const invidiousRegex = /https?:\/\/(www\.)?(m\.)?super8\.absturztau\.be\/watch\?v=([-a-zA-Z0-9_]{11})/; const youtubeMatch = status.content.match(youtubeRegex) || status.content.match(invidiousRegex); if (youtubeMatch) { // Extract video ID from YouTube link const videoId = youtubeMatch[3]; // Create embedded player for YouTube video media = `<div><iframe width="560" height="315" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allowfullscreen></iframe></div>`; } else { // Check for Pixiv artwork link const pixivRegex = /https?:\/\/(?:www\.)?pixiv\.net\/(?:en\/)?artworks\/(\d+)/; const pixivMatch = status.content.match(pixivRegex); if (pixivMatch) { // Extract artwork ID from Pixiv link const artworkId = pixivMatch[1]; // Create image preview for Pixiv artwork media = `<div><img src="https://embed.pixiv.net/decorate.php?illust_id=${artworkId}&mode=sns-automator" width="50%"></div>`; } else { const tenorRegex = /https?:\/\/(?:www\.)?tenor\.com\/view\/[a-zA-Z0-9-]+-(\d+)/; const tenorMatch = status.content.match(tenorRegex); if (tenorMatch) { // Extract Tenor.com video ID const videoId = tenorMatch[1]; // Create embedded player for Tenor.com video media = `<div><iframe src="https://tenor.com/embed/${videoId}" frameborder="0" allowfullscreen="true" width="100%" height="400px"></iframe></div>`; } else { // Check for Dailymotion video link const dailymotionRegex = /https?:\/\/(www\.)?dailymotion\.com\/video\/([a-zA-Z0-9_-]+)/; const dailymotionMatch = status.content.match(dailymotionRegex); if (dailymotionMatch) { const videoId = dailymotionMatch[2]; media = `<div><iframe frameborder="0" width="480" height="270" src="https://www.dailymotion.com/embed/video/${videoId}?autoplay=0" allowfullscreen allow="autoplay"></iframe></div>`; }else{ // Check for Vidlii video link const vidliiRegex = /https?:\/\/(www\.)?(m\.)?vidlii\.com\/watch\?v=([a-zA-Z0-9_-]+)/; const vidliiMatch = status.content.match(vidliiRegex); if (vidliiMatch) { const videoId = vidliiMatch[3]; media = `<iframe allowfullscreen src="https://www.vidlii.com/embed?v=${videoId}" frameborder="0" width="640" height="360"></iframe><br>`; }else{ // Check Soundcloud Link const soundcloudRegex = /https?:\/\/(m\.)?soundcloud\.com\/([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_-]+)/; const soundcloudMatch = status.content.match(soundcloudRegex); if (soundcloudMatch) { const soundcloudUrl = `https://w.soundcloud.com/player/?url=${encodeURIComponent(soundcloudMatch[0] )}&color=0066cc&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`; //media = `<iframe width="100%" height="300" scrolling="no" frameborder="no" allow="autoplay" src="${soundcloudUrl}"></iframe>`; media = `<iframe allowfullscreen src="${status.url}/embed" class="mastodon-embed" style="max-width: 100%; border: 0" width="600" height=400"></iframe><script src="embed.js" async><\/\script><br>`; } else { // Check for imgbb image URLs in the status content const imageRegex = /(https?:\/\/(?:www\.)?i\.ibb\.co\/[^ ]+\.(?:jpg|png|gif|bmp))/g; const imageMatches = status.content.match(imageRegex); if (imageMatches) { media += '<div>'; imageMatches.forEach(url => { media += '<img src="' + url + '" width="50%"><br>'; }); media += '</div>'; } } } } } } } // Check for video and audio attachments if (status.media_attachments.length > 0) { media = '<div>'; status.media_attachments.forEach(attachment => { if (attachment.type === 'image') { media += '<img src="' + attachment.url + '" width="50%"><br>'; } else if (attachment.type === 'video') { media += '<video src="' + attachment.url + '" controls width="50%"></video><br>'; } else if (attachment.type === 'audio') { media += '<audio src="' + attachment.url + '" controls></audio><br>'; } }); media += '</div>'; } // Check for spoiler tag if (status.url.includes('activity')) { avatar = '<!--<details><summary>Avatar (spoiler)</summary><img src="' + status.account.avatar + '" width="100px"></details>--><br>'; tootLink = '<!--<details><summary>View on Mastodon (spoiler)</summary><a href="' + status.url + '" target="_blank">Click here to view activity</a></details>-->'; } else { avatar = '<img src="' + status.account.avatar + '" width="100px"><br>'; tootLink = '<a href="' + status.url + '" target="_blank">View on Mastodon</a>'; } // Get the date of the status const date = new Date(status.created_at); // Append content to feed const contentHtml = `<div>${content}</div>`; const statusHtml = `${contentHtml}${media}${avatar}${tootLink}&nbsp;${date.toLocaleString()}<hr>`; document.getElementById('feed').innerHTML += statusHtml; }); }) .catch(error => console.error(error)); } // Add emoji renderer const emojiEndpoint = `https://${instance}/api/v1/custom_emojis`; fetch(emojiEndpoint) .then(response => response.json()) .then(customEmojis => { // Store custom emojis for later use window.customEmojis = customEmojis; // Event listener for radio button change const radioButtons = document.querySelectorAll('input[name="apiUrl"]'); radioButtons.forEach(radioButton => { radioButton.addEventListener('change', function() { const selectedApiUrl = this.value; fetchData(selectedApiUrl); }); }); // Initial fetch using the default API URL const defaultApiUrl = `https://${instance}/api/v1/accounts/${userid}/statuses`; fetchData(defaultApiUrl); }); </script> </body> _________________________________________ Display mutes for account (rqs apikey): -------------------------------------------------------- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { var entities = []; var muteCount = 0; // Variable to store the number of mutes function fetchEntities(url) { $.ajax({ url: url, type: 'GET', dataType: 'json', headers: { 'Authorization': 'Bearer apikeyhere' }, success: function(response, textStatus, xhr) { var newEntities = response; for (var i = 0; i < newEntities.length; i++) { var entity = newEntities[i]; entities.push(entity); muteCount++; // Increment the mute count } var linkHeader = xhr.getResponseHeader('Link'); var nextLink = extractLinkUrl(linkHeader, 'next'); if (entities.length >= 1000) { // Render the fetched entities renderEntities(); } else if (nextLink) { // Fetch the next set of entities fetchEntities(nextLink); } else { console.log('Finished fetching entities'); // Render the fetched entities renderEntities(); } }, error: function(xhr, status, error) { console.log('Error: ' + error); } }); } function extractLinkUrl(linkHeader, rel) { var links = linkHeader.split(','); for (var i = 0; i < links.length; i++) { var link = links[i].trim(); var regex = /<([^>]+)>;\s*rel="([^"]+)"/g; var match = regex.exec(link); if (match && match[2] === rel) { return match[1]; } } return null; } function renderEntities() { // Display the mute count at the top var muteCountHtml = '<p>Mute Count: ' + muteCount + '</p>'; $('#muteCount').html(muteCountHtml); for (var i = 0; i < entities.length; i++) { var entity = entities[i]; var entityHtml = '<p>'; entityHtml += '<a target="_blank" href="' + entity.url + '">' + entity.url + '</a><br>'; //entityHtml += 'Date: ' + entity.created_at + '<br>'; entityHtml += '</p>'; $('#entities').append(entityHtml); } } // Start fetching entities from the initial URL var initialUrl = 'https://pb.todon.de/api/v1/mutes'; fetchEntities(initialUrl); }); </script> </head> <body> <div id="muteCount"></div> <!-- Display the mute count here --> <div id="entities"></div> </body> </html> _________________________________ MTD Graph posts over last 7 days: --------------------------------- Posts/Day for @alcea@pb.todon.de<br> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <style> canvas { display: block; max-width: 800px; margin: 0 auto; } </style> </head> <body> <canvas id="dateChart"></canvas> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <div id="entities"></div> <script> $(document).ready(function() { var endpoint = 'https://pb.todon.de/api/v1/accounts/109629985010224381/statuses'; var entities = []; var dates = []; fetchEntities(); function fetchEntities() { var url = endpoint; if (entities.length > 0) { var linkHeader = '<https://pb.todon.de/api/v1/accounts/109629985010224381/statuses?max_id=' + entities[entities.length - 1].id + '>; rel="next"'; $.ajaxSetup({ headers: { 'Link': linkHeader } }); } $.ajax({ url: url, type: 'GET', dataType: 'json', headers: { 'Authorization': 'Bearer token' }, success: function(response, textStatus, xhr) { var newEntities = response; for (var i = 0; i < newEntities.length; i++) { var entity = newEntities[i]; entities.push(entity); // Filter out the date var date = new Date(entity.created_at); dates.push(date); } var linkHeader = xhr.getResponseHeader('Link'); var nextLink = extractLinkUrl(linkHeader, 'next'); if (entities.length >= 200) { // Render the fetched entities renderEntities(); // Plot the dates plotDates(); } else if (nextLink) { // Fetch the next set of entities endpoint = nextLink; fetchEntities(); } else { console.log('Finished fetching 200 entities'); // Render the fetched entities renderEntities(); // Plot the dates plotDates(); } }, error: function(xhr, status, error) { console.log('Error: ' + error); } }); } function extractLinkUrl(linkHeader, rel) { var links = linkHeader.split(','); for (var i = 0; i < links.length; i++) { var link = links[i].trim(); var regex = /<([^>]+)>;\s*rel="([^"]+)"/g; var match = regex.exec(link); if (match && match[2] === rel) { return match[1]; } } return null; } function renderEntities() { for (var i = 0; i < entities.length; i++) { var entity = entities[i]; // Render the URL and date on the page var entityHtml = '<p>'; //entityHtml += 'URL: <a href="' + entity.url + '">' + entity.url + '</a><br>'; //entityHtml += 'Date: ' + entity.created_at + '<br>'; //entityHtml += '</p>'; $('#entities').append(entityHtml); } } function plotDates() { // Filter the dates for the last 7 days var today = new Date(); var lastSevenDays = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000); var filteredDates = dates.filter(function(date) { return date >= lastSevenDays && date <= today; }); // Count the occurrences of each date var dateCounts = {}; filteredDates.forEach(function(date) { var dateString = date.toISOString().split('T')[0]; dateCounts[dateString] = (dateCounts[dateString] || 0) + 1; }); // Extract the dates and counts as separate arrays var chartLabels = Object.keys(dateCounts); var chartData = Object.values(dateCounts); // Create the chart using Chart.js var ctx = document.getElementById('dateChart').getContext('2d'); var chart = new Chart(ctx, { type: 'line', data: { labels: chartLabels, datasets: [{ label: 'Date Counts', data: chartData, fill: false, borderColor: 'rgba(0, 123, 255,0.8)', borderWidth: 2 }] }, options: { scales: { x: { display: true, title: { display: true, text: 'Date' }, reverse: true // Add this line to reverse the x-axis }, y: { display: true, title: { display: true, text: 'Count' }, beginAtZero: true, stepSize: 1 } } } }); } }); </script> __________________________________________________ MTD Fetch more than 40 statuse (via pagination): -------------------------------------------------- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <div id="entities"></div> <script> $(document).ready(function() { var endpoint = 'https://pb.todon.de/api/v1/accounts/109629985010224381/statuses'; var entities = []; fetchEntities(); function fetchEntities() { var url = endpoint; if (entities.length > 0) { var linkHeader = '<https://pb.todon.de/api/v1/accounts/109629985010224381/statuses?max_id=' + entities[entities.length - 1].id + '>; rel="next"'; $.ajaxSetup({ headers: { 'Link': linkHeader } }); } $.ajax({ url: url, type: 'GET', dataType: 'json', headers: { 'Authorization': 'Bearer token' }, success: function(response, textStatus, xhr) { var newEntities = response; for (var i = 0; i < newEntities.length; i++) { var entity = newEntities[i]; entities.push(entity); } var linkHeader = xhr.getResponseHeader('Link'); var nextLink = extractLinkUrl(linkHeader, 'next'); if (entities.length >= 200) { // Render the fetched entities renderEntities(); } else if (nextLink) { // Fetch the next set of entities endpoint = nextLink; fetchEntities(); } else { console.log('Finished fetching 200 entities'); // Render the fetched entities renderEntities(); } }, error: function(xhr, status, error) { console.log('Error: ' + error); } }); } function extractLinkUrl(linkHeader, rel) { var links = linkHeader.split(','); for (var i = 0; i < links.length; i++) { var link = links[i].trim(); var regex = /<([^>]+)>;\s*rel="([^"]+)"/g; var match = regex.exec(link); if (match && match[2] === rel) { return match[1]; } } return null; } function renderEntities() { for (var i = 0; i < entities.length; i++) { var entity = entities[i]; // Render the URL and date on the page var entityHtml = '<p>'; entityHtml += 'URL: <a href="' + entity.url + '">' + entity.url + '</a><br>'; entityHtml += 'Date: ' + entity.created_at + '<br>'; entityHtml += '</p>'; $('#entities').append(entityHtml); } } }); </script> __________________________________________ Find Emojo/Blobcat Game: ----------------------------------------- <a target="_blank" href="?instance=mastodon.social&random=no">QueryString</a><br><br> <style> .emoji { width: 45px; cursor: pointer; } .highlight { outline: 2px solid green; } .mirror { transform: scaleX(1); } </style> </head> <body> <div id="emojiContainer"></div> <script> document.addEventListener('DOMContentLoaded', function() { var customEmojis = []; function fetchEmojis() { var endpoint = 'https://pb.todon.de/api/v1/custom_emojis'; var urlParams = new URLSearchParams(window.location.search); var instanceParam = urlParams.get('instance'); if (instanceParam) { endpoint = 'https://' + instanceParam + '/api/v1/custom_emojis'; } fetch(endpoint) .then(function(response) { return response.json(); }) .then(function(data) { customEmojis = data; displayEmojis(); }); } function displayEmojis() { var emojiContainer = document.getElementById('emojiContainer'); emojiContainer.innerHTML = ''; var urlParams = new URLSearchParams(window.location.search); var randomParam = urlParams.get('random'); var shouldRandomize = randomParam !== 'no'; var shuffledEmojis = shouldRandomize ? customEmojis.sort(function() { return 0.5 - Math.random(); }) : customEmojis; shuffledEmojis.forEach(function(customEmoji) { var shortcode = customEmoji.shortcode; var url = customEmoji.url; var emojiElement = document.createElement('img'); emojiElement.src = url; emojiElement.alt = shortcode; emojiElement.width = '45px'; emojiElement.title = shortcode; emojiElement.classList.add('emoji'); emojiElement.addEventListener('click', function() { emojiElement.classList.add('highlight'); setTimeout(function() { emojiElement.classList.remove('highlight'); checkEmojiFound(customEmoji); }, 1000); }); emojiContainer.appendChild(emojiElement); }); var randomIndex = Math.floor(Math.random() * customEmojis.length); var randomEmoji = customEmojis[randomIndex]; var emojiToFind = document.createElement('div'); emojiToFind.classList.add('emoji-to-find'); var emojiToFindImage = document.createElement('img'); emojiToFindImage.src = randomEmoji.url; emojiToFindImage.alt = randomEmoji.shortcode; emojiToFindImage.width = '45px'; emojiToFindImage.title = randomEmoji.shortcode; emojiToFind.appendChild(emojiToFindImage); var emojiToFindText = document.createElement('p'); //emojiToFindText.textContent = 'Find this emoji: ' + randomEmoji.shortcode; emojiToFind.appendChild(emojiToFindText); emojiContainer.insertBefore(emojiToFind, emojiContainer.firstChild); var emojiImages = document.querySelectorAll('.emoji'); var randomEmojiImage = emojiImages[Math.floor(Math.random() * emojiImages.length)]; var emojiToFindImageClone = randomEmojiImage.cloneNode(true); emojiToFindImageClone.classList.add('mirror'); emojiToFindImage.parentNode.replaceChild(emojiToFindImageClone, emojiToFindImage); } function checkEmojiFound(emoji) { var emojiContainer = document.getElementById('emojiContainer'); var emojiToFind = emojiContainer.querySelector('.emoji-to-find'); var foundEmoji = emojiToFind.querySelector('img').alt; if (emoji.shortcode === foundEmoji) { emojiContainer.removeChild(emojiToFind); fetchEmojis(); } } fetchEmojis(); }); </script> _____________________________________________ Redirect to Mastodon home JS Scriptlet: --------------------------------------------------------------- javascript:(function() { var encodedUrl = encodeURIComponent(window.location.href); var redirectUrl = "https://alcea-wisteria.de/PHP/0demo/2023-10-22-MastodonTootSearch/searchmastourl.php?search=" + encodedUrl + "&pbUrl=https%3A%2F%2Fpb.todon.de&apikey=apikeyhere"; window.location.href = redirectUrl; })(); ________________________________________________ Multifeed Mastodon Scroll base (with "open at home", if ?takemehome is in the url) -------------------------------------------- <!--https://pb.todon.de/@alcea/111285111844791912--https://fedionfire.stream/--> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style> #messageContainer { height: 100%; overflow: auto; border: 1px solid #ccc; padding: 10px; } .message { display: flex; align-items: center; margin-bottom: 10px; padding: 5px; background-color: #f5f5f5; border: 1px solid #ddd; } .avatar { width: 40px; height: 40px; border-radius: 50%; margin-right: 10px; } .message-content { flex-grow: 1; } .message-link { color: #007bff; text-decoration: none; } </style> </head> <body> <div id="messageContainer"></div> <script> $(document).ready(function() { function fetchMastodonStatuses(instanceUrls) { const limit = 35; instanceUrls.forEach(function(instanceUrl) { const url = `${instanceUrl}/api/v1/timelines/public?limit=${limit}&exclude_bots=true`; $.ajax({ url: url, method: 'GET', dataType: 'json', success: function(data) { const statuses = data; parseMastodonStatuses(statuses); }, error: function(error) { console.error('Error fetching Mastodon statuses:', error); } }); }); } function parseMastodonStatuses(statuses) { var messageContainer = $('#messageContainer'); statuses.forEach(function(status) { var avatarUrl = status.account.avatar; var displayName = status.account.display_name; var content = status.content; //var postUrl = status.url; //var postUrl = `https://alcea-wisteria.de/PHP/0demo/2023-10-22-MastodonTootSearch/searchmastourl.php?search=${encodeURIComponent(status.url)}&pbUrl=https://pb.todon.de&apikey=apikey`; //var postUrl = window.location.search.includes('takemehome') ? `https://alcea-wisteria.de/PHP/0demo/2023-10-22-MastodonTootSearch/searchmastourl.php?search=${encodeURIComponent(status.url)}&pbUrl=https://pb.todon.de&apikey=5x1Wr4gL-rM_Q0akdLZIQrcO2PBhEby39HatYQFmVvs` : status.url; var postUrl = window.location.search.includes('takemehome') && !status.url.includes('notes') && !status.url.includes('notice') ? `https://alcea-wisteria.de/PHP/0demo/2023-10-22-MastodonTootSearch/searchmastourl.php?search=${encodeURIComponent(status.url)}&pbUrl=https://pb.todon.de&apikey=5x1Wr4gL-rM_Q0akdLZIQrcO2PBhEby39HatYQFmVvs` : status.url; var message = $('<div>').addClass('message'); var avatar = $('<img>').attr('src', avatarUrl).addClass('avatar'); var messageContent = $('<div>').addClass('message-content').html(content); var link = $('<a>').attr('href', postUrl).attr('target', '_blank').addClass('message-link').text('View Post'); message.append(avatar); message.append(messageContent); messageContent.append('<br>'); messageContent.append(link); messageContainer.append(message); }); } var instanceUrls = ['https://mastodon.social', 'https://pb.todon.de', 'https://kopimi.space', 'https://sunnygarden.org', 'https://mementomori.social']; fetchMastodonStatuses(instanceUrls); }); </script> </body> </html> __________________________ Mastodon Public Timeline(s) (with "open at home" feature): -------------------------------------------------- <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <select id="instanceDropdown"> <option value="https://pb.todon.de">pb.todon.de</option> <option value="https://mastodon.social">mastodon.social</option> <option value="https://kopimi.space">kopimi.space</option> <option value="https://sunny.garden">Sunny.Garden</option> </select> <label for="localCheckbox"> <input type="checkbox" id="localCheckbox"> Local </label> <input type="text" id="textboxUrl" placeholder="Enter home instance URL"> <input type="password" id="apikey" placeholder="API key"> <div id="statuses"></div> <script> // Function to fetch Mastodon statuses based on the selected instance and local checkbox state function fetchMastodonStatuses(instanceUrl) { const localCheckbox = $('#localCheckbox').prop('checked'); const url = `${instanceUrl}/api/v1/timelines/public?limit=50${localCheckbox ? '&local=true' : ''}`; $.ajax({ url: url, method: 'GET', dataType: 'json', headers: { 'Authorization': `Bearer ${$('#apikey').val()}` }, success: function(data) { const statuses = data; parseMastodonStatuses(statuses); }, error: function(error) { console.error('Error fetching Mastodon statuses:', error); } }); } // Function to handle shortcode function handleShortcode(shortcode) { // Your shortcode handling logic here console.log(`Handling shortcode: ${shortcode}`); } // Function to parse Mastodon statuses function parseMastodonStatuses(statuses) { $('#statuses').empty(); // Clear existing statuses const textboxUrl = $('#textboxUrl').val(); statuses.forEach((status) => { // Check if the status has a shortcode if (status.shortcode) { handleShortcode(status.shortcode); } // Process other status data as needed console.log(`Processing status: ${status.content}`); // Create a link to the status const statusLink = `${status.content}`; const apikey = $('#apikey').val(); // Check if the textbox URL is already part of the status URL const url = textboxUrl && !status.url.includes(textboxUrl) && !status.url.includes('notes' || 'plasmatrap') ? `https://alcea-wisteria.de/PHP/0demo/2023-10-22-MastodonTootSearch/searchmastourl.php?search=${status.url}&pbUrl=${textboxUrl}&apikey=${apikey}` : status.url; // Render the status and link on the page $('#statuses').append(`${status.content} <a href="${url}" target="_blank">${status.account.display_name}</a></p><hr>`); }); } // Function to handle dropdown change event function handleDropdownChange() { // Get the selected instance URL const selectedInstance = $('#instanceDropdown').val(); // Fetch Mastodon statuses for the selected instance fetchMastodonStatuses(selectedInstance); } // Add event listener to the dropdown $('#instanceDropdown').on('change', handleDropdownChange); // Add event listeners to the URL and API key textboxes $('#textboxUrl, #apikey').on('input', function() { // Call the fetchMastodonStatuses function to refetch the current state const selectedInstance = $('#instanceDropdown').val(); fetchMastodonStatuses(selectedInstance); }); // Initial fetch for the default instance const defaultInstance = 'https://pb.todon.de'; fetchMastodonStatuses(defaultInstance); </script> </body> </html> <script> window.onload = function() { const homeUrlParam = new URLSearchParams(window.location.search).get('homeurl'); const apiKeyParam = new URLSearchParams(window.location.search).get('apikey'); const homeUrlInput = document.getElementById('textboxUrl'); const apiKeyInput = document.getElementById('apikey'); if (homeUrlParam && apiKeyParam) { homeUrlInput.value = homeUrlParam; apiKeyInput.value = apiKeyParam; } }; </script> <!--php-helper--> <a href="?search=https://sunny.garden/@Iva852/109293246960188756&pbUrl=https://pb.todon.de&apikey=orfvAYfV1Sy4DtJCYN32J48Mbjh50kFTywcWEWmLHSM">test</a><br> <?php // Check if the API key is submitted if (isset($_POST['apikey'])) { $apiKey = $_POST['apikey']; $pbUrl = $_POST['pbUrl']; $search = $_POST['url']; $url = $pbUrl . '/api/v2/search/?q=' . urlencode($search) . '&limit=1&resolve=true'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $apiKey ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute the request $response = curl_exec($ch); if (curl_errno($ch)) { echo 'Error: ' . curl_error($ch); } curl_close($ch); $data = json_decode($response, true); if (isset($data['statuses'][0]['id'])) { $id = $data['statuses'][0]['id']; $urlParts = parse_url($search); $pathParts = explode('/', trim($urlParts['path'], '/')); $username = $pathParts[0]; $domain = $urlParts['host']; //echo 'Search URL: ' . $search . '<br>'; //echo 'Username: ' . $username . '<br>'; //echo 'Domain: ' . $domain . '<br>'; //echo 'ID: ' . $id . '<br>'; $newUrl = $pbUrl . '/' . $username . '@' . $domain . '/' . $id; //echo 'New URL: ' . $newUrl; echo 'New URL: <a href="' . $newUrl . '">' . $newUrl . '</a>'; } else { echo 'ID not found in the response.'; } } ?> <!-- HTML form to input the API key, $pbUrl, and URL --> <form method="POST" action=""> <label for="apikey">API Key:</label> <input type="password" id="apikey" name="apikey" required> <br> <label for="pbUrl">pbUrl:</label> <input type="text" id="pbUrl" name="pbUrl" required> <br> <label for="url">URL:</label> <input type="text" id="url" name="url" required> <input type="submit" value="Submit"> </form> <script> window.onload = function() { const urlParams = new URLSearchParams(window.location.search); const stop = urlParams.get('stop'); if (stop) { return; // Stop the script right at the beginning } const search = urlParams.get('search'); const pbUrl = urlParams.get('pbUrl'); const apiKey = urlParams.get('apikey'); if (search && pbUrl && apiKey) { document.getElementById('apikey').value = apiKey; document.getElementById('pbUrl').value = pbUrl; document.getElementById('url').value = search; //document.forms[0].submit(); // Add the 'stop' query parameter to the URL const currentUrl = window.location.href; const updatedUrl = currentUrl + (currentUrl.includes('?') ? '&' : '?') + 'stop=true'; window.history.replaceState({}, '', updatedUrl); return; // Break off the script here } // Continue with other code if needed }; </script> ___________________________________ Fetch vidlii latest videos: (rqs proxy) --------------------------- <script> const url = 'https://api.codetabs.com/v1/proxy?quest=https://www.vidlii.com/user/repeekyraidcero/videos'; fetch(url) .then(response => response.text()) .then(html => { const parser = new DOMParser(); const doc = parser.parseFromString(html, 'text/html'); const links = doc.getElementsByTagName('a'); const displayedLinks = []; for (let i = 0; i < links.length; i++) { const link = links[i]; const href = link.getAttribute('href'); const className = link.getAttribute('class'); if (href && href.startsWith('/watch?v=') && className === 'ln2' && !displayedLinks.includes(href)) { const title = link.textContent; const linkElement = document.createElement('a'); linkElement.href = 'https://www.vidlii.com' + href; linkElement.target = '_blank'; linkElement.textContent = title; document.body.appendChild(linkElement); document.body.appendChild(document.createElement('br')); document.body.appendChild(document.createElement('br')); displayedLinks.push(href); } } }) .catch(error => console.error(error)); </script> </body> </html> <!---PHP-ver--> <?php $url = 'https://www.vidlii.com/user/repeekyraidcero/videos'; $html = file_get_contents($url); $dom = new DOMDocument(); libxml_use_internal_errors(true); $dom->loadHTML($html); libxml_clear_errors(); $links = $dom->getElementsByTagName('a'); $displayedLinks = array(); foreach ($links as $link) { $href = $link->getAttribute('href'); $class = $link->getAttribute('class'); if (strpos($href, '/watch?v=') === 0 && $class === 'ln2' && !in_array($href, $displayedLinks)) { $title = $link->nodeValue; echo '<a href="https://www.vidlii.com' . $href . '" target="_blank">' . $title . '</a><br><br>' . PHP_EOL; $displayedLinks[] = $href; } } ?> ______________________________________________ Load Mastodon Followers & Followings (Custom) ----------------------------------- <!DOCTYPE html> <html> <head> <style> .green { color: green; } .red { color: red; } .column { float: left; width: 50%; } </style> </head> <body> <label for="userId">User ID:</label> <input type="text" id="userId" name="userId" value="109629985010224381"><br><br> <label for="instance">Instance:</label> <input type="text" id="instance" name="instance" value="pb.todon.de"><br><br> <button onclick="displayFollowersAndFollowings()">Display Followers and Followings</button><br><br> <div class="column"> <h2>Followers</h2> <div id="followers"></div> </div> <div class="column"> <h2>Followings</h2> <div id="followings"></div> </div> <script> // Function to make API requests async function mastodonRequest(url, accessToken) { const response = await fetch(url, { headers: { 'Authorization': `Bearer ${accessToken}` } }); const data = await response.json(); return data; } // Function to resolve user's username async function resolveUser(id, instance, accessToken) { const userUrl = `https://${instance}/api/v1/accounts/${id}`; const user = await mastodonRequest(userUrl, accessToken); return user.acct; } // Function to display followers and followings async function displayFollowersAndFollowings() { const urlParams = new URLSearchParams(window.location.search); const instanceParam = urlParams.get('instance'); const userIdsParam = urlParams.get('userids'); const userIdTextbox = document.getElementById('userId'); const instanceTextbox = document.getElementById('instance'); if (instanceParam && userIdsParam) { instanceTextbox.value = instanceParam; userIdTextbox.value = userIdsParam; } const userId = userIdTextbox.value; const instance = instanceTextbox.value; const accessToken = 'YOUR_ACCESS_TOKEN'; const followerUrl = `https://${instance}/api/v1/accounts/${userId}/followers?limit=100`; const followingUrl = `https://${instance}/api/v1/accounts/${userId}/following?limit=100`; try { const [followers, followings] = await Promise.all([ mastodonRequest(followerUrl, accessToken), mastodonRequest(followingUrl, accessToken) ]); const followerIds = followers.map(follower => follower.id); const followingIds = followings.map(following => following.id); const inBothLists = followerIds.filter(id => followingIds.includes(id)); const followersDiv = document.getElementById('followers'); const followingsDiv = document.getElementById('followings'); followersDiv.innerHTML = ''; followingsDiv.innerHTML = ''; for (const follower of followers) { const followerId = follower.id; const followerUsername = await resolveUser(followerId, instance, accessToken); const followerElement = document.createElement('span'); if (inBothLists.includes(followerId)) { followerElement.textContent = followerUsername; followerElement.classList.add('green'); } else { followerElement.textContent = followerUsername; followerElement.classList.add('red'); } followersDiv.appendChild(followerElement); followersDiv.appendChild(document.createElement('br')); } for (const following of followings) { const followingId = following.id; const followingUsername = await resolveUser(followingId, instance, accessToken); const followingElement = document.createElement('span'); if (inBothLists.includes(followingId)) { followingElement.textContent = followingUsername; followingElement.classList.add('green'); } else { followingElement.textContent = followingUsername; followingElement.classList.add('red'); } followingsDiv.appendChild(followingElement); followingsDiv.appendChild(document.createElement('br')); } } catch (error) { console.error('Error:', error); } } // Check if query strings are present in the URL const urlParams = new URLSearchParams(window.location.search); const instanceParam = urlParams.get('instance'); const userIdsParam = urlParams.get('userid'); if (instanceParam && userIdsParam) { const instanceTextbox = document.getElementById('instance'); const userIdTextbox = document.getElementById('userId'); instanceTextbox.value = instanceParam; userIdTextbox.value = userIdsParam; displayFollowersAndFollowings(); } </script> </body> </html> _______________________ Countdown Redirect -------------------------------- <script> var time = 5 * 1; setInterval(function() { //var seconds = time % 60; //var minutes = (time - seconds) / 60; var seconds = time; var minutes = 0; if (seconds.toString().length == 1) { seconds = "0" + seconds; } if (minutes.toString().length == 1) { minutes = "0" + minutes; } document.getElementById("time").innerHTML = minutes + ":" + seconds; time--; if (time == 0) { window.location.href = "https://alceawis.de"; } }, 1000); </script> <div class="timer" onload="timer(1800)"> <div class="time"><strong>Redirecting in <span id="time"> x seconds</span></strong></div></div> (Source: https://stackoverflow.com/questions/50771115/javascript-countdown-to-redirect-another-page-when-it-hits-0000 ) __________________ DeviceType identifier: ---------------------------------- Wurlf:<br> <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript"></script> <!---<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">--> <script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script> <li class="is-mobile">Mobile: <span class="wurfl-data"></span>.</li> <li class="form-factor">Form factor: <span class="wurfl-data"></span>.</li> <li class="device-name">Device: <span class="wurfl-data"></span>.</li> </ul> <script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <script src='//wurfl.io/wurfl.js'></script> <script> console.log(WURFL); $('.is-mobile .wurfl-data').html( '' + WURFL.is_mobile + '' ); $('.form-factor .wurfl-data').html( WURFL.form_factor + '' ); $('.device-name .wurfl-data').html( WURFL.complete_device_name + '' ); </script> <br>======JS=======<br> Quick:<br> <meta charset="UTF-8"> <div class="container"><span class="user-agent"></span></div> <script> var userAgent = window.navigator.userAgent; if (userAgent) { var span = document.querySelector('.user-agent'); span.innerHTML = userAgent; } </script> <br>Concise:<br> <div class="container">Device: <span class="user-agentt"></span></div> <script> var userAgent = window.navigator.userAgent; if (userAgent) { var span = document.querySelector('.user-agentt'); var openingParenIndex = userAgent.indexOf('('); var closingParenIndex = userAgent.indexOf(')'); if (openingParenIndex !== -1 && closingParenIndex !== -1) { var extractedString = userAgent.substring(openingParenIndex, closingParenIndex + 1); span.innerHTML = extractedString; } } </script> _________________________ MediaSession AudioPlayer (with buttons also!) ------------------------------ <!---Media-Session-Event-Listener--> <script> // Function to handle the previous button click event function onPrevButtonClick() { // Your code logic for handling previous button click goes here console.log('Previous button clicked'); } // Function to handle the next button click event function onNextButtonClick() { // Your code logic for handling next button click goes here console.log('Next button clicked'); } // Media session event listener for previous media session event navigator.mediaSession.setActionHandler('previoustrack', () => { onPrevButtonClick(); }); // Media session event listener for next media session event navigator.mediaSession.setActionHandler('nexttrack', () => { onNextButtonClick(); }); </script> <!--------MediaPlayer------> <!---Prevent accidental reload --> <!-- <script type="text/javascript"> window.onbeforeunload = function() { return "Are you sure you want to leave? Think of the kittens!"; } </script>--> <meta charset="UTF-8"> </head> <body> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Player</title> </head> <body> <button id="prevButton">Previous</button> <button id="playButton">▶ PLAY</button> <button id="nextButton">Next</button> <div id="cue"> <a id="lastMusicLink"></a> <b><a id="currentMusicLink"></a></b> <a id="nextMusicLink"></a> </div> <script> let audio = document.createElement('audio'); let playlist = getAwesomePlaylist(); let index = 0; function onPrevButtonClick() { index = (index - 1 + playlist.length) % playlist.length; playAudio(); } function onNextButtonClick() { index = (index + 1) % playlist.length; playAudio(); } function onPlayButtonClick() { playAudio(); } function onCueLinkClick(clickedIndex) { index = clickedIndex; playAudio(); } function playAudio() { audio.src = playlist[index].src; audio.play() .then(_ => updateMetadata()) .catch(error => console.log(error)); } function updateMetadata() { let track = playlist[index]; console.log('Playing ' + track.title); document.title = track.title; // Update cue links let lastMusicIndex = (index - 1 + playlist.length) % playlist.length; let nextMusicIndex = (index + 1) % playlist.length; document.querySelector('#lastMusicLink').textContent = 'Last: ' + playlist[lastMusicIndex].title; document.querySelector('#lastMusicLink').href = playlist[lastMusicIndex].src; document.querySelector('#lastMusicLink').addEventListener('click', () => onCueLinkClick(lastMusicIndex)); document.querySelector('#currentMusicLink').textContent = '' + playlist[index].title; document.querySelector('#currentMusicLink').href = playlist[index].src; document.querySelector('#currentMusicLink').addEventListener('click', () => onCueLinkClick(index)); document.querySelector('#nextMusicLink').textContent = 'Next: ' + playlist[nextMusicIndex].title; document.querySelector('#nextMusicLink').href = playlist[nextMusicIndex].src; document.querySelector('#nextMusicLink').addEventListener('click', () => onCueLinkClick(nextMusicIndex)); } /* Previous Track & Next Track */ audio.addEventListener('ended', function() { // Play automatically the next track when audio ends. index = (index + 1) % playlist.length; playAudio(); }); document.addEventListener("DOMContentLoaded", () => { document.querySelector('#prevButton').addEventListener('click', onPrevButtonClick); document.querySelector('#playButton').addEventListener('click', onPlayButtonClick); document.querySelector('#nextButton').addEventListener('click', onNextButtonClick); }); /* Utils */ function getAwesomePlaylist() { const BASE_URL = ''; return [ { src: BASE_URL + 'https://ry3yr.github.io/OSTR/release/rnr/009_Guitar.mp3', title: 'RnR Guitar Theme', artist: 'diarykeeper', album: 'trackmix', artwork: undefined }, { src: BASE_URL + 'https://ry3yr.github.io/OSTR/release/z_other-reconstructs/Mirai_Nikki-12_Become_a_holder.mp3', title: 'Become a holder', artist: 'diarykeeper', album: 'trackmix', artwork: undefined } ]; } </script> <!---<div id="contentframe" style="position:relative; top: 0px; left: -30px;">--><br> <iframe src="index.html" name="audioplayer" style=" display:block; position: absolute; height: 100%; width: 100%" frameborder="0" ></iframe></div> </body> </html> ______________________________ 404 redirect via htaccess / httaccess: ----------------------------------- RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ 404.html [L,R=301] _______________________________ Redirect dir to file xy ----------------------- DirectoryIndex index.html _____________________________ Add Cors to curr dir: -------------------------- Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Methods "GET,PUT,POST,DELETE" Header set Access-Control-Allow-Headers "Content-Type, Authorization" (Source: https://urusai.social/@alcea/111650325029029518 https://gist.github.com/nixta/0b98d7975562bc31c4c9) _______________ Fix File Unicode Encoding issues: (txt file displaying mojibake f.e.) --------------------------------------- .htaccess ~~~~~~ AddDefaultCharset UTF-8 ______________________________ Redirect "non filenameextension" #requests to a #html ------------------------------ .htaccess ~~~~~~~ RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.html -f RewriteRule ^(.+)$ $1.html [L] (Source: https://pb.todon.de/@alcea/111193221007063341 ) _______________________________ Fix Unicode Rendering errors: ----------------------------------------- <meta charset="utf-8"> ___________________________ Current Chocolate Level (Mastodon) ------------------------------------------ <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div id="result"></div> <script> $(document).ready(function() { var apiUrl = "https://pb.todon.de/api/v1/accounts/109629985010224381/statuses"; $.ajax({ url: apiUrl, dataType: "json", success: function(response) { var targetPost = null; for (var i = 0; i < response.length; i++) { var content = response[i].content; if (content.toLowerCase().indexOf("chocolate") !== -1 || content.toLowerCase().indexOf("choco") !== -1) { targetPost = response[i]; break; // Exit the loop if a target post is found } } if (targetPost) { var content = targetPost.content; var matches = content.match(/(\d+([.,]\d+)?)%/); if (matches) { var chocolateValue = matches[1] + "%"; $("#result").text("Current chocolate value: " + chocolateValue); } else { checkNextPost(i + 1); } } else { checkNextPost(0); } }, error: function() { $("#result").text("Error retrieving data from the API."); } }); }); function checkNextPost(index) { $.ajax({ url: "https://pb.todon.de/api/v1/accounts/109629985010224381/statuses", dataType: "json", success: function(response) { if (index < response.length) { var content = response[index].content; var matches = content.match(/(\d+([.,]\d+)?)%/); if (matches) { var chocolateValue = matches[1] + "%"; $("#result").text("Current chocolate value: " + chocolateValue); } else { checkNextPost(index + 1); } } else { $("#result").text("100% Choco. Must be homemade !"); } }, error: function() { $("#result").text("Error retrieving data from the API."); } }); } </script> </body> </html> <!---RSS ver--(will-not-with-replies)--> <!--<head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div id="result"></div> <script> $(document).ready(function() { var rssUrl = "https://pb.todon.de/@alcea.rss"; $.ajax({ url: rssUrl, dataType: "xml", success: function(xml) { var targetPost = null; $(xml).find("item").each(function() { var description = $(this).find("description").text(); if (description.toLowerCase().indexOf("chocolate") !== -1 || description.toLowerCase().indexOf("choco") !== -1) { targetPost = $(this); return false; // Exit the loop if a target post is found } }); if (targetPost) { var description = targetPost.find("description").text(); var matches = description.match(/(\d+([.,]\d+)?)%/); //var matches = description.match(/(\d+)%/); if (matches) { var chocolateValue = matches[1] + "%"; $("#result").text("Current chocolate value: " + chocolateValue); } else { checkNextPost(targetPost.next(), xml); } } else { checkNextPost($(xml).find("item").first(), xml); } }, error: function() { $("#result").text("Error retrieving RSS feed."); } }); }); function checkNextPost(post, xml) { if (post.length > 0) { var description = post.find("description").text(); var matches = description.match(/(\d+)%/); if (matches) { var chocolateValue = matches[1] + "%"; $("#result").text("Current chocolate value: " + chocolateValue); } else { var nextPost = post.next(); checkNextPost(nextPost, xml); } } else { $("#result").text("100% Choco. Must be homemade !"); } } </script> </body> </html>--> <!--php <?php $rss = file_get_contents('https://pb.todon.de/@alcea.rss'); $xml = simplexml_load_string($rss); $targetPost = null; foreach ($xml->channel->item as $item) { $description = $item->description; if (stripos($description, 'chocolate') !== false || stripos($description, 'choco') !== false) { $targetPost = $item; break; } } if ($targetPost) { $description = $targetPost->description; if (preg_match('/(\d+)%/', $description, $matches)) { $chocolateValue = $matches[1] . '%'; echo 'Current chocolate value: ' . $chocolateValue; } else { echo 'No chocolate value found.'; } } else { echo 'No post found containing chocolate or choco.'; } ?> --> ___________________________ Link w hover popup: ------------------------------- ----CSS---VER---: <style> .hover-alt-text{display:inline-flex;align-items:center;position:relative}.hover-alt-text:hover::before{content:attr(alt);position:absolute;background:#fff;border:1px solid #000;padding:5px;z-index:9999;top:-100%;white-space:nowrap;margin-top:-5px} </style> <a target="_blank" href="https://thinfi.com/0awck" alt="webdav.hidrive.strato.com/users/user/DB/Public/Phone_relatated/0Android/[Device_Backupl]/Tablet" class="hover-alt-text">Android Dvcs</a> --JS--version-- <a id="popupLink" target="_blank" href="https://thinfi.com/0awck" style="position: relative; display: inline-block; cursor: pointer;"> AndrdDvsBckp <span id="popupText" style="visibility: hidden; width: 900px; background-color: #555; color: #fff; text-align: center; border-radius: 6px; padding: 8px; position: absolute; z-index: 1; bottom: 125%; left: 50%; margin-left: -100px; opacity: 0; transition: opacity 0.3s;"> webdav.hidrive.strato.com/users/user/DB/Public/Phone_relatated/0Android/[Device_Backupl]/Tablet </span> </a> ________________________ Isola(tion) -2P Game --------------------------------- <style> #grid { display: grid; grid-template-columns: repeat(8, 50px); grid-template-rows: repeat(6, 50px); } .cell { width: 50px; height: 50px; border: 1px solid black; display: flex; align-items: center; justify-content: center; cursor: pointer; } .red-dot, .blue-dot { width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; } .red-dot { background-color: red; } .blue-dot { background-color: blue; } .broken-field { background-color: gray; cursor: default; } #turn-display { position: absolute; top: 10px; right: 10px; font-weight: bold; } </style> </head> <body> <div id="grid"></div> <div id="turn-display"></div> <script> document.addEventListener("DOMContentLoaded", function () { const grid = document.querySelector("#grid"); const turnDisplay = document.querySelector("#turn-display"); const cells = []; const rows = 6; const columns = 8; for (let i = 0; i < rows; i++) { for (let j = 0; j < columns; j++) { const cell = document.createElement("div"); cell.classList.add("cell"); cell.dataset.row = i; cell.dataset.column = j; grid.appendChild(cell); cells.push(cell); } } let redDotPosition = { row: 2, column: 0 }; cells[redDotPosition.row * columns + redDotPosition.column].classList.add("red-dot"); let blueDotPosition = { row: rows - 3, column: columns - 1 }; cells[blueDotPosition.row * columns + blueDotPosition.column].classList.add("blue-dot"); let currentPlayer = "red"; let brokenFields = []; let currentAction = "move"; updateTurnDisplay(); cells.forEach(function (cell) { cell.addEventListener("click", function () { const clickedRow = parseInt(cell.dataset.row); const clickedColumn = parseInt(cell.dataset.column); if (currentAction === "move") { if (currentPlayer === "red" && isNeighboringCell(redDotPosition, clickedRow, clickedColumn)) { moveDot("red-dot", redDotPosition, clickedRow, clickedColumn); currentAction = "break"; } else if (currentPlayer === "blue" && isNeighboringCell(blueDotPosition, clickedRow, clickedColumn)) { moveDot("blue-dot", blueDotPosition, clickedRow, clickedColumn); currentAction = "break"; } } else if (currentAction === "break") { if (!isPlayerCell(clickedRow, clickedColumn) && !isBrokenField(clickedRow, clickedColumn)) { breakField(clickedRow, clickedColumn); currentAction = "move"; currentPlayer = currentPlayer === "red" ? "blue" : "red"; } } updateTurnDisplay(); }); }); function moveDot(dotClass, currentPosition, newRow, newColumn) { const newPosition = { row: newRow, column: newColumn }; const newPositionCell = cells[newPosition.row * columns + newPosition.column]; if (!newPositionCell.classList.contains("red-dot") && !newPositionCell.classList.contains("blue-dot")) { cells[currentPosition.row * columns + currentPosition.column].classList.remove(dotClass); newPositionCell.classList.add(dotClass); if (dotClass === "red-dot") { redDotPosition = newPosition; } else if (dotClass === "blue-dot") { blueDotPosition = newPosition; } invalidateGridPoint(newPosition); } else { console.log("Cannot move to an occupied spot."); } } function isNeighboringCell(currentPosition, clickedRow, clickedColumn) { const rowDiff = Math.abs(clickedRow - currentPosition.row); const columnDiff = Math.abs(clickedColumn - currentPosition.column); const isBroken = isBrokenField(clickedRow, clickedColumn); if (isBroken) { return false; // Prevent moving onto a broken field } return ( (rowDiff === 1 && columnDiff === 0) || (rowDiff === 0 && columnDiff === 1) || (rowDiff === 1 && columnDiff === 1) ); } function isPlayerCell(row, column) { return (row === redDotPosition.row && column === redDotPosition.column) || (row === blueDotPosition.row && column === blueDotPosition.column); } function isBrokenField(row, column) { return brokenFields.some((field) => field.row === row && field.column === column); } function breakField(row, column) { const brokenField = { row: row, column: column }; brokenFields.push(brokenField); cells[row * columns + column].classList.add("broken-field"); console.log("Field broken at (" + row + ", " + column + ")"); } function invalidateGridPoint(position) { const cell = cells[position.row * columns + position.column]; cell.style.backgroundColor = ""; } function updateTurnDisplay() { turnDisplay.textContent = "Current Turn: " + currentPlayer + " (" + currentAction + ")"; } }); </script> ______________________________ Download Time / Speed Calculator: --------------------------------------------------- <script> function calculateSpeed() { var fileSize = parseFloat(document.getElementById("fileSize").value); // File size in megabytes var transmissionSpeed = parseFloat(document.getElementById("transmissionSpeed").value); // Transmission speed in megabits or gigabits per second var unit = document.getElementById("unit").value; if (unit === "Mbit/s") { transmissionSpeed /= 8; // Convert speed to megabytes per second } else if (unit === "Gbit/s") { transmissionSpeed *= 125; // Convert speed to megabytes per second } var downloadTime = fileSize / transmissionSpeed; // Calculate download time in seconds // Determine the selected unit for output var outputUnit; if (document.getElementById("seconds").checked) { outputUnit = "seconds"; } else if (document.getElementById("minutes").checked) { outputUnit = "minutes"; downloadTime /= 60; // Convert download time to minutes } else if (document.getElementById("hours").checked) { outputUnit = "hours"; downloadTime /= 3600; // Convert download time to hours } // Display the download time document.getElementById("result").innerHTML = "Download Time: " + downloadTime.toFixed(2) + " " + outputUnit; } </script> </head> <body> <h1>Download Speed Calculator</h1> <label for="fileSize">File Size (MB):</label> <input type="text" id="fileSize" style="width: 60px;"/> -&nbsp;<input type="text" id="transmissionSpeed" style="width: 25px;" value="2"/> <select id="unit"> <option value="Mbit/s">Mbit/s</option> <option value="Gbit/s">Gbit/s</option> </select><br><br> <input type="radio" id="seconds" name="outputUnit" value="seconds"> <label for="seconds">Seconds</label> <input type="radio" id="minutes" name="outputUnit" value="minutes"> <label for="minutes">Minutes</label> <input type="radio" id="hours" name="outputUnit" value="hours" checked> <label for="hours">Hours</label><br><br> <button onclick="calculateSpeed()">Calculate</button><br><br> <div id="result"></div> </body> </html> ________________________________ Advanced Mastodon Renderer ( Attachments, Youtube, Pixiv, Tenor, imgbb, dailymotion, vidlii, soundcloud shortcode-emoji) -------------------------------------------- <body> <div id="feed"></div> <script> // Function to replace emoji shortcodes with images function replaceEmojis(content, customEmojis) { customEmojis.forEach(customEmoji => { const shortcode = customEmoji.shortcode; const url = customEmoji.url; const shortcodePattern = new RegExp(':' + shortcode + ':', 'g'); const emojiTag = '<img src="' + url + '" alt="' + shortcode + '" width="20px">'; content = content.replace(shortcodePattern, emojiTag); }); return content; } // Function to fetch data from the selected API URL function fetchData(apiUrl) { const accessToken = 'your-access-token'; fetch(apiUrl, { headers: { 'Authorization': 'Bearer ' + accessToken } }) .then(response => response.json()) .then(data => { // Clear the feed before appending new content document.getElementById('feed').innerHTML = ''; data.forEach(status => { let content = replaceEmojis(status.content, customEmojis); let media = ''; let avatar = ''; let tootLink = ''; // Check for YouTube video link const youtubeRegex = /https?:\/\/(www\.)?(m\.)?youtube\.com\/watch\?v=([a-zA-Z0-9_-]{11})/; const youtubeMatch = status.content.match(youtubeRegex); if (youtubeMatch) { // Extract video ID from YouTube link const videoId = youtubeMatch[3]; // Create embedded player for YouTube video media = `<div><iframe width="560" height="315" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allowfullscreen></iframe></div>`; } else { // Check for Pixiv artwork link const pixivRegex = /https?:\/\/(?:www\.)?pixiv\.net\/(?:en\/)?artworks\/(\d+)/; const pixivMatch = status.content.match(pixivRegex); if (pixivMatch) { // Extract artwork ID from Pixiv link const artworkId = pixivMatch[1]; // Create image preview for Pixiv artwork media = `<div><img src="https://embed.pixiv.net/decorate.php?illust_id=${artworkId}&mode=sns-automator" width="50%"></div>`; } else { const tenorRegex = /https?:\/\/(?:www\.)?tenor\.com\/view\/[a-zA-Z0-9-]+-(\d+)/; const tenorMatch = status.content.match(tenorRegex); if (tenorMatch) { // Extract Tenor.com video ID const videoId = tenorMatch[1]; // Create embedded player for Tenor.com video media = `<div><iframe src="https://tenor.com/embed/${videoId}" frameborder="0" allowfullscreen="true" width="100%" height="400px"></iframe></div>`; } else { // Check for Dailymotion video link const dailymotionRegex = /https?:\/\/(www\.)?dailymotion\.com\/video\/([a-zA-Z0-9_-]+)/; const dailymotionMatch = status.content.match(dailymotionRegex); if (dailymotionMatch) { const videoId = dailymotionMatch[2]; media = `<div><iframe frameborder="0" width="480" height="270" src="https://www.dailymotion.com/embed/video/${videoId}?autoplay=0" allowfullscreen allow="autoplay"></iframe></div>`; }else{ // Check for Vidlii video link const vidliiRegex = /https?:\/\/(www\.)?(m\.)?vidlii\.com\/watch\?v=([a-zA-Z0-9_-]+)/; const vidliiMatch = status.content.match(vidliiRegex); if (vidliiMatch) { const videoId = vidliiMatch[3]; media = `<iframe allowfullscreen src="https://www.vidlii.com/embed?v=${videoId}" frameborder="0" width="640" height="360"></iframe><br>`; }else{ // Check Soundcloud Link const soundcloudRegex = /https?:\/\/(m\.)?soundcloud\.com\/([a-zA-Z0-9_-]+)\/([a-zA-Z0-9_-]+)/; const soundcloudMatch = status.content.match(soundcloudRegex); if (soundcloudMatch) { const soundcloudUrl = `https://w.soundcloud.com/player/?url=${encodeURIComponent(soundcloudMatch[0] )}&color=0066cc&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`; //media = `<iframe width="100%" height="300" scrolling="no" frameborder="no" allow="autoplay" src="${soundcloudUrl}"></iframe>`; media = `<iframe allowfullscreen src="${status.url}/embed" class="mastodon-embed" style="max-width: 100%; border: 0" width="600" height=400"></iframe><script src="embed.js" async><\/\script><br>`; } else { // Check for imgbb image URLs in the status content const imageRegex = /(https?:\/\/(?:www\.)?i\.ibb\.co\/[^ ]+\.(?:jpg|png|gif|bmp))/g; const imageMatches = status.content.match(imageRegex); if (imageMatches) { media += '<div>'; imageMatches.forEach(url => { media += '<img src="' + url + '" width="50%"><br>'; }); media += '</div>'; } } } } } } } // Check for video and audio attachments if (status.media_attachments.length > 0) { media = '<div>'; status.media_attachments.forEach(attachment => { if (attachment.type === 'image') { media += '<img src="' + attachment.url + '" width="50%"><br>'; } else if (attachment.type === 'video') { media += '<video src="' + attachment.url + '" controls width="50%"></video><br>'; } else if (attachment.type === 'audio') { media += '<audio src="' + attachment.url + '" controls></audio><br>'; } }); media += '</div>'; } // Check for spoiler tag if (status.url.includes('activity')) { avatar = '<!--<details><summary>Avatar (spoiler)</summary><img src="' + status.account.avatar + '" width="100px"></details>--><br>'; tootLink = '<!--<details><summary>View on Mastodon (spoiler)</summary><a href="' + status.url + '" target="_blank">Click here to view activity</a></details>-->'; } else { avatar = '<img src="' + status.account.avatar + '" width="100px"><br>'; tootLink = '<a href="' + status.url + '" target="_blank">View on Mastodon</a>'; } // Get the date of the status const date = new Date(status.created_at); // Append content to feed const contentHtml = `<div>${content}</div>`; const statusHtml = `${contentHtml}${media}${avatar}${tootLink}&nbsp;${date.toLocaleString()}<hr>`; document.getElementById('feed').innerHTML += statusHtml; }); }) .catch(error => console.error(error)); } // Add emoji renderer const emojiEndpoint = 'https://pb.todon.de/api/v1/custom_emojis'; fetch(emojiEndpoint) .then(response => response.json()) .then(customEmojis => { // Store custom emojis for later use window.customEmojis = customEmojis; // Event listener for radio button change const radioButtons = document.querySelectorAll('input[name="apiUrl"]'); radioButtons.forEach(radioButton => { radioButton.addEventListener('change', function() { const selectedApiUrl = this.value; fetchData(selectedApiUrl); }); }); // Initial fetch using the default API URL const defaultApiUrl = 'https://pb.todon.de/api/v1/accounts/109629985010224381/statuses'; fetchData(defaultApiUrl); }); </script> </body> _____________________________ Code Display Page: ------------------------------ <style> body {font-family: Arial, sans-serif;line-height: 1.5;margin: 20px;} a {text-decoration: none;color: #007bff;} a:hover {text-decoration: underline;} .commands-list {margin-bottom: 10px;} .commands-list a {margin-right: 10px;border-radius: 9px;padding: 4px 8px;border: 1px solid transparent;border-color: #007bff;} .commands-list .command-link a {margin-right: 0;border-radius: 0;padding: 0;border: none;background-color: transparent;} .command-link {margin-right: 10px;border-radius: 9px;padding: 4px 8px;border: 1px solid transparent;border-color: #007bff;} </style> <!-- HTML content --> <a target="_blank" href="code.html">CMDS</a> <div class="commands-list"> <!--<a target="_blank" href="Computerstuff/Commands">(↑)</a>--> </div> <div class="commands-list"> <a target="_blank" href="other/Computerstuff/Commands/Autohotkey/Commands.txt">Autohotkey</a> <a target="_blank" href="other/Computerstuff/Commands/DOS/Commands.txt">DOS</a> <a target="_blank" href="other/Computerstuff/Commands/FFMPEG%20Commands.txt">FFMPEG</a> <a target="_blank" href="other/Computerstuff/Commands/Commands_ImageMagick.txt">Imagemagick</a> <a target="_blank" href="other/Computerstuff/Commands/Sox_CMDS.txt">Sox</a> <a target="_blank" href="other/Computerstuff/Commands/HTML_Codes.txt">HTML</a> <span class="command-link"><a target="_blank" href="other/Computerstuff/Commands/PHP.txt">PHP</a><a target="_blank" href="https://ry3yr.github.io/php">(↓)</a></span> <a target="_blank" href="other/Computerstuff/Commands/Python.txt">Python</a> <a target="_blank" href="other/Computerstuff/Commands/Android-Keyevents.txt">AndroidCMDS</a> </div> <br> <br> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; } button { background-color: #4CAF50; border: none; color: white; padding: 10px 20px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin-bottom: 20px; cursor: pointer; } button:hover { opacity: 0.8; } plaintext { display: block; white-space: pre-wrap; font-family: monospace; background-color: #f5f5f5; margin-bottom: 20px; } </style> <script> const txtUrls = [ 'https://ry3yr.github.io/OSTR/release/other/Computerstuff/Commands/Autohotkey/Commands.txt', 'https://ry3yr.github.io/OSTR/release/other/Computerstuff/Commands/HTML_Codes.txt', 'https://ry3yr.github.io/OSTR/release/other/Computerstuff/Commands/DOS/Commands.txt', 'https://ry3yr.github.io/OSTR/release/other/Computerstuff/Commands/FFMPEG%20Commands.txt', 'https://ry3yr.github.io/OSTR/release/other/Computerstuff/Commands/Commands_ImageMagick.txt', 'https://ry3yr.github.io/OSTR/release/other/Computerstuff/Commands/PHP.txt', 'https://ry3yr.github.io/OSTR/release/other/Computerstuff/Commands/Python.txt', ]; function getRandomTxtUrl() { const randomIndex = Math.floor(Math.random() * txtUrls.length); return txtUrls[randomIndex]; } function fetchRandomTxt() { const randomTxtUrl = getRandomTxtUrl(); fetch(randomTxtUrl) .then(response => response.text()) .then(fileContents => { const pattern = /------(.*?)_____/gs; const matches = fileContents.match(pattern).slice(1); const randomIndex = Math.floor(Math.random() * matches.length); const randomMatch = matches[randomIndex]; const numLines = randomMatch.split('\n').length; if (numLines >= 3) { const plaintext = document.createElement('plaintext'); plaintext.textContent = randomMatch; document.body.appendChild(plaintext); } else { // Retry fetching if plaintext is empty or doesn't have enough lines fetchRandomTxt(); } }) .catch(error => { // Retry fetching if there was an error fetchRandomTxt(); }); } fetchRandomTxt(); const fetchButton = document.createElement('button'); fetchButton.textContent = 'Fetch Random Code'; fetchButton.onclick = () => { document.querySelectorAll('plaintext').forEach(e => e.remove()); fetchRandomTxt(); }; </script> <button onclick='document.querySelectorAll("plaintext").forEach(e => e.textContent = "");fetchRandomTxt();'>Fetch Random Code</button> ____________________________ Terrible T9 Keypad ----------------------------- <!DOCTYPE html> <html> <head> <style> .keypad { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 10px; max-width: 200px; } .key { padding: 10px; text-align: center; background-color: #e0e0e0; cursor: pointer; } </style> </head> <body> <div class="keypad"> <div class="key" onclick="pressKey('1')">1</div> <div class="key" onclick="pressKey('2')">2<br>a b c</div> <div class="key" onclick="pressKey('3')">3<br>d e f</div> <div class="key" onclick="pressKey('4')">4<br>g h i</div> <div class="key" onclick="pressKey('5')">5<br>j k l</div> <div class="key" onclick="pressKey('6')">6<br>m n o</div> <div class="key" onclick="pressKey('7')">7<br>p q r s</div> <div class="key" onclick="pressKey('8')">8<br>t u v</div> <div class="key" onclick="pressKey('9')">9<br>w x y z</div> <div class="key" onclick="pressKey('*')">*</div> <div class="key" onclick="pressKey('0')">0</div> <div class="key" onclick="pressKey('#')">#</div> </div><br> <input type="text" id="input-field"> <div id="link-container" style="display: none;"> <a id="website-link" href="https://www.website.com" target="_blank">Visit Website.com</a> </div> <script> let inputValue = ''; function pressKey(key) { inputValue += key; document.getElementById('input-field').value = inputValue; checkSequence(inputValue); } function checkSequence(value) { if (value === '1234') { document.getElementById('link-container').style.display = 'block'; } else { document.getElementById('link-container').style.display = 'none'; } } </script> </body> </html> __________________________________ Prefill text field with query string: -------------------------------------------------- <script> // Get the query parameter value from the URL function getQueryParameter(name) { const urlSearchParams = new URLSearchParams(window.location.search); return urlSearchParams.get(name); } // Prefill the input field with the query parameter value document.addEventListener('DOMContentLoaded', function() { const apiKeyInput = document.getElementById('api_key'); const apiKeyValue = getQueryParameter('apikey'); if (apiKeyValue) { apiKeyInput.value = apiKeyValue; } }); </script> _________________________ Lazyloading: -------------------- <img src="https://i0.wp.com/www.chrismadden.co.uk/images/cartoons/room-for-one-more-plant-cartoon-cjmadden.gif" alt="garden" width="50%" loading="lazy"> ______________________________ eBay search Url constructor: ---------------------------------------- <html> <head> <title>eBay Search</title> </head> <body> <h1>eBay Search</h1> <form method="GET" action=""> <label for="query">Search Query:</label> <input type="text" name="query" id="query" required><br><br> <label for="country">Country:</label> <select name="country" id="country" > <option value="EBAY-US">United States</option> <option value="EBAY-UK">United Kingdom</option> <option value="EBAY-AU">Australia</option> <option value="EBAY-DE" selected>Germany</option> <!-- Add more country options here --> </select><br><br> <label for="sortBy">Sort By:</label> <select name="sortBy" id="sortBy"> <option value="BestMatch">Best Match</option> <option value="15">Price + Shipping: Lowest First</option> <option value="16" selected>Price + Shipping: Highest First</option> <!-- Add more sorting options here --> </select><br><br> <label for="buyNow">Buy Now/Bid:</label> <select name="buyNow" id="buyNow"> <option value="BuyNow">Buy Now</option> <option value="Auction">Bid</option> </select><br><br> <label for="minPrice">Minimum Price:</label> <input type="number" name="minPrice" id="minPrice"><br><br> <label for="maxPrice">Maximum Price:</label> <input type="number" name="maxPrice" id="maxPrice"><br><br> <label for="locationPref">Location Preference:</label> <select name="locationPref" id="locationPref"> <option value="1">Home</option> <option value="2">Worldwide</option> <option value="3">Europe</option> </select><br><br> <input type="submit" value="Search"> </form> <script> document.querySelector('form').addEventListener('submit', function(event) { event.preventDefault(); var query = document.getElementById('query').value; var country = document.getElementById('country').value; var sortBy = document.getElementById('sortBy').value; var buyNow = document.getElementById('buyNow').value; var minPrice = document.getElementById('minPrice').value; var maxPrice = document.getElementById('maxPrice').value; var locationPref = document.getElementById('locationPref').value; var baseUrl = ''; if (country === 'EBAY-DE') { baseUrl = 'https://www.ebay.de'; } else if (country === 'EBAY-UK') { baseUrl = 'https://www.ebay.co.uk'; } else { baseUrl = 'https://www.ebay.com'; } var sortingOption = ''; if (sortBy === '15') { sortingOption = '&_sop=15'; } else if (sortBy === '16') { sortingOption = '&_sop=16'; } var priceOption = ''; if (minPrice !== '') { priceOption += '&_udlo=' + minPrice; } if (maxPrice !== '') { priceOption += '&_udhi=' + maxPrice; } var locationOption = ''; if (locationPref === '1') { locationOption = '&LH_PrefLoc=1'; } else if (locationPref === '2') { locationOption = '&LH_PrefLoc=2'; } else if (locationPref === '3') { locationOption = '&LH_PrefLoc=3'; } var searchUrl = baseUrl + '/sch/i.html?_nkw=' + encodeURIComponent(query) + '&_ipg=50' + sortingOption + '&LH_BIN=' + (buyNow === 'BuyNow' ? '1' : '0') + '&LH_LocatedIn=' + encodeURIComponent(country) + priceOption + locationOption; // Display the search URL var searchUrlElement = document.createElement('a'); searchUrlElement.href = searchUrl; searchUrlElement.target = '_blank'; searchUrlElement.innerText = searchUrl; // Remove the existing link var existingLink = document.querySelector('a'); if (existingLink) { existingLink.parentNode.removeChild(existingLink); } // Append the new link to the document body //document.body.appendChild(document.createElement('br')); //document.body.appendChild(document.createElement('br')); //document.body.appendChild(document.createElement('h2')).innerText = 'Search URL:'; //document.body.appendChild(document.createElement('br')); document.body.appendChild(searchUrlElement); }); </script> </body> </html> ________________________________________________ YT Comment Finder: --------------------------------- <!DOCTYPE html> <html> <body> <form id="searchForm"> <label for="yturl">YouTube URL:</label> <input type="text" id="yturl" name="yturl" placeholder="Enter YouTube video URL" required><br> <label for="keyword">Keyword:</label> <input type="text" id="keyword" name="keyword" placeholder="Enter yt comment keyword" required><br> <button type="submit">Search</button> </form> <div id="commentsContainer"> <ul id="commentsList"></ul> </div> <script> document.getElementById('searchForm').addEventListener('submit', function (event) { event.preventDefault(); var videoUrl = document.getElementById('yturl').value; var keyword = document.getElementById('keyword').value; findYouTubeComments(videoUrl, keyword); }); function findYouTubeComments(videoUrl, keyword) { var videoId = getVideoIdFromUrl(videoUrl); var apiKey = atob('Base64APIKey'); var url = 'https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&maxResults=10&videoId=' + videoId + '&searchTerms=' + encodeURIComponent(keyword) + '&key=' + apiKey; fetch(url) .then(function (response) { return response.json(); }) .then(function (data) { displayComments(data.items); }) .catch(function (error) { console.log('Error:', error); }); } function displayComments(items) { var commentsList = document.getElementById('commentsList'); commentsList.innerHTML = ''; if (items.length === 0) { commentsList.innerHTML = '<li>No comments found.</li>'; } else { items.forEach(function (item) { var commentId = item.id; var comment = item.snippet.topLevelComment.snippet.textDisplay; var commentUrl = 'https://www.youtube.com/watch?v=' + item.snippet.videoId + '&google_comment_id=' + commentId; var listItem = document.createElement('li'); listItem.innerHTML = '<a href="' + commentUrl + '">' + comment + '</a>'; commentsList.appendChild(listItem); }); } } function getVideoIdFromUrl(url) { var videoId = ''; var pattern = /(?:\?v=|\/embed\/|\/\d\/|\/vi\/|\/v\/|https?:\/\/(?:www\.)?youtube\.com\/v\/|https?:\/\/(?:www\.)?youtube\.com\/embed\/|https?:\/\/youtu\.be\/|https?:\/\/(?:www\.)?youtube\.com\/user\/[^#\/]+#p\/[^#\/]+\/|https?:\/\/(?:www\.)?youtube\.com\/s[^#\/]+\/|https?:\/\/(?:www\.)?youtube\.com\/playlist\?)([^#\&\?\/]+)/; var matches = url.match(pattern); if (matches && matches.length > 1) { videoId = matches[1]; } return videoId; } </script> </body> </html> ________________________________________________ YT Studio esque: ------------------------- <a target="_blank" href="https://ry3yr.github.io/ytsearch">YT General Search</a>&nbsp; <a target="_blank" href="https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/ytchannelsearch-dkpr.html">YTChannel Search</a>&nbsp; <a target="_blank" href="https://ry3yr.github.io/ytstudio">YTStudio Overview</a><br> <!---LatestYTComments---> <iframe src="data:text/html;base64, PCFET0NUWVBFIGh0bWw+CjxodG1sPgo8aGVhZD4KCiAgICA8dGl0bGU+RmV0Y2ggWW91VHViZSBDb21tZW50czwvdGl0bGU+CjwvaGVhZD4KPGJvZHk+CiAgICA8IS0tIEhUTUwgZm9ybSBmb3IgQVBJIGtleSBhbmQgY2hhbm5lbCBzZWxlY3Rpb24gLS0+CiAgICA8Zm9ybSBpZD0iY29tbWVudEZvcm0iIG1ldGhvZD0iUE9TVCI+CiAgICAgICAgPGxhYmVsIGZvcj0iYXBpX2tleSI+QVBJIEtleTo8L2xhYmVsPgogICAgICAgIDxpbnB1dCB0eXBlPSJ0ZXh0IiBuYW1lPSJhcGlfa2V5IiBpZD0iYXBpX2tleSIgdmFsdWU9IiI+CiAgICAgICAgPGxhYmVsIGZvcj0iY2hhbm5lbF9pZCI+Q2hhbm5lbDo8L2xhYmVsPgogICAgICAgIDxzZWxlY3QgaWQ9ImNoYW5uZWxfaWQiIG5hbWU9ImNoYW5uZWxfaWQiIHJlcXVpcmVkPgogICAgICAgICAgICA8b3B0aW9uIHZhbHVlPSJVQ3JsdEdpaDExQV9OYXl6NmhHNVh0SXciPkRpYXJ5a2VlcGVyPC9vcHRpb24+CiAgICAgICAgICAgIDxvcHRpb24gdmFsdWU9IlVDbUlwT25kNUJWeDVTaTJocDBXTktadyIgc2VsZWN0ZWQ+UmVwZWVreXJhaWRfQ2Vybzwvb3B0aW9uPgogICAgICAgICAgICA8b3B0aW9uIHZhbHVlPSJVQ0Q3bVJCdWp5eFVSZXNRNmppaUd5cFEiPlBCPC9vcHRpb24+CiAgICAgICAgPC9zZWxlY3Q+CiAgICAgICAgPGJ1dHRvbiB0eXBlPSJzdWJtaXQiPkZldGNoIENvbW1lbnRzPC9idXR0b24+CiAgICA8L2Zvcm0+CiAgICA8IS0tIENvbnRhaW5lciB0byBkaXNwbGF5IHRoZSBmZXRjaGVkIGNvbW1lbnRzIC0tPgogICAgPGRpdiBpZD0iY29tbWVudHNDb250YWluZXIiPjwvZGl2PgogICAgPHNjcmlwdD4KICAgICAgICBjb25zdCBmb3JtID0gZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoJ2NvbW1lbnRGb3JtJyk7CiAgICAgICAgY29uc3QgY29tbWVudHNDb250YWluZXIgPSBkb2N1bWVudC5nZXRFbGVtZW50QnlJZCgnY29tbWVudHNDb250YWluZXInKTsKICAgICAgICBmb3JtLmFkZEV2ZW50TGlzdGVuZXIoJ3N1Ym1pdCcsIGFzeW5jIChldmVudCkgPT4gewogICAgICAgICAgICBldmVudC5wcmV2ZW50RGVmYXVsdCgpOwogICAgICAgICAgICBjb25zdCBhcGlLZXkgPSBkb2N1bWVudC5nZXRFbGVtZW50QnlJZCgnYXBpX2tleScpLnZhbHVlOwogICAgICAgICAgICBjb25zdCBjaGFubmVsSWQgPSBkb2N1bWVudC5nZXRFbGVtZW50QnlJZCgnY2hhbm5lbF9pZCcpLnZhbHVlOwogICAgICAgICAgICBjb25zdCBhcGlVcmwgPSBgaHR0cHM6Ly93d3cuZ29vZ2xlYXBpcy5jb20veW91dHViZS92My9jb21tZW50VGhyZWFkcz9wYXJ0PXNuaXBwZXQmYWxsVGhyZWFkc1JlbGF0ZWRUb0NoYW5uZWxJZD0ke2NoYW5uZWxJZH0mbWF4UmVzdWx0cz0xMCZvcmRlcj10aW1lJmtleT0ke2FwaUtleX1gOwogICAgICAgICAgICB0cnkgewogICAgICAgICAgICAgICAgY29uc3QgcmVzcG9uc2UgPSBhd2FpdCBmZXRjaChhcGlVcmwpOwogICAgICAgICAgICAgICAgY29uc3QgZGF0YSA9IGF3YWl0IHJlc3BvbnNlLmpzb24oKTsKICAgICAgICAgICAgICAgIGNvbnN0IGNvbW1lbnRzID0gZGF0YS5pdGVtczsKICAgICAgICAgICAgICAgIC8vIENsZWFyIHByZXZpb3VzIGNvbW1lbnRzCiAgICAgICAgICAgICAgICBjb21tZW50c0NvbnRhaW5lci5pbm5lckhUTUwgPSAnJzsKICAgICAgICAgICAgICAgIC8vIERpc3BsYXkgdGhlIGZldGNoZWQgY29tbWVudHMKICAgICAgICAgICAgICAgIGNvbW1lbnRzLmZvckVhY2goKGNvbW1lbnQpID0+IHsKICAgICAgICAgICAgICAgICAgICBjb25zdCBzbmlwcGV0ID0gY29tbWVudC5zbmlwcGV0LnRvcExldmVsQ29tbWVudC5zbmlwcGV0OwogICAgICAgICAgICAgICAgICAgIGNvbnN0IGF1dGhvciA9IHNuaXBwZXQuYXV0aG9yRGlzcGxheU5hbWU7CiAgICAgICAgICAgICAgICAgICAgY29uc3QgdGV4dCA9IHNuaXBwZXQudGV4dERpc3BsYXk7CiAgICAgICAgICAgICAgICAgICAgY29uc3QgdmlkZW9JZCA9IHNuaXBwZXQudmlkZW9JZDsKICAgICAgICAgICAgICAgICAgICBjb25zdCB2aWRlb1VybCA9IGBodHRwczovL3d3dy55b3V0dWJlLmNvbS93YXRjaD92PSR7dmlkZW9JZH1gOwogICAgICAgICAgICAgICAgICAgIGNvbnN0IGNvbW1lbnRFbGVtZW50ID0gZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgnZGl2Jyk7CiAgICAgICAgICAgICAgICAgICAgY29tbWVudEVsZW1lbnQuaW5uZXJIVE1MID0gYAogICAgICAgICAgICAgICAgICAgICAgICA8cD48c3Ryb25nPiR7YXV0aG9yfTwvc3Ryb25nPjogJHt0ZXh0fTwvcD4KICAgICAgICAgICAgICAgICAgICAgICAgPHA+RnJvbSBWaWRlbzogPGEgaHJlZj0iJHt2aWRlb1VybH0iIHRhcmdldD0iX2JsYW5rIj4ke3ZpZGVvVXJsfTwvYT48L3A+CiAgICAgICAgICAgICAgICAgICAgYDsKICAgICAgICAgICAgICAgICAgICBjb21tZW50c0NvbnRhaW5lci5hcHBlbmRDaGlsZChjb21tZW50RWxlbWVudCk7CiAgICAgICAgICAgICAgICB9KTsKICAgICAgICAgICAgfSBjYXRjaCAoZXJyb3IpIHsKICAgICAgICAgICAgICAgIGNvbnNvbGUuZXJyb3IoJ0Vycm9yIGZldGNoaW5nIGNvbW1lbnRzOicsIGVycm9yKTsKICAgICAgICAgICAgfQogICAgICAgIH0pOwogICAgPC9zY3JpcHQ+CjwvYm9keT4KPC9odG1sPg== " style="border:0px #ffffff none;" name="statusit" scrolling="auto" frameborder="0" marginheight="0px" marginwidth="0px" height="220px" width="800px" allowfullscreen></iframe> <!DOCTYPE html> <html> <head> <title>YouTube Channel Videos</title> <style> body { font-family: Arial, sans-serif; background-color: #f2f2f2; } form { max-width: 600px; margin: 0 auto; padding: 20px; background-color: #fff; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,.1); } label { display: block; margin-bottom: 10px; font-weight: bold; } select, input[type="text"], button { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; margin-bottom: 20px; font-size: 14px; } input[type="checkbox"], label[for="show_thumbnail"] { display: inline; margin-right: 5px; } button[type="submit"] { background-color: #4CAF50; color: #fff; cursor: pointer; } </style> </head> <body> <!-- HTML form --> <form method="POST" action=""> <label for="channel_id">Channel ID:</label> <select id="channel_id" name="channel_id" required> <option value="UCrltGih11A_Nayz6hG5XtIw">Diarykeeper</option> <option value="UCmIpOnd5BVx5Si2hp0WNKZw">Repeekyraid_Cero</option> </select> <label for="api_key">API Key:</label> <input type="text" id="api_key" name="api_key" required> <input type="checkbox" id="show_thumbnail" name="show_thumbnail"> <label for="show_thumbnail">Show Thumbnail</label><br> <button type="submit">Get Channel Videos</button> </form> <script> document.addEventListener('DOMContentLoaded', function() { var form = document.querySelector('form'); form.addEventListener('submit', function(event) { event.preventDefault(); var channelId = document.getElementById('channel_id').value; var apiKey = document.getElementById('api_key').value; var url = `https://www.googleapis.com/youtube/v3/channels?part=contentDetails&id=${channelId}&key=${apiKey}`; fetch(url) .then(function(response) { if (!response.ok) { throw new Error('Error: cURL request failed'); } return response.json(); }) .then(function(data) { var uploadsPlaylistId = data.items[0].contentDetails.relatedPlaylists.uploads; var playlistUrl = `https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=${uploadsPlaylistId}&key=${apiKey}`; return fetch(playlistUrl); }) .then(function(playlistResponse) { if (!playlistResponse.ok) { throw new Error('Error: cURL playlist request failed'); } return playlistResponse.json(); }) .then(function(playlistData) { var items = playlistData.items; items.forEach(function(item) { var videoId = item.snippet.resourceId.videoId; var videoTitle = item.snippet.title; var videoThumbnail = item.snippet.thumbnails.default.url; var videoPublishedAt = item.snippet.publishedAt; var videoContainer = document.createElement('div'); if (document.getElementById('show_thumbnail').checked) { var thumbnailImg = document.createElement('img'); thumbnailImg.src = videoThumbnail; thumbnailImg.alt = 'Thumbnail'; videoContainer.appendChild(thumbnailImg); } var videoLink = document.createElement('a'); videoLink.href = `https://www.youtube.com/watch?v=${videoId}`; videoLink.textContent = videoTitle; videoContainer.appendChild(videoLink); var videoIdText = document.createElement('p'); videoIdText.textContent = 'Video ID: ' + videoId; videoContainer.appendChild(videoIdText); var uploadDateText = document.createElement('p'); uploadDateText.textContent = 'Upload Date: ' + videoPublishedAt; videoContainer.appendChild(uploadDateText); var commentsUrl = `https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&maxResults=5&videoId=${videoId}&key=${apiKey}`; fetch(commentsUrl) .then(function(commentsResponse) { if (!commentsResponse.ok) { throw new Error('Error: cURL comments request failed'); } return commentsResponse.json(); }) .then(function(commentsData) { var comments = commentsData.items; comments.forEach(function(comment) { var commentText = document.createElement('p'); commentText.textContent = 'Comment: ' + comment.snippet.topLevelComment.snippet.textDisplay; videoContainer.appendChild(commentText); }); }) .catch(function(error) { console.error(error); }); document.body.appendChild(videoContainer); }); }) .catch(function(error) { console.error(error); }); }); }); </script> ___________________ Youtube Channel Search ------------------------------------ <br> Set Channel: <a href="#" onclick="document.getElementById('channelId').value = 'UCmIpOnd5BVx5Si2hp0WNKZw'; return false;">Repeekyraid</a> <a href="#" onclick="document.getElementById('channelId').value = 'UCrltGih11A_Nayz6hG5XtIw'; return false;">Diarykeeper</a><br> <!DOCTYPE html> <html> <head> <title>YouTube Channel Content Search</title> </head> <body> <h1>YouTube Channel Content Search</h1> <label for="channelName">Channel Name:</label> <input type="text" id="channelName"><br><br> <label for="channelId">Channel ID:</label> <input type="text" id="channelId" value="UCrltGih11A_Nayz6hG5XtIw"><br><br> <label for="searchText">Search Text:</label> <input type="text" id="searchText" required><br><br> <button onclick="searchVideos()">Search</button> <div id="searchResults"></div> <script> function searchVideos() { var channelName = document.getElementById("channelName").value; var channelId = document.getElementById("channelId").value; var searchText = document.getElementById("searchText").value; if (searchText === "") { alert("Please enter a search text."); return; } // Set your YouTube Data API key var apiKey = 'APIKEY'; // Determine the channel parameter based on channel name or channel ID var channelParam = ""; if (channelId !== "") { channelParam = "channelId=" + encodeURIComponent(channelId); } else if (channelName !== "") { channelParam = "channel=" + encodeURIComponent(channelName); } // Make a request to the YouTube Data API var url = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=" + encodeURIComponent(searchText) + "&maxResults=10&key=" + apiKey + "&" + channelParam; fetch(url) .then(response => response.json()) .then(data => { var searchResultsDiv = document.getElementById("searchResults"); searchResultsDiv.innerHTML = ""; if (data.items && data.items.length > 0) { var resultsHeading = document.createElement("h2"); resultsHeading.textContent = "Search Results"; searchResultsDiv.appendChild(resultsHeading); data.items.forEach(function(item) { if (item.id.kind !== "youtube#video") { return; // Skip non-video results } var videoId = item.id.videoId; var videoTitle = item.snippet.title; var videoThumbnail = item.snippet.thumbnails.default.url; var videoLink = "https://www.youtube.com/watch?v=" + videoId; var videoLinkElement = document.createElement("a"); videoLinkElement.href = videoLink; videoLinkElement.target = "_blank"; var thumbnailImageElement = document.createElement("img"); thumbnailImageElement.src = videoThumbnail; thumbnailImageElement.alt = videoTitle; var videoTitleElement = document.createElement("p"); videoTitleElement.textContent = videoTitle; videoLinkElement.appendChild(thumbnailImageElement); videoLinkElement.appendChild(videoTitleElement); searchResultsDiv.appendChild(videoLinkElement); }); } else { var noResultsMessage = document.createElement("p"); noResultsMessage.textContent = "No videos found for the specified channel and search text."; searchResultsDiv.appendChild(noResultsMessage); } }) .catch(error => { console.error(error); alert("An error occurred during the API request."); }); } </script> </body> </html> ______________________ Youtube Search ------------------------- <!DOCTYPE html> <html> <head> <title>YouTube Search</title> <style> .additional-info { color: #888; } </style> </head> <body> <label for="api_key">API Key:</label> <input type="text" id="api_key" required><br><br> <label for="search_query">Search Query:</label> <input type="text" id="search_query" required><br><br> <label for="max_results">Max Results:</label> <input type="number" id="max_results" min="1" max="50" value="50" required><br><br> <input type="checkbox" id="show_additional_info"> <label for="show_additional_info">Show Additional Info</label><br><br> <button onclick="searchYouTube()">Search</button> <br><br> <div id="results"></div> <script> function searchYouTube() { var apiKey = document.getElementById('api_key').value; var searchQuery = document.getElementById('search_query').value; var maxResults = document.getElementById('max_results').value; var showAdditionalInfo = document.getElementById('show_additional_info').checked; var apiUrl = 'https://www.googleapis.com/youtube/v3/search'; var requestUrl = apiUrl + '?part=snippet&maxResults=' + maxResults + '&q=' + encodeURIComponent(searchQuery) + '&key=' + apiKey; fetch(requestUrl) .then(function(response) { return response.json(); }) .then(function(data) { var resultsDiv = document.getElementById('results'); resultsDiv.innerHTML = ''; data.items.forEach(function(item) { if (item.id.kind === 'youtube#video') { var videoId = item.id.videoId; var title = item.snippet.title; var link = 'https://www.youtube.com/watch?v=' + videoId; var titleElement = document.createElement('p'); titleElement.textContent = 'Title: ' + title; if (showAdditionalInfo) { var channelId = item.snippet.channelId; var channelTitle = item.snippet.channelTitle; var uploadDate = item.snippet.publishedAt; var channelElement = document.createElement('p'); channelElement.classList.add('additional-info'); channelElement.textContent = 'Channel: ' + channelTitle + ' (ID: ' + channelId + ')'; var uploadDateElement = document.createElement('p'); uploadDateElement.classList.add('additional-info'); uploadDateElement.textContent = 'Upload Date: ' + uploadDate; resultsDiv.appendChild(channelElement); resultsDiv.appendChild(uploadDateElement); } var linkElement = document.createElement('a'); linkElement.href = link; linkElement.textContent = 'Link'; linkElement.target = '_blank'; // Add target="_blank" attribute resultsDiv.appendChild(titleElement); resultsDiv.appendChild(linkElement); resultsDiv.appendChild(document.createElement('br')); } }); }) .catch(function(error) { console.log('Error:', error); }); } </script> </body> </html> _____________________________ Disable site elements (here: object & iframe) if "keyword" is part of url: ----------------------------------------------------------------------------------------------------------- <script> // Check if "lowbandwidth" is present in the URL if (window.location.href.includes("lowbandwidth")) { // Create a <style> element var style = document.createElement("style"); // Define the CSS rules style.innerHTML = ` iframe, object { display: none !important; } `; // Add the <style> element to the document's head document.head.appendChild(style); } </script> _____________________ Disable all img & iframe onpage: -------------------------------------------------- <style> img, iframe { display: none !important; } </style> _____________ HTML Render ---------------------- <!DOCTYPE html> <html> <head> <title>HTML Render</title> <script type="text/javascript"> function renderContent() { var content = document.getElementById("content").value; var base64 = btoa(content); var iframe = document.getElementById("output"); iframe.src = "data:text/html;base64," + base64; } </script> </head> <body> <textarea id="content" rows="15" cols="50"></textarea> <br /> <button onclick="renderContent()">Render</button> <hr> <div> <iframe id="output" style="border: 0px #ffffff none;" name="statusit" scrolling="auto" frameborder="0" marginheight="0px" marginwidth="0px" height="1200px" width="80%" allowfullscreen ></iframe> </div> </body> </html> ______________________________ Folderlister (with urlconversion, link support and download to .html) ------------------------------------------ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Drag and Drop Folder</title> </head> <body> <button id="downloadButton">Download List</button> <div id="dropzone">Drop a folder here</div> <ul id="fileList"></ul> <input type="text" id="prependText" placeholder="Enter text to prepend" value="http://10.10.10.254/data/UsbDisk1/Volume1/"> <label> <input type="checkbox" id="wrapLinesCheckbox"> Wrap lines as links </label> <label> <input type="checkbox" id="convertToUrlCheckbox" checked> Convert paths to URL-conforming characters </label> <script> var dropzone = document.getElementById('dropzone'); var fileList = document.getElementById('fileList'); var prependText = document.getElementById('prependText'); var wrapLinesCheckbox = document.getElementById('wrapLinesCheckbox'); var convertToUrlCheckbox = document.getElementById('convertToUrlCheckbox'); var downloadButton = document.getElementById('downloadButton'); dropzone.addEventListener('dragover', function(event) { event.preventDefault(); }); dropzone.addEventListener('drop', function(event) { event.preventDefault(); // Clear the file list fileList.innerHTML = ''; var items = event.dataTransfer.items; for (var i = 0; i < items.length; i++) { var item = items[i]; if (item.kind === 'file') { var entry = item.webkitGetAsEntry(); if (entry) { if (entry.isDirectory) { traverseDirectory(entry, ''); } else if (entry.isFile) { addFileToList(entry.fullPath); } } } } }); function traverseDirectory(directory, parentPath) { var directoryReader = directory.createReader(); directoryReader.readEntries(function(entries) { for (var i = 0; i < entries.length; i++) { var entry = entries[i]; if (entry.isFile) { addFileToList(parentPath + entry.name); } else if (entry.isDirectory) { traverseDirectory(entry, parentPath + entry.name + '/'); } } }, function(error) { console.error('Error reading directory:', error); }); } function addFileToList(filePath) { var li = document.createElement('li'); var lineContent = prependText.value + filePath; if (convertToUrlCheckbox.checked) { lineContent = encodeURI(lineContent); } if (wrapLinesCheckbox.checked) { var link = document.createElement('a'); link.href = lineContent; link.textContent = lineContent; li.appendChild(link); } else { li.textContent = lineContent; } fileList.appendChild(li); } downloadButton.addEventListener('click', function() { var content = fileList.innerHTML; var filename = 'extHDD.html'; var element = document.createElement('a'); element.setAttribute('href', 'data:text/html;charset=UTF-8,' + encodeURIComponent(content)); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); }); </script> <style> #dropzone { width: 500px; height: 100px; border: 2px dashed black; text-align: center; padding-top: 80px; font-size: 24px; } </style> </body> </html> ________________________ imgbb uploader (via api) ----------------------------------- <body> <input type="file" id="imageInput"> <button onclick="uploadImage()">Upload</button> <div id="imageURL"></div> <div id="imageViewURL"></div> <script> function uploadImage() { const apiKey = 'Apikey'; const expiration = 0; const imageInput = document.getElementById('imageInput'); const imageFile = imageInput.files[0]; if (!imageFile) { console.log('Please select an image file.'); return; } const formData = new FormData(); formData.append('image', imageFile); fetch(`https://api.imgbb.com/1/upload?key=${apiKey}&expiration=${expiration}`, { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { console.log(data); // JSON response from the API if (data.status === 200) { console.log('Image uploaded successfully!'); const imageURL = data.data.url; const imageViewURL = data.data.url_viewer; document.getElementById('imageURL').textContent = `Image URL: ${imageURL}`; document.getElementById('imageViewURL').textContent = `Viewer URL: ${imageViewURL}`; // Perform any further actions with the uploaded image data } else { console.log('Image upload failed. Error:', data.error.message); } }) .catch(error => { console.error('Error:', error); }); } </script> </body> </html> ___________________________ Youtube URL Link Extractor ------------------------------------------ <script> var xhr = new XMLHttpRequest(); // Define the URL of the webpage var url = 'https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/UnderratedContent.html'; // Send a GET request to the URL xhr.open('GET', url, true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // Get the response text var html = xhr.responseText; // Create a regular expression to match URLs containing "watch" and their corresponding link names var regex = /<a[^>]+href=["']([^"']*\bwatch\b[^"']*)["'][^>]*>(.*?)<\/a>/gi; // Find all matches in the HTML var matches = html.matchAll(regex); // Create a container div to hold the textareas var containerDiv = document.createElement('div'); containerDiv.style.display = 'flex'; // Create a textarea element to display the URLs var urlTextarea = document.createElement('textarea'); urlTextarea.rows = 10; urlTextarea.cols = 50; urlTextarea.style.overflow = 'auto'; // Create a textarea element to display the link names var nameTextarea = document.createElement('textarea'); nameTextarea.rows = 10; nameTextarea.cols = 50; nameTextarea.style.overflow = 'auto'; // Add each match to the textareas if (matches) { for (var match of matches) { // Extract the URL and link name from the match var url = match[1]; var name = match[2]; // Append the URL to the URL textarea urlTextarea.value += url + '\n'; // Append the link name to the name textarea nameTextarea.value += name + '\n'; } } else { urlTextarea.value = 'No URLs containing "watch" found.'; nameTextarea.value = 'No link names found.'; } // Append the textareas to the container div containerDiv.appendChild(urlTextarea); containerDiv.appendChild(nameTextarea); // Append the container div to the document body document.body.appendChild(containerDiv); // Set up event listener to synchronize scrolling urlTextarea.addEventListener('scroll', function () { nameTextarea.scrollTop = urlTextarea.scrollTop; }); nameTextarea.addEventListener('scroll', function () { urlTextarea.scrollTop = nameTextarea.scrollTop; }); } }; // Send the request xhr.send(); </script> <iframe src="data:text/html;base64, CjxzY3JpcHQ+CnZhciB4aHIgPSBuZXcgWE1MSHR0cFJlcXVlc3QoKTsKdmFyIHVybCA9ICdodHRwczovL3J5M3lyLmdpdGh1Yi5pby9PU1RSL0RpYXJ5a2VlcGVyc19Ib21lcGFnZS9VbmRlcnJhdGVkQ29udGVudC5odG1sJzsKeGhyLm9wZW4oJ0dFVCcsIHVybCwgdHJ1ZSk7Cnhoci5vbnJlYWR5c3RhdGVjaGFuZ2UgPSBmdW5jdGlvbiAoKSB7CiAgaWYgKHhoci5yZWFkeVN0YXRlID09PSA0ICYmIHhoci5zdGF0dXMgPT09IDIwMCkgewogICAgdmFyIGh0bWwgPSB4aHIucmVzcG9uc2VUZXh0OwogICAgdmFyIHJlZ2V4ID0gLzxhW14+XStocmVmPVsiJ10oW14iJ10qXGJ3YXRjaFxiW14iJ10qKVsiJ11bXj5dKj4oLio/KTxcL2E+L2dpOwogICAgdmFyIG1hdGNoZXMgPSBodG1sLm1hdGNoQWxsKHJlZ2V4KTsKICAgIHZhciBteW5ld0RpdiA9IGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoJ2RpdicpOwogICAgaWYgKG1hdGNoZXMpIHsKICAgICAgZm9yICh2YXIgbWF0Y2ggb2YgbWF0Y2hlcykgewogICAgICAgIHZhciB1cmwgPSBtYXRjaFsxXTsKICAgICAgICB2YXIgbmFtZSA9IG1hdGNoWzJdOwogICAgICAgIHZhciBsaW5rID0gZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgnYScpOwogICAgICAgIGxpbmsuaHJlZiA9IHVybDsKICAgICAgICBsaW5rLnRhcmdldCA9ICdfYmxhbmsnOwogICAgICAgIGxpbmsudGV4dENvbnRlbnQgPSBuYW1lOwogICAgICAgIG15bmV3RGl2LmFwcGVuZENoaWxkKGxpbmspOwogICAgICAgIG15bmV3RGl2LmFwcGVuZENoaWxkKGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoJ2JyJykpOwogICAgICB9CiAgICB9IGVsc2UgewogICAgICBteW5ld0Rpdi50ZXh0Q29udGVudCA9ICdObyBsaW5rcyBmb3VuZC4nOwogICAgfQogICAgZG9jdW1lbnQuYm9keS5hcHBlbmRDaGlsZChteW5ld0Rpdik7CiAgfQp9Owp4aHIuc2VuZCgpOwo8L3NjcmlwdD4= " style="border:0px #ffffff none;" name="statusit" scrolling="auto" frameborder="0" marginheight="0px" marginwidth="0px" height="250px" width="500px" allowfullscreen></iframe> ______________________________________________________ Pixiv Dynamic Owlcarousel generator (with embed as img): ----------------------------------------------------- <!DOCTYPE html> <html> <head> <title>Ryedai1's new Art n Doodle's</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.1/animate.min.css'> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.0.0-beta.3/assets/owl.carousel.min.css'> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.0.0-beta.3/assets/owl.theme.default.min.css'> </head> <body> <!-- partial:index.partial.html --> <div class="owl-carousel owl-theme" id="carousel"></div> <!-- partial --> <script src='https://code.jquery.com/jquery-1.12.2.min.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.0.0-beta.3/owl.carousel.min.js'></script> <script> $(document).ready(function(){ var imageUrl = "https://embed.pixiv.net/decorate.php?illust_id="; var artworks = [ { id: "101357774" }, { id: "98087776" }, ]; var carousel = $('#carousel'); // Dynamically generate the carousel items artworks.forEach(function(artwork) { var link = $('<a></a>').attr('target', '_blank').attr('href', 'https://www.pixiv.net/en/artworks/' + artwork.id); //var image = $('<img>').attr('src', imageUrl + artwork.id + '&mode=sns-automator').attr('height', '50%').attr('width', '50%'); var image = $('<img>').attr('src', imageUrl + artwork.id + '&mode=sns-automator').attr('height', '50%').attr('width', '50%').attr('loading', 'lazy'); var item = $('<div></div>').addClass('item').append(link.append(image)); carousel.append(item); }); // Initialize the Owl Carousel carousel.owlCarousel({ loop:true, margin:10, nav:true, center: true, responsive:{ 0:{ items:1 }, 600:{ items:3 }, 1000:{ items:5 } } }); }); </script> </body> </html> ___________________________________ Pseudo Password Box to reveal content: -------------------------------------------------------------- <script> function checkKeyword() { var e = document.getElementById("inputField").value; if (e.length === 4) { if (e === atob("NDU2Nw==")) { document.getElementById("inputField").style.display = "none"; var newElement = document.createElement("p"); newElement.innerHTML = decodeURIComponent(atob("aHR0cHM6Ly9odG1sZWRpdC5zcXVhcmVmcmVlLmNvbS8=")); document.body.appendChild(newElement); } else { document.getElementById("keywordForm").submit(); } } } </script> <form id="keywordForm" onsubmit="event.preventDefault(); checkKeyword()"> <input type="text" id="inputField" style="border:none;" placeholder="Enter keyword"> </form> ___________________________________________ Trigger event (from ext url etc.) when date-span is divisible by 'x' "birthday": ---------------------------------------------------------------------------------------------------------------- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { var currentDate = new Date(); var targetDate = new Date('July 13, 2021'); var daysPassed = Math.floor((currentDate.getTime() - targetDate.getTime()) / (1000 * 60 * 60 * 24)); if (daysPassed % 750 === 0) { document.querySelector("a[href='javascript:mybdayFunction()']").click(); } }); function mybdayFunction() { $("#mybday").load("https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/site/effects/wisteria_petal_rain.html"); } </script> <a href="javascript:mybdayFunction()" style="color:transparent">bday</a> <div id="bigdivv" style="position:relative; top: 0px; left: -650px;"> <div class="formClass"><div id="mybday"></div></div> </div> _______________________________________ 3D Model render with url dropdown -------------------------------------- <body> <select id="model-selector"> <option value="">Select a model</option> <option value="https://s3-us-west-2.amazonaws.com/s.cdpn.io/127738/banana.obj">Banana</option> <option value="https://s3-us-west-2.amazonaws.com/s.cdpn.io/127738/banana.obj">Model 2</option> <option value="https://example.com/model3.obj">Model 3</option> </select> <canvas id="canvas"></canvas> <script src='https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.min.js'></script> <script src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/127738/OBJLoader.js'></script> <script> let scene, camera, renderer, mesh; function init() { // Create a new scene scene = new THREE.Scene(); // Create a new camera camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.set(0, 50, 100); // Create a new renderer renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('canvas') }); renderer.setSize(window.innerWidth, window.innerHeight*2); // Add a light to the scene const light = new THREE.PointLight(0xffffff, 1, 1000); light.position.set(0, 0, 50); scene.add(light); // Load the initial model loadModel(document.getElementById('model-selector').value); } function loadModel(url) { // Remove the old mesh from the scene if (mesh) { scene.remove(mesh); } // Load the new model const loader = new THREE.OBJLoader(); loader.load(url, (obj) => { // Set the scale and position of the mesh obj.scale.set(1, 1, 1); obj.position.set(0, 75, 50); // Add the mesh to the scene mesh = obj; scene.add(mesh); }); } // Initialize the renderer init(); // Listen for changes to the model selector document.getElementById('model-selector').addEventListener('change', (event) => { const url = event.target.value; if (url) { loadModel(url); } }); // Render the scene function render() { requestAnimationFrame(render); renderer.render(scene, camera); mesh.rotation.z+=.01; } render(); </script> </body> </html> __________________________________ Soundcloud URL to iframe ----------------------------------- <script> // The SoundCloud URL to extract the track ID from const url = 'https://m.soundcloud.com/winterworks_gmbh/metal-stage'; // The URL of the CodeTabs proxy const proxyUrl = 'https://api.codetabs.com/v1/proxy?quest='; // Fetch the SoundCloud page source using the CodeTabs proxy fetch(proxyUrl + url) .then(response => response.text()) .then(pageSource => { // Check if the page source contains a "404 Not Found" error if (pageSource.includes('<title>404 Not Found</title>')) { throw new Error('The SoundCloud track could not be found.'); } // Extract the track ID from the page source const regex = /sounds:(\d+)/; const match = pageSource.match(regex); if (!match) { throw new Error('The SoundCloud track ID could not be found.'); } const trackID = match[1]; // Embed the SoundCloud player with the track ID const playerURL = `https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/${trackID}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`; const iframe = `<iframe width="100%" height="166" scrolling="no" frameborder="no" allow="autoplay" src="${playerURL}"></iframe>`; // Output the embedded player document.body.innerHTML = iframe; }) .catch(error => { console.error('Error:', error); }); </script> <plaintext> <?php // The SoundCloud URL to extract the track ID from $url = 'https://m.soundcloud.com/winterworks_gmbh/metal-stage'; // Fetch the SoundCloud page source $pageSource = file_get_contents($url); // Extract the track ID from the page source preg_match('/sounds:(\d+)/', $pageSource, $matches); $trackID = $matches[1]; // Embed the SoundCloud player with the track ID $playerURL = 'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/' . $trackID . '&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true'; $iframe = '<iframe width="100%" height="166" scrolling="no" frameborder="no" allow="autoplay" src="' . $playerURL . '"></iframe>'; // Output the embedded player echo $iframe; ?> ________________________________________________ Text Interspersion remover ----------------------------------------- <body> <textarea id="input-textbox" cols="60" rows="4"></textarea><br><br> <textarea id="output-textbox" cols="60" rows="4" style="border: none;"></textarea> <script> document.addEventListener("DOMContentLoaded", function() { // Get the input and output textbox elements const inputTextbox = document.getElementById("input-textbox"); const outputTextbox = document.getElementById("output-textbox"); // Add an event listener to the input textbox to detect changes inputTextbox.addEventListener("input", function() { // Remove all formatting characters from the textbox value const plainText = inputTextbox.value.replace(/[^\x00-\x7F]/g, ""); // Update the output textbox value with the plain text outputTextbox.value = plainText; }); }); </script> </body> </html> _________________________________ Reload page after X seconds ---------------------------------------------- <meta http-equiv="refresh" content="5" > https://stackoverflow.com/questions/4644027/how-to-automatically-reload-a-page-after-a-given-period-of-inactivity _____________________________________________________ Show last Github CommitAction + what was changed: ----------------------------------------------------------------------------------- <script> fetch('https://api.github.com/repos/Ry3yr/OSTR/commits?per_page=1') .then(res => res.json()) .then(res => { const latestCommit = res[0]; const message = latestCommit.commit.message; const date = new Date(latestCommit.commit.author.date).toLocaleDateString(); document.getElementById('message').innerHTML = `${message} - ${date}`; }) </script> <pre id="message">Loading</pre> _____________________________________ Display LastGithubUpdate: (requires proxy because of CORS) ---------------------------------------------------------------------------------------- <p id="last-updated"></p> <script> const atomFeedUrl = 'https://api.codetabs.com/v1/proxy?quest=https://github.com/Ry3yr/OSTR/releases.atom'; fetch(atomFeedUrl) .then(response => response.text()) .then(xmlText => { const parser = new DOMParser(); const xmlDocument = parser.parseFromString(xmlText, 'application/xml'); const lastUpdated = xmlDocument.querySelector('updated').textContent; const lastUpdatedElement = document.getElementById('last-updated'); lastUpdatedElement.textContent = `Last updated: ${lastUpdated}`; }) .catch(error => { console.error('Failed to fetch Atom feed:', error); }); </script> </body> </html> ____________________________________ Display (random) Code from txt file: ---------------------------------------- <script> fetch('https://ry3yr.github.io/OSTR/release/other/Computerstuff/Commands/HTML_Codes.txt') .then(response => response.text()) .then(fileContents => { const pattern = /------(.*?)_____/gs; const matches = fileContents.match(pattern).slice(1); // remove first match const randomIndex = Math.floor(Math.random() * matches.length); const randomMatch = matches[randomIndex]; const numLines = randomMatch.split('\n').length; if (numLines >= 3) { const plaintext = document.createElement('plaintext'); plaintext.textContent = randomMatch; document.body.appendChild(plaintext); } }); </script> ____________________________ Mastodon profile renderer: --------------------------------------- <script> const profileUrl = 'https://mastodon.social/api/v1/accounts/109977878421486714'; // Make a GET request to the profile URL using fetch fetch(profileUrl) .then(response => response.json()) .then(data => { // Access the fields in the JSON object const id = data.id; const username = data.username; const display_name = data.display_name; const locked = data.locked; const bot = data.bot; const discoverable = data.discoverable; const group = data.group; const created_at = data.created_at; const note = data.note; const url = data.url; const avatar = data.avatar; const avatar_static = data.avatar_static; const header = data.header; const header_static = data.header_static; const followers_count = data.followers_count; const following_count = data.following_count; const statuses_count = data.statuses_count; const last_status_at = data.last_status_at; const noindex = data.noindex; const emojis = data.emojis; const roles = data.roles; const fields = data.fields; // Do something with the data document.write(`${username}@mastodon.social<br>\n`); document.write(`<img src=${avatar} width=12%>`); document.write("<br><hr>"); document.write(`${note}`); document.write("<hr>"); //document.write(`${display_name}\n`); document.write(`Following: <b>${following_count}</b>\n`); document.write(`Followers: <b>${followers_count}</b>\n`); document.write(`Posts: <b>${statuses_count}</b>\n`); }) .catch(error => console.error(error)); </script> _____________________________________________ Youtube RSS render (with iframe support) ------------------------------------------------------------- <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.js"></script> <style> .youtube-video { margin: 20px; border: 1px solid #ccc; padding: 10px; border-radius: 5px; box-shadow: 2px 2px 5px #ccc; display: flex; flex-wrap: wrap; align-items: center; } .youtube-video img { margin-right: 10px; max-width: 200px; } .youtube-video h2 { margin-top: 0; } .youtube-video iframe { margin-left: 20px; } </style> </head> <body> <div id="youtube-feed"></div> <script> $(function() { var $content = $('#youtube-feed'); var data = { rss_url: 'https://www.youtube.com/feeds/videos.xml?channel_id=UCmIpOnd5BVx5Si2hp0WNKZw' }; $.get('https://api.rss2json.com/v1/api.json', data, function(response) { if (response.status == 'ok') { var output = ''; $.each(response.items, function(k, item) { const title = item.title; const titleShortened = (title.length > 60) ? title.substring(0, 60) + "..." : title; const thumbnail = item.thumbnail; const videoId = item.guid.split(':')[2]; const count = item.viewCount; const date = new Date(item.pubDate).toLocaleDateString(); const url = `https://www.youtube.com/watch?v=${videoId}`; const urlShortened = url.substring(0,60)+'...'; const embedUrl = `https://www.youtube.com/embed/${videoId}`; output += '<div class="youtube-video">'; output += `<a href="${url}" target="_blank"><img src="${thumbnail}" /></a>`; output += `<iframe width="260" height="115" src="${embedUrl}" frameborder="0" allowfullscreen></iframe>`; output += '<br>'; output += '<div>'; output += `<h2><a href="${url}" target="_blank">${titleShortened}</a></h2>`; output += `<p>Date: ${date}</p>`; output += '</div>'; output += '</div>'; return k < 9; }); $content.html(output).hide(); $content.fadeIn('slow'); } }); }); </script> </body> </html> __________________________________ Nitter RSS render (with image support) --------------------------------------------------------- <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.js"></script> <style> .medium-blog-image { display: flex; flex-wrap: wrap; justify-content: center; align-items: center; } .medium-blog-image img { margin: 5px; max-width: 100%; max-height: 200px; } </style> </head> <body> <div id="prita-medium-content"></div> <script> $(function() { var $content = $('#prita-medium-content'); var data = { rss_url: 'https://nitter.absturztau.be/alceawisteria/rss' }; $.get('https://api.rss2json.com/v1/api.json', data, function(response) { if (response.status == 'ok') { var output = ''; $.each(response.items, function(k, item) { output += '<div class="medium-blog-post" onclick="window.open(\'' + item.guid + '\',\'mywindow\');">' output += '<div class="medium-blog-title"><h2>' + item.title + '</h2></div>'; output += '<div class="medium-blog-date">' + $.format.date(item.pubDate, "MMM dd, yyyy") + '</div>'; output += '<div class="medium-blog-image">'; var $itemContent = $('<div>').html(item.content); $itemContent.find('img').each(function() { output += '<img src="' + $(this).attr('src') + '" />'; }); output += '</div>'; output += '</div>'; return k < 8; }); $content.html(output).hide(); $content.fadeIn('slow'); } }); }); </script> </body> <!-- partial --> </body> </html> https://codepen.io/ryedai1/pen/oNQompj __________________________________ Convert #Textfield "Enter" #events to "•" ----------------------------------------------------------- (To stop single line approaches from breaking ) <script> const descriptionTextarea = document.getElementById('description'); descriptionTextarea.addEventListener('keydown', function (event) { if (event.keyCode === 13) { event.preventDefault(); const currentValue = this.value; this.value = currentValue + '•'; } }); </script> _____________________________ Mastodon account ID lookup: ------------------------------------------ <!---account-id-lookup-https://pb.todon.de/api/v1/accounts/lookup?acct=@ryedai@mastodon.social--> <body> <label for="instance">Mastodon instance:</label> <input type="text" id="instance" value="mastodon.social"> <label for="username">Username:</label> <input type="text" id="username" value="ryedai"> <button onclick="fetchAvatarUrl()">Get UserID</button> <p id="avatarUrlContainer"></p> <script> function fetchAvatarUrl() { const instance = document.getElementById('instance').value; const username = document.getElementById('username').value; const rssUrl = `https://${instance}/@${username}.rss`; fetch(rssUrl) .then(response => response.text()) .then(xml => { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xml, 'text/xml'); const urlElement = xmlDoc.querySelector('url'); const url = urlElement.textContent; const startIndex = url.indexOf('avatars/') + 'avatars/'.length; const endIndex = url.indexOf('/original'); const avatarUrl = url.slice(startIndex, endIndex).replace(/\//g, ''); // Display the URL in the DOM const urlContainer = document.getElementById('avatarUrlContainer'); urlContainer.textContent = avatarUrl; }) .catch(error => console.error(error)); } </script> </body> </html> <!--<script> fetch('https://mastodon.social/@ryedai.rss') .then(response => response.text()) .then(xml => { const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xml, 'text/xml'); const urlElement = xmlDoc.querySelector('url'); const url = urlElement.textContent; const startIndex = url.indexOf('avatars/') + 'avatars/'.length; const endIndex = url.indexOf('/original'); const avatarUrl = url.slice(startIndex, endIndex).replace(/\//g, ''); const urlContainer = document.createElement('p'); urlContainer.textContent = avatarUrl; document.body.appendChild(urlContainer); }) .catch(error => console.error(error)); </script>--> _______________________________ Multi Account Mastodon api tl parser (with image/video/audio & youtube support & pixiv & tenor & imgbb-dir-img-link) ---------------------------------------------------------- <body> <div> <input type="radio" name="apiUrl" value="https://mastodon.social/api/v1/accounts/109977878421486714/statuses" checked> ryedai1 <input type="radio" name="apiUrl" value="https://pb.todon.de/api/v1/accounts/109629985010224381/statuses"> Alcea <!-- Add more radio buttons for additional instances --> <div id="feed"></div> </div> <script> // Function to fetch data from the selected API URL function fetchData(apiUrl) { const accessToken = 'your-access-token'; fetch(apiUrl, { headers: { 'Authorization': 'Bearer ' + accessToken } }) .then(response => response.json()) .then(data => { // Clear the feed before appending new content document.getElementById('feed').innerHTML = ''; data.forEach(status => { const content = '<div>' + status.content + '</div>'; let media = ''; let avatar = ''; let tootLink = ''; // Check for video and audio attachments if (status.media_attachments.length > 0) { media = '<div>'; status.media_attachments.forEach(attachment => { if (attachment.type === 'image') { media += '<img src="' + attachment.url + '" width="50%"><br>'; } else if (attachment.type === 'video') { media += '<video src="' + attachment.url + '" controls width="50%"></video><br>'; } else if (attachment.type === 'audio') { media += '<audio src="' + attachment.url + '" controls></audio><br>'; } }); media += '</div>'; } else { // Check for YouTube video link const youtubeRegex = /https?:\/\/(www\.)?(m\.)?youtube\.com\/watch\?v=([a-zA-Z0-9_-]{11})/; const youtubeMatch = status.content.match(youtubeRegex); if (youtubeMatch) { // Extract video ID from YouTube link const videoId = youtubeMatch[3]; // Create embedded player for YouTube video media = `<div><iframe width="560" height="315" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allowfullscreen></iframe></div>`; } else { // Check for Pixiv artwork link const pixivRegex = /https?:\/\/(?:www\.)?pixiv\.net\/(?:en\/)?artworks\/(\d+)/; const pixivMatch = status.content.match(pixivRegex); if (pixivMatch) { // Extract artwork ID from Pixiv link const artworkId = pixivMatch[1]; // Create image preview for Pixiv artwork media = `<div><img src="https://embed.pixiv.net/decorate.php?illust_id=${artworkId}&mode=sns-automator" width="50%"></div>`; } else { const tenorRegex = /https?:\/\/(?:www\.)?tenor\.com\/view\/[a-zA-Z0-9-]+-(\d+)/; const tenorMatch = status.content.match(tenorRegex); if (tenorMatch) { // Extract Tenor.com video ID const videoId = tenorMatch[1]; // Create embedded player for Tenor.com video media = `<div><iframe src="https://tenor.com/embed/${videoId}" frameborder="0" allowfullscreen="true" width="100%" height="400px"></iframe></div>`; }else{ // Check for imgbb image URLs in the status content const imageRegex = /(https?:\/\/(?:www\.)?i\.ibb\.co\/[^ ]+\.(?:jpg|png|gif|bmp))/g; const imageMatches = status.content.match(imageRegex); if (imageMatches) { media += '<div>'; imageMatches.forEach(url => { media += '<img src="' + url + '" width="50%"><br>'; }); media += '</div>'; } } } } } // Check for spoiler tag if (status.url.includes('activity')) { avatar = '<!--<details><summary>Avatar (spoiler)</summary><img src="' + status.account.avatar + '" width="100px"></details>--><br>'; tootLink = '<!--<details><summary>View on Mastodon (spoiler)</summary><a href="' + status.url + '" target="_blank">Click here to view activity</a></details>-->'; } else { avatar = '<img src="' + status.account.avatar + '" width="100px"><br>'; tootLink = '<a href="' + status.url + '" target="_blank">View on Mastodon</a>'; } // Get the date of the status const date = new Date(status.created_at); // Append content to feed document.getElementById('feed').innerHTML += content + media + avatar + tootLink + '&nbsp;' + date.toLocaleString() + '<hr>'; }); }) .catch(error => console.error(error)); } // Event listener for radio button change const radioButtons = document.querySelectorAll('input[name="apiUrl"]'); radioButtons.forEach(radioButton => { radioButton.addEventListener('change', function() { const selectedApiUrl = this.value; fetchData(selectedApiUrl); }); }); // Initial fetch using the default API URL const defaultApiUrl = 'https://mastodon.social/api/v1/accounts/109977878421486714/statuses'; fetchData(defaultApiUrl); </script> </body> ______________________________ Mastodon api timeline parser (with image/video/audio & youtube support & pixiv) ------------------------------------------------------------------------------------------- <body> <div id="feed"></div> <script> const apiUrl = 'https://mastodon.social/api/v1/accounts/109977878421486714/statuses'; const accessToken = 'your-access-token'; fetch(apiUrl, { headers: { 'Authorization': 'Bearer ' + accessToken } }) .then(response => response.json()) .then(data => { data.forEach(status => { const content = '<div>' + status.content + '</div>'; let media = ''; let avatar = ''; let tootLink = ''; // Check for video and audio attachments if (status.media_attachments.length > 0) { media = '<div>'; status.media_attachments.forEach(attachment => { if (attachment.type === 'image') { media += '<img src="' + attachment.url + '" width="50%"><br>'; } else if (attachment.type === 'video') { media += '<video src="' + attachment.url + '" controls width="50%"></video><br>'; } else if (attachment.type === 'audio') { media += '<audio src="' + attachment.url + '" controls></audio><br>'; } }); media += '</div>'; } else { // Check for YouTube video link const youtubeRegex = /https?:\/\/(www\.)?(m\.)?youtube\.com\/watch\?v=([a-zA-Z0-9_-]{11})/; const youtubeMatch = status.content.match(youtubeRegex); if (youtubeMatch) { // Extract video ID from YouTube link const videoId = youtubeMatch[3]; // Create embedded player for YouTube video media = `<div><iframe width="560" height="315" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allowfullscreen></iframe></div>`; } else { // Check for Pixiv artwork link const pixivRegex = /https?:\/\/(?:www\.)?pixiv\.net\/(?:en\/)?artworks\/(\d+)/; const pixivMatch = status.content.match(pixivRegex); if (pixivMatch) { // Extract artwork ID from Pixiv link const artworkId = pixivMatch[1]; // Create image preview for Pixiv artwork media = `<div><img src="https://embed.pixiv.net/decorate.php?illust_id=${artworkId}&mode=sns-automator" width="50%"></div>`; } } } // Check for spoiler tag if (status.url.includes('activity')) { avatar = '<!--<details><summary>Avatar (spoiler)</summary><img src="' + status.account.avatar + '" width="100px"></details>--><br>'; tootLink = '<!--<details><summary>View on Mastodon (spoiler)</summary><a href="' + status.url + '" target="_blank">Click here to view activity</a></details>-->'; } else { avatar = '<img src="' + status.account.avatar + '" width="100px"><br>'; tootLink = '<a href="' + status.url + '" target="_blank">View on Mastodon</a>'; } // Get the date of the status const date = new Date(status.created_at); // Append content to feed document.getElementById('feed').innerHTML += content + media + avatar + tootLink + '&nbsp;' + date.toLocaleString() + '<hr>'; }); }) .catch(error => console.error(error)); </script> </body> __________________________________________________ Mastodon api timeline parser (with image & youtube support) ------------------------------------------------------------------------------------------- <body> <div id="feed"></div> <script> const apiUrl = 'https://mastodon.social/api/v1/accounts/109977878421486714/statuses'; const accessToken = 'your-access-token'; fetch(apiUrl, { headers: { 'Authorization': 'Bearer ' + accessToken } }) .then(response => response.json()) .then(data => { data.forEach(status => { const content = '<div>' + status.content + '</div>'; let media = ''; let avatar = ''; let tootLink = ''; // Check for YouTube video link const youtubeRegex = /https?:\/\/(www\.)?(m\.)?youtube\.com\/watch\?v=([a-zA-Z0-9_-]{11})/; const youtubeMatch = status.content.match(youtubeRegex); if (youtubeMatch) { // Extract video ID from YouTube link const videoId = youtubeMatch[3]; // Create embedded player for YouTube video media = `<div><iframe width="560" height="315" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allowfullscreen></iframe></div>`; } else { // Check for image attachments if (status.media_attachments.length > 0) { media = '<div>'; status.media_attachments.forEach(attachment => { if (attachment.type === 'image') { media += '<img src="' + attachment.url + '" width="50%"><br>'; } }); media += '</div>'; } } // Check for spoiler tag if (status.url.includes('activity')) { avatar = '<!--<details><summary>Avatar (spoiler)</summary><img src="' + status.account.avatar + '" width="100px"></details>--><br>'; tootLink = '<!--<details><summary>View on Mastodon (spoiler)</summary><a href="' + status.url + '" target="_blank">Click here to view activity</a></details>-->'; } else { avatar = '<img src="' + status.account.avatar + '" width="100px"><br>'; tootLink = '<a href="' + status.url + '" target="_blank">View on Mastodon</a>'; } // Get the date of the status const date = new Date(status.created_at); // Append content to feed document.getElementById('feed').innerHTML += content + media + avatar + tootLink + '&nbsp;' + date.toLocaleString() + '<hr>'; }); }) .catch(error => console.error(error)); </script> </body> ________________________________ Mastodon api timeline parser: ---------------------------------------------- <div id="feed"></div> <script> const apiUrl = 'https://mastodon.social/api/v1/accounts/109977878421486714/statuses'; //const userId = '109977878421486714'; const accessToken = 'your-access-token'; fetch(apiUrl, { headers: { 'Authorization': 'Bearer ' + accessToken } }) .then(response => response.json()) .then(data => { data.forEach(status => { const content = '<div>' + status.content + '</div>'; const avatar = '<img src="' + status.account.avatar + '" width="100px"><br><hr>'; document.getElementById('feed').innerHTML += content + avatar; }); }) .catch(error => console.error(error)); </script> <!-- partial --> </body> </html> __________________________________ DragNDrop FileLister (&Search) ------------------------------ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Drag and Drop Folder</title> </head> <body> <img src="https://www.solar-fox.de/files/oneo/img/soledos/logos/meteocontrol_neu.png" width="30%"><br> <input type="file" id="folder-selector" webkitdirectory directory="C:\Konfi-Data\Export"><br><br> <div id="dropzone">Drop a folder here</div> <input type="text" id="searchBox" placeholder="Search..."> <input type="text" id="keyword" placeholder="Count element"> <div id="count"></div> <button id="countTodayButton">Done today</button> <ul id="fileList"></ul> <script> var dropzone = document.getElementById('dropzone'); var fileList = document.getElementById('fileList'); var timestamps = { today: [], yesterday: [] }; var elementsDoneToday = 0; dropzone.addEventListener('dragover', function(event) { event.preventDefault(); }); dropzone.addEventListener('drop', function(event) { event.preventDefault(); var items = event.dataTransfer.items; for (var i = 0; i < items.length; i++) { var item = items[i]; if (item.kind === 'file' && item.webkitGetAsEntry().isDirectory) { traverseFileTree(item.webkitGetAsEntry(), function(file) { var timestamp = new Date(file.lastModified); var today = new Date(); today.setHours(0,0,0,0); var yesterday = new Date(today); yesterday.setDate(today.getDate() - 1); if (timestamp >= today) { timestamps.today.push(file.lastModified); } else if (timestamp >= yesterday) { timestamps.yesterday.push(file.lastModified); } var li = document.createElement('li'); li.textContent = file.name + " (" + timestamp.toLocaleString() + ")"; fileList.appendChild(li); var index = timestamps.today.indexOf(file.lastModified); if (index === -1) { index = timestamps.yesterday.indexOf(file.lastModified) + timestamps.today.length; } fileList.insertBefore(li, fileList.childNodes[index]); if (timestamp >= today) { elementsDoneToday++; } }); } } countDiv.textContent = 'Elements done today: ' + (timestamps.today.length); }); function traverseFileTree(item, callback) { var dirReader = item.createReader(); var entries = []; function readEntries() { dirReader.readEntries(function(results) { if (!results.length) { // All entries have been read entries.forEach(function(entry) { if (entry.isFile) { entry.file(function(file) { callback(file); }); } else if (entry.isDirectory) { traverseFileTree(entry, callback); } }); } else { // Read next set of entries entries = entries.concat(Array.from(results)); readEntries(); } }); } readEntries(); } var searchBox = document.getElementById('searchBox'); searchBox.addEventListener('input', function(event) { var searchTerm = event.target.value.toLowerCase(); var fileItems = fileList.getElementsByTagName('li'); for (var i = 0; i < fileItems.length; i++) { var fileName = fileItems[i].textContent.toLowerCase(); if (fileName.indexOf(searchTerm) === -1) { fileItems[i].classList.add('hidden'); } else { fileItems[i].classList.remove('hidden'); } } }); var keywordInput = document.getElementById('keyword'); var countDiv = document.getElementById('count'); var keywordCount = 0; keywordInput.addEventListener('input', function(event) { var keyword = event.target.value.toLowerCase(); var fileItems = fileList.getElementsByTagName('li'); keywordCount = 0; for (var i = 0; i < fileItems.length; i++) { var fileName = fileItems[i].textContent.toLowerCase(); if (fileName.indexOf(keyword) !== -1) { keywordCount++; } } countDiv.textContent = 'Number of files containing "' + keyword + '": ' + keywordCount; }); var countTodayButton = document.getElementById('countTodayButton'); countTodayButton.addEventListener('click', function() { var today = new Date(); today.setHours(0,0,0,0); elementsDoneToday = 0; for (var i = 0; i < timestamps.today.length; i++) { if (timestamps.today[i] >=today) { elementsDoneToday++; } } countDiv.textContent = 'Elements done today: ' + elementsDoneToday; }); </script> <style> #dropzone { width: 500px; height: 100px; border: 2px dashed black; text-align: center; padding-top: 80px; font-size: 24px; } .hidden { display: none; } </style> </body> </html> ___________________________________________ GDrive Direct link transform: ------------------------------------------ <body> <textarea id="myGDriveTextBox" style="width: 500px; height: 300px;"></textarea> <br> <button onclick="modifyLinks()">Modify Links</button> <br> <div id="modifiedLinks"></div> <script> function modifyLinks() { var textBox = document.getElementById("myGDriveTextBox"); var text = textBox.value; text = text.replace(/https:\/\/drive.google.com\/file\/d\/([\w-]+)\/view\?usp=sharing/g, "https://drive.google.com/uc?export=download&id=$1"); var modifiedLinksDiv = document.getElementById("modifiedLinks"); modifiedLinksDiv.innerHTML = "<pre>" + text + "</pre>"; } </script> </body> </html> ________________________ Pixiv Style Color BG Hashtag link: -------------------------------------------------- <a target="_blank" href="https://www.pixiv.net/en/users/75406576/artworks/%E6%B5%81%E6%98%9F%E3%81%AE%E3%83%AD%E3%83%83%E3%82%AF%E3%83%9E%E3%83%B3" style="background-color: red; padding: 5px; border-radius: 10px; text-decoration: none; color: white;">#Megaman Starforce</a> ______________________ Extract PlaystoreAppID from URL: ----------------------------------------------------- <script> function extractElement() { const inputUrl = document.getElementById('input-url').value; const regex = /details\?id=([^&]+)&hl=/; const matches = inputUrl.match(regex); if (matches && matches.length > 1) { const extractedElement = matches[1]; document.getElementById('result').textContent = extractedElement; } else { document.getElementById('result').textContent = 'Element not found'; } } </script> </head> <body> <label for="input-url">Enter URL:</label> <input type="text" id="input-url" style="width: 80%;"> <button onclick="extractElement()">Extract</button> <p id="result"></p> </body> </html> ____________________ Dekudeals JSON parser ---------------------------------------------------------------------------- <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Aoi's Collection | Deku Deals</title> </head> <body> <a target="_blank" href="https://www.dekudeals.com/collection/nw7vnrstb9">Link</a>&nbsp; <a target="_blank" href="http://alceawisteria.byethost7.com/PHP/0demo/2023-04-30-parse-json/parse.php#inks/more/67087617">reload</a> <a target="_blank" href="http://gg.gg/dekudealsgamezisecollectionjson">Add (Gamesizes) to json</a><br> <style> .tooltip { position: relative; display: inline-block; cursor: pointer; } .tooltip .tooltiptext { visibility: hidden; width: 200px; background-color: #000; color: #fff; text-align: center; border-radius: 5px; padding: 5px; position: absolute; z-index: 1; bottom: 125%; left: 50%; transform: translateX(-50%); opacity: 0; transition: opacity 0.3s; } .tooltip:hover .tooltiptext { visibility: visible; opacity: 1; } </style> </head> <body> <div id="collection-table"></div> <script> fetch('https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/collection.json') .then(response => response.json()) .then(data => { let totalPhysicalGames = 0; let totalPhysicalPrice = 0; let totalAllPrice = 0; let tableHtml = ` <table> <tr> <th>Link</th> <th>Format <a href="?sort=format_asc">^</a> / <a href="?sort=format_desc">v</a></th> <th>Price <a href="?sort=price_asc">^</a> / <a href="?sort=price_desc">v</a></th> <th>Status <a href="?sort=status_asc">^</a> / <a href="?sort=status_desc">v</a></th> <th>Date Added <a href="?sort=date_asc">^</a> / <a href="?sort=date_desc">v</a></th> <th>Gamesize</th> </tr> `; const urlParams = new URLSearchParams(window.location.search); const sortBy = urlParams.get('sort'); if (sortBy === 'price_asc') { data.items.sort((a, b) => a.price_paid - b.price_paid); } else if (sortBy === 'price_desc') { data.items.sort((a, b) => b.price_paid - a.price_paid); } else if (sortBy === 'format_asc') { data.items.sort((a, b) => a.format.localeCompare(b.format)); } else if (sortBy === 'format_desc') { data.items.sort((a, b) => b.format.localeCompare(a.format)); } else if (sortBy === 'date_asc') { data.items.sort((a, b) => new Date(a.added_at) - new Date(b.added_at)); } else if (sortBy === 'date_desc') { data.items.sort((a, b) => new Date(b.added_at) - new Date(a.added_at)); } else if (sortBy === 'status_asc') { data.items.sort((a, b) => (a.status || '').localeCompare(b.status || '')); } else if (sortBy === 'status_desc') { data.items.sort((a, b) => (b.status || '').localeCompare(a.status || '')); } data.items.forEach(item => { let status = item.status || ''; let formatCell = item.format; let extrainfo = ''; if (item.note && item.note.includes("DigitalAlso")) { extrainfo = ' DigitalAlso'; } let imageUrl = item.image; tableHtml += ` <tr> <td> <div class="tooltip"> <img src="${imageUrl}" width="20" height="20"> <span class="tooltiptext">${item.note}</span> <a target="_blank" href="${item.link}">${item.name}</a>${extrainfo} </div> </td> <td>${formatCell}</td> <td>${item.price_paid}</td> <td>${status}</td> <td>${new Date(item.added_at).toLocaleDateString()}</td> <td>${item.gamesize}</td> </tr> `; if (item.format === "physical") { totalPhysicalGames++; totalPhysicalPrice += item.price_paid; } totalAllPrice += item.price_paid; }); tableHtml += ` </table> <p>• Total Games: ${data.items.length} • Physical Games: ${totalPhysicalGames} <br><hr> • Physical Price: ${totalPhysicalPrice} • Total All Price: ${totalAllPrice}</p> `; const collectionTableDiv = document.getElementById('collection-table'); collectionTableDiv.innerHTML = tableHtml; }) .catch(error => console.log(error)); </script> _________________ Extract "€" values and display subtotal (JS version - broken url import) ---------------------------------------- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Calculate Total</title> <script> async function calculateTotal(event) { event.preventDefault(); const urlInput = document.querySelector('#url'); const textAreaInput = document.querySelector('textarea[name="input"]'); const keywordInput = document.querySelector('input[name="keyword"]'); const resultElement = document.querySelector('#result'); const matchingLinesElement = document.querySelector('#matching-lines'); let input = ''; const url = urlInput.value; if (url) { const response = await fetch(url); const text = await response.text(); input = text.replace(/<[^>]+>/g, ''); // strip tags } else { input = textAreaInput.value; } let total = 0; const keyword = keywordInput.value; const lines = input.split('\n'); const matchingLines = []; let isFirstLine = true; lines.forEach((line) => { if (!keyword || line.includes(keyword)) { if (isFirstLine && url) { isFirstLine = false; return; } const matches = line.matchAll(/(\d+)[€]/g); for (const match of matches) { total += parseInt(match[1]); } matchingLines.push(line); } }); resultElement.textContent = `Total value for '${keyword || 'all'}' lines: €${total}`; if (matchingLines.length > 0 && keyword) { matchingLinesElement.innerHTML = '<h2>Matching lines:</h2><ul>' + matchingLines.map(line => `<li>${line}</li>`).join('') + '</ul>'; } else { matchingLinesElement.innerHTML = ''; } } </script> </head> <body> <form onsubmit="calculateTotal(event)"> <label for="url">URL:</label> <input type="text" name="url" id="url"> <br> <textarea name="input"></textarea> <br> Keyword: <input type="text" name="keyword"> <br> <button type="submit">Calculate total</button> </form> <div id="result"></div> <div id="matching-lines"></div> </body> </html> __________________ Redirect Code URL Transformer with dld function: -------------------------------- <textarea id="url-input" rows="15" cols="60"><meta http-equiv="refresh" content="0; https://website.com"> <script type="text/javascript"> window.location.href = "https://website.com" </script> <title>Homepage</title> </head> <body> <!-- Note: don't tell people to `click` the link, just tell them that it is a link. --> If you are not redirected automatically, follow this <a href='https://website.com'>-</a>. </body> </html></textarea><br> <input type="text" id="new-url"> <button onclick="changeUrl()">Change URL</button> <button onclick="downloadHtml()">DLD</button> <script> function changeUrl() { var newUrl = document.getElementById('new-url').value; if (newUrl !== '') { var html = document.getElementById('url-input').value; html = html.replaceAll('https://website.com', newUrl); document.getElementById('url-input').value = html; document.querySelector('meta[http-equiv="refresh"]').setAttribute('content', '0; ' + newUrl); } } function downloadHtml() { var htmlContent = document.getElementById('url-input').value; var filename = 'page.html'; var blob = new Blob([htmlContent], {type: 'text/html'}); var link = document.createElement('a'); link.download = filename; link.href = URL.createObjectURL(blob); document.body.appendChild(link); link.click(); document.body.removeChild(link); } </script> _________________ Date URL Transformer (Nintendo Direct): --------------------------------- <div id="url-container"></div> <script> const currentDate = new Date(); const day = currentDate.getDate(); const month = currentDate.getMonth() + 1; const year = currentDate.getFullYear(); const formattedDay = day < 10 ? `0${day}` : day; const formattedMonth = month < 10 ? `0${month}` : month; const url = `https://www.nintendo.com/nintendo-direct/${formattedMonth}-${formattedDay}-${year}/`; const urlContainer = document.getElementById('url-container'); urlContainer.innerHTML = `<a target="_blank" href="${url}">${url}</a>`; </script> ___________ Parse RSS + Description: -------------------------------------- <script> fetch('https://paper.wf/alcea/feed/') .then(response => response.text()) .then(data => { const parser = new DOMParser(); const xml = parser.parseFromString(data, 'text/xml'); const items = xml.querySelectorAll('item'); const titles = Array.from(items).map(item => item.querySelector('title').textContent); const descriptions = Array.from(items).map(item => item.querySelector('description').innerHTML); const links = Array.from(items).map(item => item.querySelector('link').textContent); const container = document.createElement('div'); titles.forEach((title, index) => { const item = document.createElement('div'); const itemTitle = document.createElement('h3'); const itemDescription = document.createElement('p'); const itemLink = document.createElement('a'); itemTitle.textContent = title; itemDescription.innerHTML = descriptions[index]; itemLink.textContent = 'Read more'; itemLink.href = links[index]; item.appendChild(itemTitle); item.appendChild(itemDescription); item.appendChild(itemLink); container.appendChild(item); }); document.body.appendChild(container); }) .catch(error => console.log(error)); </script> _________________________________ Parse RSS with image support: ----------------------------------------------- <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.js"></script> <style> .medium-blog-image { display: flex; flex-wrap: wrap; justify-content: center; align-items: center; } .medium-blog-image img { margin: 5px; max-width: 100%; max-height: 200px; } </style> </head> <body> <div id="prita-medium-content"></div> <script> $(function() { var $content = $('#prita-medium-content'); var data = { rss_url: 'https://rsshub.app/pixiv/user/75406576' }; $.get('https://api.rss2json.com/v1/api.json', data, function(response) { if (response.status == 'ok') { var output = ''; $.each(response.items, function(k, item) { output += '<div class="medium-blog-post" onclick="window.open(\'' + item.guid + '\',\'mywindow\');">' output += '<div class="medium-blog-title"><h2>' + item.title + '</h2></div>'; output += '<div class="medium-blog-date">' + $.format.date(item.pubDate, "MMM dd, yyyy") + '</div>'; output += '<div class="medium-blog-image">'; $(item.content).find('img').each(function() { output += '<img src="' + $(this).attr('src') + '" />'; }); output += '</div>'; output += '</div>'; return k < 3; }); $content.html(output).hide(); $content.fadeIn('slow'); } }); }); </script> </body> ________________ Simple RSS Render: ------------------------------ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css"> </head> <body> <!-- partial:index.partial.html --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="https://www.jquery-plugins.net/FeedEK/FeedEk.min.js"></script> <div id="divRss" class="perrea_nena"></div> <script> $('#divRss').FeedEk({ FeedUrl : 'https://rsshub.app/pixiv/user/75406576', MaxCount : 5, ShowDesc : true, DescCharacterLimit:80, ShowPubDate:false, TitleLinkTarget:'_blank', }); </script> <!-- partial --> <script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> </body> ________________ YT Channel Preview Tag html generator ----------------------------------------------------------- <hr> <body> <div> <label for="channel-url-input">Channel URL:</label> <input type="text" id="channel-url-input"> </div> <div> <label for="channel-image-input">Channel Image URL:</label> <input type="text" id="channel-image-input"> </div> <div> <label for="channel-name-input">Channel Name:</label> <input type="text" id="channel-name-input"> </div> <div> <label for="video-url-input">Video URL:</label> <input type="text" id="video-url-input"> </div> <div> <label for="video-title-input">Video Title:</label> <input type="text" id="video-title-input"> </div> <button onclick="fillVideo()">Fill Video</button> <br><br> <div style="display: flex;"> <div> <label for="html-output">HTML Output:</label> <textarea id="html-output"></textarea> </div> <div id="preview-container" style="margin-left: 50px;"></div> </div> <script> function fillVideo() { let channelUrl = document.getElementById("channel-url-input").value.trim(); let channelImage = document.getElementById("channel-image-input").value.trim(); let channelName = document.getElementById("channel-name-input").value.trim(); let videoUrl = document.getElementById("video-url-input").value.trim(); let videoTitle = document.getElementById("video-title-input").value.trim(); let channelLink = document.createElement("a"); channelLink.href = channelUrl; let channelImageElement = document.createElement("img"); channelImageElement.alt = "Channel Image"; channelImageElement.src = channelImage; channelImageElement.height = 50; channelImageElement.width = 50; channelLink.appendChild(channelImageElement); let channelNameElement = document.createElement("span"); channelNameElement.textContent = channelName; let videoLink = document.createElement("a"); videoLink.href = videoUrl; let videoTitleElement = document.createElement("span"); videoTitleElement.textContent = videoTitle; let videoContainer = document.createElement("div"); videoContainer.appendChild(channelLink); videoContainer.appendChild(channelNameElement); videoContainer.appendChild(document.createElement("br")); videoContainer.appendChild(videoLink); videoLink.appendChild(videoTitleElement); let htmlString = videoContainer.outerHTML; let htmlOutput = document.getElementById("html-output"); htmlOutput.value = htmlString; let previewContainer = document.getElementById("preview-container"); previewContainer.innerHTML = htmlString; } </script> </body> <hr> __________________ Render html/text as "plaintext": (useful for codedumps) -------------------------------------- <plaintext> text </plaintext> ____________________________________ Load URL into dom onload automatically -------------------------------------------------------- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <a href="#" id="navLink" style="color:transparent">-</a> <div id="outputnav"></div> <script> $(document).ready(function() { $("#navLink").trigger("click"); }); $("#navLink").on("click", function() { $("#outputnav").load("https://ry3yr.github.io/OSTR/Unresoundtracker/navigationalt.html"); }); </script> ________________________________________________________________________________________________ Fetch sitepart between via delimiter ---------------------------------------- <details> <div id="content"></div> <script> const baseUrl = "https://alceawis.de"; // Base URL fetch("https://alceawis.de/code.html") .then(response => response.text()) .then(data => { const start = data.indexOf("CMDS") + 4; const end = data.indexOf("CodeDistribution") - 0; const content = data.substring(start, end); // Create a temporary element to parse the content as HTML const tempElement = document.createElement("div"); tempElement.innerHTML = content; // Find and convert relative URLs to absolute URLs const relativeUrls = tempElement.querySelectorAll("a[href], img[src]"); relativeUrls.forEach(url => { const originalUrl = url.getAttribute("href") || url.getAttribute("src"); const absoluteUrl = new URL(originalUrl, baseUrl).href; url.setAttribute("href", absoluteUrl); url.setAttribute("src", absoluteUrl); }); // Append the modified content to the target element document.getElementById("content").appendChild(tempElement); }); </script> </details><br> ====relative version: === <body> <div id="content"></div> <script> fetch("https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Cool_Stuff.html") .then(response => response.text()) .then(data => { const start = data.indexOf("Tools") + 5; const end = data.indexOf("Hobbies") - 7; const content = data.substring(start, end); document.getElementById("content").innerHTML = content; }) .catch(error => console.log(error)); </script> </body> </html> (Source: to php equiv: "now do it in js and display into dom") ________________________________________________________________________________________________ Render PDF on button press: ----------------------------------------------- <div id="holder"></div> <button id="renderButton">YGODECK</button> <script src='https://cdn.jsdelivr.net/npm/pdfjs-dist@2.0.385/build/pdf.min.js'></script> <script> function renderPDF(url, canvasContainer, options) { options = options || { scale: 2 }; function renderPage(page) { var viewport = page.getViewport(options.scale); var wrapper = document.createElement("div"); wrapper.className = "canvas-wrapper"; var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var renderContext = { canvasContext: ctx, viewport: viewport }; canvas.height = viewport.height; canvas.width = viewport.width; wrapper.appendChild(canvas) canvasContainer.appendChild(wrapper); page.render(renderContext); } function renderPages(pdfDoc) { for(var num = 1; num <= pdfDoc.numPages; num++) pdfDoc.getPage(num).then(renderPage); } PDFJS.disableWorker = true; // Add event listener to the render button document.getElementById('renderButton').addEventListener('click', function() { PDFJS.getDocument(url).then(renderPages); // Disable the button after rendering this.disabled = true; }); } renderPDF('https://ry3yr.github.io/0curr-irl.pdf', document.getElementById('holder')); </script> ________________________________ Render pdf directly ----------------------------- <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css"> <link rel="stylesheet" href="./style.css"> </head> <body> <!-- partial:index.partial.html --> <div id="holder"></div> <!-- partial --> <script src='https://cdn.jsdelivr.net/npm/pdfjs-dist@2.0.385/build/pdf.min.js'></script> <script> function renderPDF(url, canvasContainer, options) { options = options || { scale: 1 }; function renderPage(page) { var viewport = page.getViewport(options.scale); var wrapper = document.createElement("div"); wrapper.className = "canvas-wrapper"; var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var renderContext = { canvasContext: ctx, viewport: viewport }; canvas.height = viewport.height; canvas.width = viewport.width; wrapper.appendChild(canvas) canvasContainer.appendChild(wrapper); page.render(renderContext); } function renderPages(pdfDoc) { for(var num = 1; num <= pdfDoc.numPages; num++) pdfDoc.getPage(num).then(renderPage); } PDFJS.disableWorker = true; PDFJS.getDocument(url).then(renderPages); } renderPDF('https://ry3yr.github.io/OSTR/release/other/game/ygo/deck/0curr-irl.pdf', document.getElementById('holder')); </script> </body> </html> ________________________________ Render pdf in webbrowser ----------------------------------------- <!DOCTYPE html> <html> <head> <title>PDF Viewer</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.2/pdf.js"></script> </head> <body> <label for="pdf-upload">Upload PDF:</label> <input type="file" id="pdf-upload" accept="application/pdf"/> <label for="pdf-url">PDF URL:</label> <input type="text" id="pdf-url" placeholder="Enter PDF URL"/> <button id="load-pdf">Load PDF</button> <button id="zoom-in" style="background:transparent; border:transparent;display: none;">Zoom In</button> <div id="zoom-percent" style="background:transparent; border:transparent;display: none;">60</div> <button id="zoom-out" style="background:transparent; border:transparent;display: none;">Zoom Out</button> <button id="zoom-reset" style="background:transparent; border:transparent;display: none;">Reset Zoom</button> <div id="pages"></div> <script> pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.2/pdf.worker.js'; document.querySelector("#pdf-upload").addEventListener("change", function(e){ document.querySelector("#pages").innerHTML = ""; zoomReset(); var file = e.target.files[0] if(file.type != "application/pdf"){ alert(file.name + " is not a pdf file.") return } var fileReader = new FileReader(); fileReader.onload = function() { var typedarray = new Uint8Array(this.result); pdfjsLib.getDocument(typedarray).promise.then(function(pdf) { // you can now use *pdf* here console.log("the pdf has", pdf.numPages, "page(s)."); for (var i = 0; i < pdf.numPages; i++) { (function(pageNum){ pdf.getPage(i+1).then(function(page) { // you can now use *page* here var viewport = page.getViewport(2.0); var pageNumDiv = document.createElement("div"); pageNumDiv.className = "pageNumber"; pageNumDiv.innerHTML = "Page " + pageNum; var canvas = document.createElement("canvas"); canvas.className = "page"; canvas.title = "Page " + pageNum; document.querySelector("#pages").appendChild(pageNumDiv); document.querySelector("#pages").appendChild(canvas); canvas.height = viewport.height; canvas.width = viewport.width; page.render({ canvasContext: canvas.getContext('2d'), viewport: viewport }).promise.then(function(){ console.log('Page rendered'); }); page.getTextContent().then(function(text){ console.log(text); }); }); })(i+1); } }); }; fileReader.readAsArrayBuffer(file); }); document.querySelector("#load-pdf").addEventListener("click", function(){ document.querySelector("#pages").innerHTML = ""; zoomReset(); var url = document.querySelector("#pdf-url").value.trim(); if (!url) { alert("Please enter a PDF URL."); return; } if (!url.endsWith(".pdf")) { alert("Please enter a valid PDF URL."); return; } fetch(url).then(function(response) { if (!response.ok) { throw new Error(response.statusText); } return response.arrayBuffer(); }).then(function(buffer) { pdfjsLib.getDocument(buffer).promise.then(function(pdf) { // you can now use *pdf* here console.log("the pdf has", pdf.numPages, "page(s)."); for (var i = 0; i < pdf.numPages; i++) { (function(pageNum){ pdf.getPage(i+1).then(function(page) { // you can now use *page* here var viewport = page.getViewport(2.0); var pageNumDiv = document.createElement("div"); pageNumDiv.className = "pageNumber"; pageNumDiv.innerHTML = "Page " + pageNum; var canvas = document.createElement("canvas"); canvas.className = "page"; canvas.title = "Page " + pageNum; document.querySelector("#pages").appendChild(pageNumDiv); document.querySelector("#pages").appendChild(canvas); canvas.height = viewport.height; canvas.width = viewport.width; page.render({ canvasContext: canvas.getContext('2d'), viewport: viewport }).promise.then(function(){ console.log('Page rendered'); }); page.getTextContent().then(function(text){ console.log(text); }); }); })(i+1); } }); }).catch(function(error) { alert("Failed to load PDF: " + error.message); }); }); var curWidth = 60; function zoomIn(){ if (curWidth < 150) { curWidth += 10; document.querySelector("#zoom-percent").innerHTML = curWidth; document.querySelectorAll(".page").forEach(function(page){ page.style.width = curWidth + "%"; }); } } function zoomOut(){ if (curWidth > 20) { curWidth -= 10; document.querySelector("#zoom-percent").innerHTML = curWidth; document.querySelectorAll(".page").forEach(function(page){ page.style.width = curWidth + "%"; }); } } function zoomReset(){ curWidth = 60; document.querySelector("#zoom-percent").innerHTML = curWidth; document.querySelectorAll(".page").forEach(function(page){ page.style.width = curWidth + "%"; }); } document.querySelector("#zoom-in").onclick = zoomIn; document.querySelector("#zoom-out").onclick = zoomOut; document.querySelector("#zoom-reset").onclick = zoomReset; window.onkeypress = function(e){ if (e.code == "Equal") { zoomIn(); } if (e.code == "Minus") { zoomOut(); } }; </script> </body> </html> https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/pdffilerender.html https://codepen.io/ryedai1/full/KKGYemE ________________________________________________________________________________________________ Fetch all links from site & display --------------------------------------------------- <script> fetch('https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Art.html') .then(response => response.text()) .then(data => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(data, 'text/html'); const base = htmlDoc.createElement('base'); base.href = 'https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Art.html'; htmlDoc.head.appendChild(base); const links = htmlDoc.querySelectorAll('a[href]'); const linkList = document.createElement('ul'); links.forEach(link => { const listItem = document.createElement('li'); const anchor = document.createElement('a'); anchor.href = link.href; anchor.target = '_blank'; // Set target to _blank anchor.textContent = link.href; listItem.appendChild(anchor); linkList.appendChild(listItem); }); document.body.appendChild(linkList); }) .catch(error => console.error(error)); </script> ______________________ Fetch and Display images from website: -------------------------------------- <script> const url = 'https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/index.html'; fetch(url) .then(response => response.text()) .then(data => { const parser = new DOMParser(); const html = parser.parseFromString(data, "text/html"); const images = html.querySelectorAll("img"); images.forEach(image => { const imageUrl = image.getAttribute("src"); const img = document.createElement("img"); img.src = imageUrl; document.body.appendChild(img); }); }); </script> (Source: chatgpt.org.ua "write javascript image parser for https://app.box.com/s/j7i88s6jb4yyk4wmiti4tol8ejoikdhl" ) _____________________________________ Click link on page load (if# exists in url): --------------------------------- <a id=linky href=""></a> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { if (window.location.href.indexOf("alceawisteria") > -1) { //alert("your url contains the name franky"); document.getElementById('linky').click(); window.history.back(); window.close(); } }); </script> (put script part at very end of page to make it work) (Source: https://stackoverflow.com/questions/4597050/how-to-check-if-the-url-contains-a-given-string ) __________________________ Change link color: -------------------------- <a target="_blank" href="http://alceawisteria.byethost7.com/PHP/0demo/2023-03-25-BoxNet/rollingyourpage.html" style="color:lightgrey">rollingyourpage</a> (Source: https://www.rapidtables.com/web/html/link/html-link-color.html _________________________________ Location values: -------------------------- Let's suppose you have this url: http://localhost:4200/landing?query=1# location values, as follow: window.location.hash: "#2" window.location.host: "localhost:4200" window.location.hostname: "localhost" window.location.href: "http://localhost:4200/landing?query=1#2" window.location.origin: "http://localhost:4200" window.location.pathname: "/landing" window.location.port: "4200" window.location.protocol: "http:" (source: https://stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc ) ___________________________________ Disable links in iframe: --------------------------------- iframe { pointer-events: none; } (Source: https://stackoverflow.com/questions/69644930/can-links-inside-iframe-that-link-to-another-domain-be-ignored-disabled ) ___________________________________ Download current webpage: ----------------------------------------- <a onclick="this.href='data:text/html;charset=UTF-8,'+encodeURIComponent(document.documentElement.outerHTML)" href="#" download="page.html">Download</a> (See also: https://codepen.io/theConstructor/pen/vKNRdE ) (Source: https://stackoverflow.com/questions/26219180/download-current-html-file ) ____________________________________ Run console command via button: --------------------------------------------------- <button onclick="exec(`document.querySelector('button')`)">Test</button> <script> Function exec(code){ console.log(Function(`return (${ code })`)())} </script> (Source: https://stackoverflow.com/questions/70295800/how-to-run-a-console-lwith-a-button-in-html ) _____________________________ Resize all images to XY% ---------------------------------------- <style> img{ width: 80%; height: 80%; margin-top: .4rem; //border-radius: 50rem; } </style> ________________ Set Basis for relative links: ------------------------------------------- <base href="https://m.box.net"> (Source: https://stackoverflow.com/questions/3329499/convert-a-relative-url-to-an-absolute-url-with-simple-html-dom ) __________________ Make all #links in current dom open in new #tab --------------------- <base target="_blank"> ________________ Nocache meta tag: ---------------------------- (prevent site from being cached /caching ) <meta http-equiv="Cache-control" content="No-Cache"> https://stackoverflow.com/questions/4480304/how-to-set-http-headers-for-cache-control#4480318 _________________ Scroll < h> text (horizontally) ------------------------------ (Replace translateX with "translateY" to scroll vertically) <style>h2 {animation: example linear 5s infinite;}@keyframes example {from { transform: translateX(-40%); } to { transform: translateX(100%);}}</style> <h2>This is an announcement</h2> (source: https://stackoverflow.com/questions/75291198/animate-text-to-make-it-scroll ) ____________________ Embed code into website w.o. js or iframe: ----------------------- <object type="text/html" data="https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/index.html" style="width:100%; height:100%"></object> (Source: https://stackoverflow.com/questions/46690121/embed-html-content-from-another-http-request-without-an-iframe ) _________________________ Test RSS: ---------------- <div class="updatebox"> <script src="//rss.bloople.net/?url= https://www.youtube.com/feeds/videos.xml?channel_id=UCmIpOnd5BVx5Si2hp0WNKZw &showtitle=false&type=js"></script></div> ________________ Render base64 encoded html directly as iframe inpage: ------------------------------------------------------------------------------- <iframe src="data:text/html;base64, Base64Code " style="border:0px #ffffff none;" name="statusit" scrolling="auto" frameborder="0" marginheight="0px" marginwidth="0px" height="350px" width="500px" allowfullscreen></iframe> _________ Image as button: ------------------------- <button type="button"> <img src="https://i.ibb.co/CW5Wvry/buttonpng.png" alt="buttonpng" border="0" height=45px id="btn" /> </button> ___________ Subscribe to RSS Button --------------------------------------- &nbsp;<a target="_blank" href="https://backend.deviantart.com/rss.xml?q=gallery:aoikurayami1/"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/46/Generic_Feed-icon.svg/1920px-Generic_Feed-icon.svg.png" height="15" width="15"></a> ______________________________ Cool animated font: ------------------- <style> @import url(https://fonts.googleapis.com/css?family=Montserrat);body,html{height:100%;font-weight:800;margin:0;padding:0}body{background:#03032100;font-family:Arial}.container{display:flex;height:100%;align-items:center}svg{display:block;font:10.5em Montserrat;width:960px;height:300px;margin:0 auto}.text-copy{fill:none;stroke:white;stroke-dasharray:6% 29%;stroke-width:5px;stroke-dashoffset:0%;animation:5.5s linear infinite stroke-offset}.text-copy:first-child{stroke:#4D163D;animation-delay:-1}.text-copy:nth-child(2){stroke:#840037;animation-delay:-2s}.text-copy:nth-child(3){stroke:#BD0034;animation-delay:-3s}.text-copy:nth-child(4){stroke:#BD0034;animation-delay:-4s}.text-copy:nth-child(5){stroke:#FDB731;animation-delay:-5s}@keyframes stroke-offset{100%{stroke-dashoffset:-35%}} </style><div class="container"> <svg viewBox="0 0 1100 220"> <symbol id="s-text"> <text text-anchor="middle" x="50%" y="80%">Diarykeeper</text> </symbol><g class = "g-ants"> <use xlink:href="#s-text" class="text-copy"></use> <use xlink:href="#s-text" class="text-copy"></use> <use xlink:href="#s-text" class="text-copy"></use> <use xlink:href="#s-text" class="text-copy"></use> <use xlink:href="#s-text" class="text-copy"></use> </g></svg></div> (Source: ) _____________________________ Roll Text over site: -------------------- <marquee> Want to join this <strong>HeLLa CoOL</strong> webring??</marquee> _____________________________ Add Url post one: ------------------------- <a target="_blank" href="?https://www.url"> _____________________________ Action on mouseover (f.e. "change image) ----------------------- <a href="mailme.html" target="rainbowmain" onmouseover="image1.src='images/df17_merged_invisbg_12over.png';" onmouseout="image1.src='images/df17_merged_invisbg_12.png';"><img src="images/df17_merged_invisbg_12.png" name="image1" width="34" height="35" alt=""></a></td> (Source: view-source:https://www.jellyfishforest.com/duckyfeet/ ) _________________________ Call JS/ CSS: ------------------- <script class="u-script" type="text/javascript" src="jquery.min.js" defer="defer"></script> <link rel="stylesheet" href="/html/styles.css"> (Source: https://www.w3schools.com/html/html_css.asp ) ______________ Reload page within href: ------------------------ <a href="javascript:window.location.reload(true)">Reload</a> (Source: https://stackoverflow.com/questions/8174282/link-to-reload-current-page ) ______________________________ HTML redirect (auto) ------------------------------ <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0; url=https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/index.html"> <script type="text/javascript"> window.location.href = "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/index.html" </script> <title>Homepage</title> </head> <body> <!-- Note: don't tell people to `click` the link, just tell them that it is a link. --> If you are not redirected automatically, follow this <a href='https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/index.html'>-</a>. </body> </html> (Source: ) _________________________________ Custom font in your website: ---------------------------- (Source: https://www.fontsquirrel.com/tools/webfont-generator https://www.pagecloud.com/blog/how-to-add-custom-fonts-to-any-website) _________________________________ Bookmark link ("goto" part of page) ---------------- <a href="#z">Scripting Languages</a> … <a name="z">Scripting Languages</a> (Source: https://www.tutorialspoint.com/How-to-create-a-bookmark-link-in-HTML ) __________________ Display base64 image: ----------------------- <img src=" data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6AQMAAACyIsh+AAAABlBMVEX///8AAABVwtN+AAAACXBIWXMAAA7EAAAOxAGVKw4bAAACC0lEQVRogeWZMa6EMAxEHVFQcgSOwtHgaDkKR6CkQPh7xs4u2l9svU6KFQlPK8UajxMj8m2sinGKTPtcn1M+6JYFwF6HczymXWTRTbl5nxrfEaB6DSdmc10U74dLGDcLUzZgVMWKjXIzEp0CMh1cX/UuV0rAZa/HrK6HQnn8y4vsgPse8t3yYlvlBmDTD5/8caANW9i578IXh3yO5AACdQ1Yoh42BYA0mfelGp8EEFGzNVN9FHfTg7rbo8ZRD10AsMGWF8rIlHbm8WkSQLHvkdVdFry/h2s8af6Y9gPobWlxhu2Z3ZeWJlolEYBDC+KAfDd5hOrhefZy6wWQqOYQANP95pl2giuK22AOAEfU0asYdO7yEJ7k/Q+6AFZE5nFFfeSFByoJ4LLHK5e9PVyocZg+8iI7IAyUsrgzTq2423NtefH7wIpqfiEOOzSuLO5K04ui1geAai4PG2SHAoGz9A8bzADYzl0AvnE/2qHW2yzyog8g8gJ9mPpqu3nc6tsnEwAlDi0QQLTd2I7wC0w3gN9ZWkOiVT2MGo2aBEAMNF5oc9FsPPwM0w+werpHPwoKKF7c95cNpgAQBbYT1V3O+02Ig+u+G6AJwBfQlWGP/Z04qYDJV+yXpsfiLs9E6AWIbyhmg7inT3u05bIAEgKgyWlruz0upH0AjM7Jm/mi/HToH0z10Y7uAPg2/gCJcpY5m9E2HAAAAABJRU5ErkJggg==" alt="Red dot" /> </div> </div> (Source: https://www.base64-image.de/ ) _____________________________ Generate QR Code from URL: ------------------------------------------- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script type="text/javascript"> function generateBarCode() { var nric = $('#text').val(); var url = 'https://api.qrserver.com/v1/create-qr-code/?data=' + nric + '&amp;size=50x50'; $('#barcode').attr('src', url); } </script> </head> <body> <input id="text" type="text" value="UnderratedContent" style="Width:20%" onblur='generateBarCode();' /> <img id='barcode' src="https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/UnderratedContent.html&amp;size=100x100" alt="" title="UnderratedContent" width="50" height="50" /> </body> </html> (Source: https://stackoverflow.com/questions/30115242/generating-a-simple-qr-code-with-just-html ) https://blog.qr4.nl/Online-QR-Code-Decoder.aspx _____________________ Midway viewport (android tablet): ------------------------------ <meta id="myViewport" name="viewport" content="width = 600"> (Source: https://stackoverflow.com/questions/24523996/how-to-set-viewport-dynamically) ___________ Force Desktop page: ------------------- <head> <meta id="viewport" name="viewport" content="width=1024, height=768, initial-scale=0, minimum-scale=0.25" /> (Source: https://stackoverflow.com/questions/3588628/can-i-change-the-viewport-meta-tag-in-mobile-safari-on-the-fly) ___________________ Disable sites mobile view: ------------------------------------- Remove <meta name="viewport" content="width=device-width, initial-scale=1"> from your html file. (Source: https://stackoverflow.com/questions/46905233/how-to-disable-mobile-version-of-website _________________________________ Load link into existing iframe: ------------------------------- <div> <a href="https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Project.html" target="iframeblog">Art Gatekeeping Rant</a> <a href="https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Comments.html" target="iframeblog">+2</a> <a href="#">Link 3</a> <a href="#">Link 4</a> </div> <br> </div> </body> <br><iframe src="demo_iframe.htm" name="iframeblog" height="100%" width="100%"scrolling="no" frameborder="0" allowtransparency="true"></iframe> (Source: https://www.w3schools.com/tags/att_iframe_name.asp https://stackoverflow.com/questions/740816/open-link-in-iframe ) _______________________________________________ Mini dropdown menu (2023\12\31) ------------------------------------------------- <style>.dropdown-content{display:none;position:absolute;background-color:#f9f9f9;min-width:160px;box-shadow:0 8px 16px 0 rgba(0,0,0,.2);z-index:1}.dropbtn:hover+.dropdown-content,.dropdown-content:hover{display:block}</style> <div class="dropdown"> <button class="dropbtn">List</button> <div class="dropdown-content"> <a href="?instance=mstdn.animexx.de&userid=111676830721936824" style="color: blue;">@Alcea@Animexx</a> <a href="?instance=mstdn.animexx.de&userid=111676830721936824" style="color: blue;">url2</a> </div> </div> _______________________________________________ Compact dropdown button (with images) ------------------------------------------------------------' <style> .dropdown {position: absolute;display: inline-block;} .dropdown-content { display: none;position: absolute;background-color: #ffffff;min-width: 0px;box-shadow:5px 5px 0px 0px rgba(0,0,0,0.2);z-index: 1;} .dropdown-content a { color: black;padding: 2px 2px;text-decoration: none;display: block;} .dropdown-content a:hover {background-color: #fff;} .dropdown:hover .dropdown-content {display: block;} .dropdown:hover .dropbtn {background-color: transparent;} </style> <div class="dropdown" hidden>  <button class="dropbtn"><img src="https://cdn-icons-png.flaticon.com/512/2327/2327670.png" height="45" width="45"></button> <div class="dropdown-content"> <a target="_blank" href="https://pb.todon.de/@alcea.rss"><img src="https://upload.wikimedia.org/wikipedia/commons/4/48/Mastodon_Logotype_%28Simple%29.svg" height="45" width="45"></a> <a target="_blank" href="https://nitter.absturztau.be/ryedai1/rss"><img src="https://upload.wikimedia.org/wikipedia/commons/4/4f/Twitter-logo.svg" height="45" width="45"></a> <a target="_blank" href="mailto:hax0rxy@googlemail.com"><img src="https://upload.wikimedia.org/wikipedia/commons/4/4e/Mail_%28iOS%29.svg" height="45" width="45"></a> </div> </div> __________________________ Hoverable Dropbdown menu: -------------------------- <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .dropbtn { background-color: #04AA6D;color: white;padding: 16px;font-size: 16px;border: none; } .dropdown { position: relative;display: inline-block; } .dropdown-content { display: none;position: absolute;background-color: #f1f1f1;min-width: 160px;box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);z-index: 1; } .dropdown-content a { color: black;padding: 12px 16px;text-decoration: none;display: block; } .dropdown-content a:hover {background-color: #ddd;} .dropdown:hover .dropdown-content {display: block;} .dropdown:hover .dropbtn {background-color: #3e8e41;} </style> </head> <body> <div class="dropdown"> <button class="dropbtn">Dropdown</button> <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> <a href="#">Link 4</a> </div> </div> </body> (Source: https://www.w3schools.com/howto/howto_css_dropdown.asp) _______________________ Twitter Box: ----------------- https://www.codingnepalweb.com/tweet-box-character-limit-highlighting-javascript/ _______________________________ Embed img from url: ------------------------------ <img src="/wp-content/uploads/flamingo.jpg"> (Source: https://html.com/attributes/img-src/ ) ______________________________ Remove frame border: ----------------------------- ...src="https://www.site.com" frameBorder="0"> (Source: stackoverflow.com/questions/65034/remove-border-from-iframe) __________________________________ Display txt content in iframe: ------------------------------------------ <iframe src="yourtext.txt"></iframe> (Source: https://www.generacodice.com/en/articolo/789689/Is+there+any+way+similar+to+%26lt%3Bimg%26gt%3B+to+display+contents+of+a+.txt+file ) _________________________________ Render html from text file ---------------------------- <embed src = "file.txt"> (Source: https://www.codegrepper.com/code-examples/html/how+to+render+html+from+text+file) ______________________________ Zoom iframe content: --------------------- <style type="text/css"> #iframe { zoom: 0.15; -moz-transform:scale(0.75); -moz-transform-origin: 0 0; -o-transform: scale(0.75); -o-transform-origin: 0 0; -webkit-transform: scale(0.75); -webkit-transform-origin: 0 0; } </style> (Source: https://stackoverflow.com/questions/7203064/how-to-zoom-iframe-content-only-without-using-a-frame-set) _____________________ Scroll iframe to specific positions: ----------------------------------- <style> #mydiv { width : 100%; height : 100%; overflow : hidden; position : relative; } #myframe { position : absolute; top : -500px; left : 0px; width : 1280px; height : 1200px; } </style> <body style="margin: 0 auto;"> <div id="mydiv"> <div id="myframe"> <iframe src="http://www.example.com" id="myframe" scrolling="no"></iframe> </div> For XFrame Bypass: ------------------ <body style="margin: 0 auto;"> <div id="mydiv"> <div id="myframe"> <script type="module" src="https://unpkg.com/x-frame-bypass"></script> <iframe is="x-frame-bypass" src="https://github.com/Ry3yr/OSTR/tree/main/Diarykeepers_Homepage" height="100%" width="100%"scrolling="no" frameborder="0" allowtransparency="true"></iframe> <p style=""> </p> (Source: https://stackoverflow.com/questions/14117763/how-do-you-put-only-a-certain-section-of-a-website-into-an-iframe/14117980) ____________________ Scale iframe content: --------------------- <style> #wrap { width: 600px; height: 390px; padding: 0; overflow: hidden; } #frame { width: 800px; height: 520px; border: 1px solid black; } #frame { zoom: 0.75; -moz-transform: scale(0.75); -moz-transform-origin: 0 0; } </style> <div id="wrap"> <iframe id="frame" src="test2.html"></iframe> </div> (Source: https://stackoverflow.com/questions/166160/how-can-i-scale-the-content-of-an-iframe) ____________________ HTML reload page: -------------------------- Reload once upon open: window.onload = function() { if(!window.location.hash) { window.location = window.location + '#loaded'; window.location.reload(); } } (Source: https://stackoverflow.com/questions/6985507/one-time-page-refresh-after-first-page-load) Keep refreshing every 'x' <meta http-equiv="refresh" content="1"> ( Source: https://stackoverflow.com/questions/5294842/refresh-a-page-using-javascript-or-html ) ____________________ Uhrzeit & Kalender --------------------------- https://www.schulferien.org/Uhrzeit/ __________________________ Transparent text: ------------------------- Transparent color code: When you have a 6 digit color code e.g. #ffffff, replace it with #ffffff00. Just add 2 zeros at the end to make the color transparent. (Source: https://stackoverflow.com/questions/18189201/is-there-a-color-code-for-transparent-in-html/18189313 ) Option b) color:rgba(255,0,0,0.0); (Source: https://stackoverflow.com/questions/20048225/invisible-transparent-font-color-with-css-on-all-major-browsers ) _________________________ HTML Comment: ------------------- <!-- and the comment closes with --> https://blog.christosoft.de/2015/04/html5-bogus-comment/ _________________________________ Copy current URL to clipboard: ----------------------------- <button onclick="myFunction()">CopyURL</button> <script> function myFunction() { var copyText = navigator.clipboard.writeText(window.location.href); } </script> (Source: https://stackoverflow.com/questions/49618618/copy-current-url-to-clipboard ) ________________________ Copy text to clipboard: ------------------------------- <input type="text" value="text" id="myInput"> <button onclick="myFunction()">Copy text</button> <script> function myFunction() { var copyText = document.getElementById("myInput"); copyText.select(); copyText.setSelectionRange(0, 99999); navigator.clipboard.writeText(copyText.value); } </script> (Source: https://www.w3schools.com/howto/howto_js_copy_clipboard.asp ) _______________________ Display current url: --------------------------- <script> function getURL() { alert("The URL of this page is: " + window.location.href); } </script> <button type="button" onclick="getURL();">ClickMe</button> (Source: https://www.tutorialrepublic.com/faq/how-to-get-the-current-url-with-javascript.php) ____________________________ Encode Mail to Anti Spam: ------------------ https://www.viathinksoft.de/tools/antispam/index.php ________________________ Visitor Counter: ------------------- <a href="https://www.daniel-marschall.de/counter/"><img src="https://www.daniel-marschall.de/counter/counter.php?id=1347&amp;format=graphic&amp;theme=digital" alt="Visitors" title="Visitors"></a> Premade: smallseotools.com/de/visitor-hit-counter https://github.com/brentvollebregt/hit-counter https://www.powr.io/plugins/hit-counter/standalone https://www.daniel-marschall.de/counter/ Make your own: https://www.ionos.de/digitalguide/websites/webseiten-erstellen/besucherzaehler-selbst-erstellen-so-funktionierts/ _____________________ Make part scrollable: ------------------- <head> <style> h1 { color:Green; } div.scroll { margin:4px, 4px; padding:4px; background-color: white; width: 500px; height: 110px; overflow-x: hidden; overflow-y: auto; text-align:justify; } </style> </head> <body> <div class="scroll"> </div> </center> </body> </html> (Source: https://www.geeksforgeeks.org/making-a-div-vertically-scrollable-using-css/ ) _____________ Add tab-icon to weppage (favicon): ------------------- <link rel="icon" type="image/png" href="favicon.png"><!-- Major Browsers --> <!--[if IE]><link rel="SHORTCUT ICON" href="favicon.ico"/><![endif]--><!-- Internet Explorer--> Add 32x32 favicon.png to websites main dir https://www.hostinger.com/tutorials/how-to-add-favicon-to-website https://realfavicongenerator.net/ OR Add to html directly via base64 Encoded Image directly inside the tag like this: <link href="data:image/x-icon;base64,IMAGE-BASE64" rel="icon" type="image/x-icon" /> https://stackoverflow.com/questions/16375592/favicon-not-showing-up-in-google-chrome/16375622#16375622 ___________________________ Tile image over background: -------------------------- <style> body { background-image: url("/examples/images/tile.png"); } </style> (Source: https://www.tutorialrepublic.com/css-tutorial/css-background.php) ============ One line version ============= <body background="http://www.geocities.ws/jaup/bgrnd40.gif"> ________________________ Html Audioplayer ---------------- https://github.com/NelsWebDev/BetterAudioPlaylist (Source: https://m.youtube.com/watch?v=PZuvCpx5lKY) (Q: https://stackoverflow.com/questions/69810359/interface-with-audioplayer-within-spoiler-tag) ___________________ Keep Element on bottom-right page corner: ----------------- <html> <head> <meta charset=utf-8 /> <title>Test</title> <style> #foo { position: fixed; bottom: 0; right: 0; } </style> </head> <body> <div id="foo">Hello World</div> </body> </html> (Source: https://stackoverflow.com/questions/3616572/how-to-position-a-div-in-bottom-right-corner-of-a-browser) (Bottom right audioplayer: stackoverflow.com/questions/38156970/how-do-i-make-a-simple-audio-element-stay-at-the-bottom-of-the-browser-window) ____________________________________________________ Open link in program + fallback ------------------------------- <html> <script> function openApp () { var start, end, elapsed; var params = window.location.href.split("lp=")[1]; var url = params.split("&customURI=")[0]; var customURI = params.split("&customURI=")[1]; var time = (new Date()).getTime(); document.location = customURI+url; setTimeout(function(){ var now = (new Date()).getTime(); if((now - time)<2550) { javascript: console.log(new Date().getTime()); document.location = url; } else{ window.open('', '_self', ''); window.close(); } }, 2000); } </script> <body onload="openApp()"> <a onclick="openApp()" id="newButton">Click Here to open the App</a> </body> (Source: https://stackoverflow.com/questions/11710902/can-i-make-a-link-that-will-open-in-my-app-if-its-installed-and-fall-back-to-a) ____________________ Comment / Guestbook script: ---------------------------- https://www.htmlcommentbox.com/ https://www.123guestbook.com/ )Alts https://www.quackit.com/html/codes/add_comments_to_website.cfm •You can find more solutions by searching for 'comments' at https://www.thenewdynamic.org. https://stackoverflow.com/questions/59096243/adding-comments-in-blog-posts-on-github-pages ) https://www.freecodecamp.org/news/how-you-can-build-your-own-free-serverless-comment-box-dc9d4f366d12/ ___________________ Add Disquis comment section to your page: ------------------------ https://www.create.net/support/how-to-add-a-disqus-comment-section-to-your-website (must add own domain to https://diarykeeper.disqus.com/admin/settings/advanced/ !!!) [ Enable Guestpost: https://help.disqus.com/en/articles/1717211-guest-commenting https://i.ibb.co/xs9kMNs/Screenshot-20211108-131308.jpg ] __________________________ Resizeable Button: ------------------ <a href="http://bitdegree.org" target="_blank"> <button class="button">Submit</button> <style> .button {height: 50px; width: 100px;}</style> (Source: https://www.quora.com/How-do-you-edit-a-button-size-in-HTML) ____________________________ Button: ------- <a href="http://bitdegree.org" target="_blank"> <button>Click me!</button> (Source: https://www.bitdegree.org/learn/html-button) ___________ Own Forum: --------------- https://www.forumotion.com/ https://www.makeuseof.com/tag/5-great-sites-create-forum/ ________ Link to Whatsapp / WA via browser ------------------------------------------- https://api.whatsapp.com/send/?phone=%2B491625385381&text&app_absent=0 https://wa.me/+491625385381 ____________________________ Change font color: ------------------- <span style="color: rgb(51, 51, 255);">me</style> __________________________ Change font size: ------------------ <font size="-1">text</font> _________________________________ Change img size via html: ------------------------- <img src='image.jpg' alt="Image" height="100" width="100"> https://www.codegrepper.com/code-examples/html/resize+image+in+html _________________________________ Link to website-image on another page: --------------------------------- <p> <a href="https://www.computerhope.com/"> <img src="https://www.computerhope.com/cdn/media/logo-200-gray.png"> </a> </p> https://www.computerhope.com/issues/ch000059.htm _______________________________________________________________ Use Github Pages to host website: --------------------------------- http://docsbeta.pinegrow.com/host-html-website-github-pages-free/ (Result: => https://ry3yr.github.io/OSTR/All_Project_(spoiler_button).html) (Push git change via windows: https://gitforwindows.org/) _______________________________________________________________ Bypass iFrame Limitation: -------------------------------------- <script type="module" src="https://unpkg.com/x-frame-bypass"></script> <iframe is="x-frame-bypass" src="https://vgmdb.net"></iframe> https://github.com/niutech/x-frame-bypass _______________________________________________________________ Fullscreen iframe: ------------------ <body style="margin: 0 auto;"> <iframe src="https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Startseite.html" frameborder="0" style="overflow:hidden; display:block; position: absolute; height: 100%; width: 100%"> <p style=""> Your browser does not support iframes. </p> </body> ______________________ Render webpage into frame: -------------------------- <iframe src="https://www.abcsubmit.com/view/id_1f8339emu_jn1?utm=abcsubmit" width="400" height="400"></iframe> _______________________________________________________________ RSS Feed Widget --------------- <div id="widgetmain" style="text-align:left;overflow-y:auto;overflow-x:hidden;width:600px;background-color:#transparent; border:1px solid #333333;"><div id="rsswidget" style="height:500px;"><iframe src="http://us1.rssfeedwidget.com/getrss.php?time=1626283386459&amp;x=http%3A%2F%2Ffeeds.feedburner.com%2Fvgmdb_album_new%3Fformat%3Dxml&amp;w=600&amp;h=500&amp;bc=333333&amp;bw=1&amp;bgc=transparent&amp;m=20&amp;it=true&amp;t=vgmdb&amp;tc=333333&amp;ts=15&amp;tb=transparent&amp;il=true&amp;lc=0000FF&amp;ls=14&amp;lb=false&amp;id=true&amp;dc=333333&amp;ds=14&amp;idt=true&amp;dtc=284F2D&amp;dts=12" border="0" hspace="0" vspace="0" marginwidth="0" marginheight="0" style="border:0; padding:0; margin:0; width:600px; height:500px;" id="rssOutput" frameborder="no">Reading RSS Feed ...</iframe></div><div style="text-align:right;margin-bottom:0;border-top:1px solid #333333;" id="widgetbottom"><span style="font-size:70%"></span><br></div></div> www.rssfeedwidget.com (Source: https://stackoverflow.com/questions/15821278/how-to-make-a-html-page-to-show-content-from-another-url) # You have to check for HTTP response header X-Frame-Option of those sites. if its value is "DENY or SAMEORIGIN", then you can not load those website in the iframes. DENY = No one can load the website in iframe. Even the same domain page wont be able to load. SAMEORIGIN = only a page which is in same domain can load this website in iframe. https://stackoverflow.com/questions/6663244/cant-show-some-websites-in-iframe-tag Alt RSS Widget: <script src="https://apps.elfsight.com/p/platform.js" defer></script> <div class="elfsight-app-8283fde1-03d2-4c5e-a789-3e2e667372e4"></div> ____________________________________________ Embed Gdrive folder via iframe: -------------------------------- <iframe src=" https://drive.google.com/embeddedfolderview?id=1QbDDSVbCEZOXjJKICwuJNEHFKWwl_AvX#list" style="width:100%; height:600px; border:0;"></iframe> (Source: https://stackoverflow.com/questions/20681974/how-to-embed-a-google-drive-folder-in-a-website) ____________________________________________ Embed Gdrive file via iframe ------------------------- <iframe src=" https://drive.google.com/file/d/1z0_ygovRUlwMRjc-UQVO8HbwW57Qs_On/preview" width="640" height="480"></iframe> (Source:https://stackoverflow.com/questions/44164367/how-to-embed-google-drive-document-pdf-in-blogger-post) ____________________________________________ Contact form (mail): -------------------------- GDRIVE: you can still view or host HTML files that are in public folders as follows: Replace https://drive.google.com/?authuser=0#folders/ with "googledrive.com/host/" Your new URL will look something like this: http://www.googledrive.com/host/0B81vQexWOx6hRDVMQWZTekx4Umc https://superuser.com/questions/813701/view-rendered-html-of-html-document-in-new-google-drive https://www.freecontactform.com/form-guides/html-email-form#htmlform https://hwpi.harvard.edu/assetslibrary/host-css-or-js-file-google-drive https://discuss.codecademy.com/t/linking-css-to-html-via-google-drive/64725/4 [Service] https://www.abcsubmit.com ____________________________________________ GoogleDrive embed: (dot menu -> Embed item... -> copy code) ---------------------------- <iframe src="https://drive.google.com/file/d/-url-identifier-gdrive/preview" width="640" height="480"></iframe> url-identifier-gdrive: f.e.: (between "/d/" and "/view") https://drive.google.com/file/d/1pOZxwsDoRQ3V3ubonniGEbpSo6BXjQnr/view --hotlink--file: (https://stackoverflow.com/questions/10311092/displaying-files-e-g-images-stored-in-google-drive-on-a-website) https://docs.google.com/uc?id=FILE-ID ___________________________________________ Obfuscate html --------------------------- https://www.wmtips.com/tools/html-obfuscator/ (Source: https://community.spiceworks.com/topic/790618-hiding-view-source-on-websites) ____________________________________________ HTML Password encrypt (via pagecrypt) ------------------------------------------------------- https://www.maxlaumeister.com/pagecrypt/ E:\Dropbox\Public\00_Powershell\[Context_menu_handler_sendto]\encrypt_html.bat ____________________________________________ HTML Password protect (via htaccess): ------------------------------------------------------ https://www.lifewire.com/password-protect-single-file-with-htaccess-3467922 ____________________________________________ Append to Form input (query) via onsubmit: ------------------------------------------- (Source: https://stackoverflow.com/questions/34128361/appending-form-input-value-to-action-url-as-path) ____________________________________________ Searchbox (w.o. q=?, only "/"): --------------------------------------- <div id="tfheader"> <form id="tfnewsearch" method="get" action="http://de.wiktionary.org/wiki/"> <input type="text" class="tftextinput" id="tftextinput" name="q" size="21" maxlength="120"><input type="submit" value="search" class="tfbutton"> </form> <div class="tfclear"></div> </div> <script> var a = document.getElementById('tfnewsearch'); a.addEventListener('submit',function(e) { e.preventDefault(); var b = document.getElementById('tftextinput').value; window.location.href = 'http://de.wiktionary.org/wiki/'+b; }); </script> https://stackoverflow.com/questions/27580420/html-how-to-create-search-bar ________________________________________________________________________________________________________ Search bar (works on: PC, iPad, Android, 3DS, WiiU) ------------------------------------------------------------ <!DOCTYPE html> <html> <head> <title>Search Box Example 1</title> <meta name="ROBOTS" content="NOINDEX, NOFOLLOW" /> <!-- CSS styles for standard search box --> <style type="text/css"> #tfheader{ background-color:#c3dfef; } #tfnewsearch{ float:right; padding:20px; } .tftextinput{ margin: 0; padding: 5px 15px; font-family: Arial, Helvetica, sans-serif; font-size:14px; border:1px solid #0076a3; border-right:0px; border-top-left-radius: 5px 5px; border-bottom-left-radius: 5px 5px; } .tfbutton { margin: 0; padding: 5px 15px; font-family: Arial, Helvetica, sans-serif; font-size:14px; outline: none; cursor: pointer; text-align: center; text-decoration: none; color: #ffffff; border: solid 1px #0076a3; border-right:0px; background: #0095cd; background: -webkit-gradient(linear, left top, left bottom, from(#00adee), to(#0078a5)); background: -moz-linear-gradient(top, #00adee, #0078a5); border-top-right-radius: 5px 5px; border-bottom-right-radius: 5px 5px; } .tfbutton:hover { text-decoration: none; background: #007ead; background: -webkit-gradient(linear, left top, left bottom, from(#0095cc), to(#00678e)); background: -moz-linear-gradient(top, #0095cc, #00678e); } /* Fixes submit button height problem in Firefox */ .tfbutton::-moz-focus-inner { border: 0; } .tfclear{ clear:both; } </style> </head> <body> <!-- HTML for SEARCH BAR --> <div id="tfheader"> <form id="tfnewsearch" method="get" action="http://www.google.com"> <input type="text" class="tftextinput" name="q" size="21" maxlength="120"><input type="submit" value="search" class="tfbutton"> </form> <div class="tfclear"></div> </div> </body> </html> (Source: https://www.textfixer.com/tutorials/html-search-box.php) https://pastebin.com/MzWCYjeD ________________________________________________________________________________________________ Search Bar Example (with set off text) ------------------------------------------------- <!DOCTYPE HTML> <html lang="de"> <head> <style> body{ padding:20px; } *{ margin: 0; padding:0px; } .tftextinput{ font-family: Arial, Helvetica, sans-serif; font-size:14px; border:1px solid #0076a3; border-bottom-left-radius:5px; border-bottom-right-radius:5px; } </style> <title>savepage</title> </head> <body> <div id="tfheader"> <form id="tfnewsearch" method="GET" action="https://api.github.com/users/xxx/events/public"> <input class="tftextinput" id="text" size="21" maxlength="120" type="text"><br> <input value="GitHubUser" class="tfbutton" type="submit"></form> </div> <script> var ele=document.getElementById('tfnewsearch'); ele.addEventListener("submit",function(evt){ let alt=ele.getAttribute('action'); let such_link=document.getElementById('text').value; let neuer_link=alt.replace('xxx',`${such_link}`) neu=ele.setAttribute('action',neuer_link); //ele.submit(); // evt.preventDefault(); console.log(ele.getAttribute('action')) }); </script> </body> </html> (Source: https://www.html-seminar.de/forum/thread/8884-html-submit-form-searchbox-ver%C3%A4nderte-position-suchparameter/#post60465) ________________________________________________________________________________________________________ Hide texrt data: -------------------- .hidden { background: #000; font-color: #000; transition: background 0.5s ease; } .hidden:hover { background: none; } Here is a large block of text with a hidden <span class="hidden">password</span> that is only revealed on hover. (Source:https://discourse.joplinapp.org/t/hiding-passwords-with-markdown/1588/2 ) ________________________________________________________________________________________________________ CSS Data uri: --------------------- https://css-tricks.com/data-uris/ ________________________________________________________________________________________________________ Create colored button: ---------------------- <button style="background-color: white; border-color:white; color: white" > https://www.wikihow.com/Change-the-Button-Color-in-HTML ______________________________________________________ Borderless (Spoiler) Button: ----------------------------- Add: "padding: 0; border: none;" to remove border <div class="pre-spoiler"> <input style="color: rgb(255, 255, 255);padding: 0; border: none;" name=" " onclick="if (this.parentNode.getElementsByTagName('div')[0].style.display != 'none') { this.parentNode.getElementsByTagName('div')[0].style.display = 'none'; this.value = ' '; } else { this.parentNode.getElementsByTagName('div')[0].style.display = 'block'; this.value = '-';}" value=" " background-color="" border-color:white="" color="" white="" type=" style="> <div class="spoiler" style="display: none;"> --- </div> (Source: https://stackoverflow.com/questions/11497094/remove-border-from-buttons ) ___________________________ CSS-Spoiler_Button ------------------ <style> body{padding-left:150px}p{font-size:16px;color:#2f4f4f}button:focus{outline:0}img{margin:10px}#spoiler_button{font-size:20px;font-weight:700;width:175px;height:55px;margin:0 10px;color:#fff;border-radius:5px;border:none}#spoiler_button:hover{font-weight:700;color:#fff;box-shadow:5px 5px 5px #000}#spoiler_button:active{font-weight:700;box-shadow:none}.fadein,.fadeout{height:0;-moz-transition:opacity 1s ease-in-out;-o-transition:opacity 1s ease-in-out;-webkit-transition:opacity 1s ease-in-out;opacity:0}.fadein{height:100%;opacity:1} </style> <button name="spoiler_button" id="spoiler_button" type="button">Show Spoilers</button> <div id="spoiler_text" class="fadeout" > <br>Text </div> <script> var divToggleVis=document.getElementById("spoiler_text"),button=document.getElementById("spoiler_button");button.onclick=function(){"fadeout"===divToggleVis.className?divToggleVis.className="fadein":divToggleVis.className="fadeout","Show Spoilers"===button.innerHTML?button.innerHTML="Hide Spoilers":button.innerHTML="Show Spoilers"}; </script> (Source: https://trujared.medium.com/how-to-easily-add-a-spoiler-button-to-your-webpage-dec050c4867f ) ________________________ HTML Spoiler Tag code / Spoiler button ------------------------------------- <div class="pre-spoiler"> <input name="Deutsch" type="button" onClick="if (this.parentNode.getElementsByTagName('div')[0].style.display != 'none') { this.parentNode.getElementsByTagName('div')[0].style.display = 'none'; this.value = 'ButtontextSpoiler'; } else { this.parentNode.getElementsByTagName('div')[0].style.display = 'block'; this.value = 'ButtontextSpoiler';}" value="ButtontextSpoiler"> <div class="spoiler" style="display: none;"> <br>Text </div> #Make button white, via "KompoZer's "split-view" -> edit button" <input name="Buttonz" onclick="if (this.parentNode.getElementsByTagName('div')[0].style.display != 'none') { this.parentNode.getElementsByTagName('div')[0].style.display = 'none'; this.value = 'Buttonz'; } else { this.parentNode.getElementsByTagName('div')[0].style.display = 'block'; this.value = 'Buttonz';}" value="Buttonz" background-color:="" white;="" border-color:white;="" color:="" white="" type=" style="> (SOURCE: https://forum.chip.de/discussion/1381745/spoiler-in-html) ________________________________________________________________________________________________________ HTML Spoiler Tag code / Spoiler button (invisible) ------------------------------------- <div class="pre-spoiler"><input name="Deutsch" type="button" onClick="if (this.parentNode.getElementsByTagName('div')[0].style.display != 'none') { this.parentNode.getElementsByTagName('div')[0].style.display = 'none'; this.value = 'ButtontextSpoiler'; } else { this.parentNode.getElementsByTagName('div')[0].style.display = 'block'; this.value = 'ButtontextSpoiler';}" value="ButtontextSpoiler" style="background:transparent; border:none; color:transparent;"><div class="spoiler" style="display: none;" > text </div> (Source: ) ________________________________________________________ HTML "Mouseover" spoiler button: <div class="pre-spoiler"> <input name="Deutsch" type="button" onmouseover="if (this.parentNode.getElementsByTagName('div')[0].style.display != 'none') { this.parentNode.getElementsByTagName('div')[0].style.display = 'none'; this.value = 'ButtontextSpoiler'; } else { this.parentNode.getElementsByTagName('div')[0].style.display = 'block'; this.value = 'ButtontextSpoiler';}" value="ButtontextSpoiler"> <div class="spoiler" style="display: none;"> <br>Text </div> __________________________________________________________________________________________________________ Alt Spoiler Button: ------------------- <div id="spoiler" style="display:none"> <iframe src="https://alceawisteria.codeberg.page/Diarykeepers_Homepage/stash/webamp.html" frameBorder="no" width=500px height=250></iframe> </div> <button title="Click to show/hide content" type="button" onclick="if(document.getElementById('spoiler') .style.display=='none') {document.getElementById('spoiler') .style.display=''}else{document.getElementById('spoiler') .style.display='none'}">Winamp</button> (Source: ) _________________________ ================= ===htmlunicodecharas== (enter on "Source page" in NVU-HTML_Editor "f.e."&#9742 => ☎) &#9986 -> ✂ https://www.w3schools.com/charsets/ref_utf_symbols.asp xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==========xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx===brknz===xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ________ Search Bar Example: (broken in 3DS/iPad) ---------------------------- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <style type="text/css"> #tfheader{ } #tfnewsearch{ float:left; padding:0px; } .tftextinput{ margin: 0; padding: 0px 0px; font-family: Arial, Helvetica, sans-serif; font-size:14px; border:1px solid #0076a3; border-left:0px; border-top-left-radius: 0px 0px; border-bottom-left-radius: 5px 5px; } </style> <title>savepage</title> </head> <body> <!-- HTML for SEARCH BAR --> <div id="tfheader"> <form id="tfnewsearch" method="get" action="http://www.google.com"> <input class="tftextinput" name="q" size="21" maxlength="120" type="text"><input value="search" class="tfbutton" type="submit"></form> </div> </body> </html> (Source: https://www.textfixer.com/tutorials/html-search-box.php) https://www.informatikzentrale.de/formulare-get-post-auswerten.html https://shipow.github.io/searchbox/ ==================== ==htmlknowledge====== Percent-encoding, also known as URL encoding, is a mechanism for encoding information in a Uniform Resource Identifier (URI) under certain circumstances. Although it is known as URL encoding, it is, in fact, used more generally within the main Uniform Resource Identifier (URI) set, which includes both Uniform Resource Locator (URL) and Uniform Resource Name (URN). As such, it is also used in the preparation of data of the application/x-www-form-urlencoded media type, as is often used in the submission of HTML form data in HTTP requests. https://en.wikipedia.org/wiki/Percent-encoding https://stackoverflow.com/questions/2949173/how-can-i-stop-the-browser-from-url-encoding-form-values-on-get https://help.surveygizmo.com/help/url-variables _______________________________________________ _______________________________________________ Host (direct link files) via GDrive: ------------------------------------ (download gdrive file via "browser's download function" => extract url via download manager: https://doc-08-28-docs.googleusercontent.com/docs/securesc/3pli3vb6c3fjid7vrr3dsc370lictgus/s0gn0auvde7qio9pka1m5fu34rjh8eec/1626641550000/12239065730730513726/06275268013771742302Z/1n2SyolVouApQftVAEWXqOKJ_F4bN2W4H?e=download&nonce=r0nhojk7dh1uu&user=06275268013771742302Z&hash=rbp7if89k7n8l4bgu8kpineqce7mj3f5 => remove "e=download&" https://doc-08-28-docs.googleusercontent.com/docs/securesc/3pli3vb6c3fjid7vrr3dsc370lictgus/s0gn0auvde7qio9pka1m5fu34rjh8eec/1626641550000/12239065730730513726/06275268013771742302Z/1n2SyolVouApQftVAEWXqOKJ_F4bN2W4H?nonce=r0nhojk7dh1uu&user=06275268013771742302Z&hash=rbp7if89k7n8l4bgu8kpineqce7mj3f5 _______________________________________________ ================== == hostwebsite === Use Github Pages to host website: --------------------------------- http://docsbeta.pinegrow.com/host-html-website-github-pages-free/ (Result:) => https://ry3yr.github.io/OSTR/Diarykeepers_Homepage =================================================== =================================================== =================================================== =================================================== =============== javascriptz ======================= ** javascript test site: jsfiddle** In HTML, JavaScript code is inserted between <script> and </script> tags - w3schools.com/js/js_whereto.asp https://cdnjs.com/libraries (prehosted JS script links) JSONEScape tool https://www.freeformatter.com/json-escape.html#ad-output Check Javascript errors: https://www.shellcheck.net/ •MinifyJS: https://www.toptal.com/developers/javascript-minifier/ •CompressJS: https://jscompress.com/ ----------------------------------------- Autoadvance video playlist player ------------------------------------------ https://codepen.io/ryedai1/pen/mdKGVOz https://cdpn.io/ryedai1/fullpage/mdKGVOz?nocache=true ________________________ Yesterdays happenings ----------------------------------- <li><a id="link" href="#">Yesterdays Happenings</a></li> <script> Date.prototype.toShortFormat = function() { const monthNames = ["January", "February", "March", "April", "May", "Juni", "July", "August", "September", "October", "November", "December"]; const day = this.getDate()-1; const monthIndex = this.getMonth(); const monthName = monthNames[monthIndex]; const year = this.getFullYear(); return `${year}_${monthName}_${day}`; } let anyDate = new Date(1528578000000); console.log(anyDate.toShortFormat()); let today = new Date(); console.log(today.toShortFormat()); var link = document.getElementById("link"); link.setAttribute("href","https://en.m.wikipedia.org/w/index.php?title=Portal:Current_events/" + today.toShortFormat()); </script> <!--https://stackoverflow.com/questions/4822852/how-to-get-the-day-of-week-and-the-month-of-the-year--> <!-- partial --> ________________________ Click text in page: ------------ if (document.all !== undefined) { var items = document.all; } else { var items = document.getElementsByTagName("*"); }; for (var i = 0; i < items.length; ++i) { if (items[i].textContent.includes("Your Text Here")) { console.log("success"); items[i].click(); } } (Source: https://stackoverflow.com/questions/62722876/how-to-click-a-specific-text-in-the-page-javascript) _________________ Javascript Weather (snow): https://www.cssscript.com/minimalist-falling-snow-effect-with-pure-javascript-snow-js/ ______________________________ Quote of the day button w linksupport ----------------------------------- <head><meta charset="UTF-8"><style> div {text-align: left;} h1 {font-size: 11px;font-family: Arial;} button {width: 128px;height: 28px;background-color: white;color: black;} {font-size: 11px;} button:hover{background-color: white;} </style></head><body> <div><button onclick="generateQuote();">QuoteOfTheDay</button><p id="quoteOutput"></div> <script>const arrayOfQuotes = [ {'quote': 'Startdust Road - YGO Vrains OST 2 -Shinkichi Mitsumune'}, {'quote': '<a target="_blank" href="https://m.youtube.com/watch?v=TU_bS6ttM4Q">Can\'t stay mad at you - Haven Danger</a>'}, {'quote': '<a target="_blank" href="https://m.youtube.com/watch?v=cqAawjQyieg">Kellys Lullaby - Another Code R - Satoshi Okubo</a>'}, {'quote': 'Abandon Me - Chicory OST - Lena Raine'}, {'quote': '<a target="_blank" href="https://youtube.com/watch?v=jCYB1BeDv1w">A Fathers Letter - MftO. Vol I - Stephen Barton</a>'}, ];function generateQuote(){const random = Number.parseInt(Math.random()*arrayOfQuotes.length + 1); document.querySelector('#quoteOutput').innerHTML = `\"${arrayOfQuotes[random].quote}\"`;} </script> </body> (Source: ) DayQuotes random line + Linksupport + external files + search --------------------------------------------------------------------------- <!DOCTYPE html> <!--https://run.plnkr.co/plunks/6wCVvXqoIGl6hN6Q--> <style> div {text-align: left;} h1 {font-size: 11px;font-family: Arial;} button {width: 128px;height: 28px;background-color: white;color: black;} {font-size: 11px;} button:hover{background-color: white;} </style> <html> <head> <meta charset="utf-8" /> <!--<link rel="stylesheet" href="style.css" />--> <script src="https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/jquery.min.js"></script> <script> var lines; var randomNumber; var lastRandomNumber; $(document.body).ready(function () { // load the trivia from the server $.ajax({ url: 'https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Daymusic_array.js' }).done(function(content) { lines = content.replace(/\r\n|\r/g, '\n').trim().split('\n'); if (lines && lines.length) { $('#searchInput').on('keyup', function () { searchLines($(this).val()); }); $('#showLine').on('click', function () { while (randomNumber === lastRandomNumber) { randomNumber = parseInt(Math.random() * lines.length); if (lines.length === 1) { break; } } lastRandomNumber = randomNumber; var line = lines[randomNumber].replace("{'quote': '", "").replace("'},", ""); $('#trivia').html(line); $('#searchResults').empty(); }); } }); }); function searchLines(query) { // filter the list of lines based on the search query var filteredLines = lines.filter(function(line) { return line.toLowerCase().includes(query.toLowerCase()); }); // display the filtered results var resultsHtml = ''; filteredLines.forEach(function(line) { resultsHtml += '<div>' + line + '</div>'; }); $('#searchResults').html(resultsHtml); } </script> </head> <body> <input type="text" id="searchInput" placeholder="Search..."> <div id="searchResults"></div> <button id="showLine">CurrListening</button> <p id="trivia"></p> </body> • <a target="_blank" href="https://-db/ratings.php?do=view&userid=24381">vgmdb ratings</a> • <a target="_blank" href="">LastFM </a> <!----------------viewsource---> • <a target="_blank" href="Daymusic_array.js">List</a> <!--<a id="myLink" title="Click to do something" href="#" onclick="viewSource();return false;">List</a> <script> function viewSource(){; var source = "<html>"; source += document.getElementsByTagName('html')[0].innerHTML; source += "</html>"; source = source.replace(/</g, "&lt;").replace(/>/g, "&gt;"); source = "<pre>"+source+"</pre>"; sourceWindow = window.open('','Source of page','height=800,width=800,scrollbars=1,resizable=1'); sourceWindow.document.write(source); sourceWindow.document.close(); if(window.focus) sourceWindow.focus(); } </script>--> </html> ______________ Quote of the Day (button, no nr) ---------------- <head> <meta charset="UTF-8"> <style> div {text-align: center;} h1 { font-size: 24px;font-family: Arial; } button { width: 100px;height: 40px;background-color: white;color: black; } p{ font-size: 24px; } button:hover{ background-color: white; } </style> </head> <body> <div> <button onclick="generateQuote();">QuoteOfTheDay</button> <p id="quoteOutput"><p id="authorOutput"> </div> <script> const arrayOfQuotes = [ {'author': 'Jim Rohn','quote': 'Beware of what you become in pursuit of what you want.'}, {'author': 'Epictetus','quote': 'It\'s not what happens to you, but how you react to it that matters.'}, {'author': 'Frank Sinatra','quote': 'The best revenge is massive success.'}, {'author': 'Wayne Gretzy','quote': 'You miss 100% of the shots you don\'t take.'}, {'author': 'Nelson Mandela','quote': 'Resentment is like drinking poison and waiting for your enemies to die.'}, {'author': 'Elbert Hubbard','quote': 'Do not take life too seriously. You will not get out alive.'}, ]; function generateQuote(){ const random = Number.parseInt(Math.random()*arrayOfQuotes.length + 1); document.querySelector('#quoteOutput').textContent = `\"${arrayOfQuotes[random].quote}\"`; document.querySelector('#authorOutput').textContent = `-${arrayOfQuotes[random].author}`; } </script> </body> https://github.com/JS-Beginners/quote-of-the-day-project/blob/main/quotes.js _____________________________________________________________ JS Fallback script: ----------------- <script src="https://mipage.com/pathtoscript/owlscript.js" onerror="loadFallbackScript()"></script> and then loading the fallback script from code: <script> function createScriptElement(src) { const script = document.createElement('script'); script.src = src; return script; } function loadFallbackScript() { const fallbackScriptElement = createScriptElement('fallback.js'); document.head.append(fallbackScriptElement); } </script> (Source: https://stackoverflow.com/questions/70229312/implement-fallback-incase-original-script-is-not-found/70235593#70235593 ) ______________________________ Searchbar with clickable links: ------------------------------- <!--- https://stackoverflow.com/questions/36634118/creating-a-clickable-search-result-from-a-json-table ---> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> </head> <body> <div class="container" style="padding:1px 1px;"> <form role="form"> <div class="form-group"> <input type="input" class="form-control input-lg" id="txt-search" placeholder="Type your search character"> </div> </form> <div id="filter-records"></div> </div> </body> </html> <script type="text/javascript"> $(document).ready(function(){ var data = [ {"id":"1","page_name":"Startseite","html_name":"index.html","undefined_value":"61","profile_image":"null.png"}, {"id":"2","page_name":"New Art","html_name":"0newart.html","undefined_value":"00","profile_image":"null.png"}, {"id":"99","page_name":"Pagename","html_name":"null","undefined_value":"00","profile_image":"null.png"}]; $('#txt-search').keyup(function(){ var searchField = $(this).val(); if(searchField === '') { $('#filter-records').html(''); return; } var regex = new RegExp(searchField, "i"); var output = '<div class="row">'; var count = 1; $.each(data, function(key, val){ if ((val.html_name.search(regex) != -1) || (val.page_name.search(regex) != -1)) { output += '<div class="col-md-4"><a href="'+val.html_name+''; output += '">'; output += '<p>' + val.html_name + '</p>' output += '</div>'; output += '</div>'; if(count%2 == 0){ output += '</div><div class="row">' } count++; } }); output += '</div>'; $('#filter-records').html(output); }); }); </script> (Source: https://stackoverflow.com/questions/70222874/json-search-fails-after-adding-11th-entry) (Source: https://www.js-tutorials.com/jquery-tutorials/live-search-json-objects-data-using-jquery/) ______________________________ Simulate back button -------------------- history.go(-1) (Source: https://stackoverflow.com/questions/13490407/how-to-emulate-browser-back-button-using-javascript) ________________________ JS Alerts (Popup/Prompt/Entry): ----------------------- https://www.w3schools.com/js/js_popup.asp __________________ Alert user to switch to Landscape ---------------- <script> if(window.innerHeight > window.innerWidth){ alert("Please use Landscape!"); } </script> (Source: https://stackoverflow.com/questions/4917664/detect-viewport-orientation-if-orientation-is-portrait-display-alert-message-ad ) ____________________________________________ Adaptive height iFrame: ---------------------------- Option a): --------- <style> iframe {width: 1px;min-width: 100%;} </style> <iframe id="myIframe" src="0newart.html"></iframe> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/4.3.2/iframeResizer.min.js"></script> <script type="text/javascript"> iFrameResize({ log: true }, '#myIframe') </script> Option b): ---------- <head> <script> function resizeIframe(obj) { obj.style.height = obj.contentWindow.document.documentElement.scrollHeight + 'px'; }</script> .. <iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" /> (Source: https://codehunter.cc/a/javascript/make-iframe-automatically-adjust-height-according-to-the-contents-without-using-scrollbar-duplicate ) _________________________________________________________________ Load html from (same domain site) via jquery: ------------------------------------ <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ var baseUrl = window.location.href.match(/(.*)[\/\\]/)[1]; $("#output").load(baseUrl + "/Search.html"); }); </script> <div class="formClass"> <div id="output"> </div> (Source: https://stackoverflow.com/questions/70268604/direct-path-alternative-for-offsite-html-loading-via-js) ______________________________________________ Load html from offsite via jquery: ---------------------------------- a) Automatically: ------------------------ <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#output").load("https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Search.html"); }); </script> <div class="formClass"> <div id="output"> </div> b) Requiring user button press: --------------------------------------------- <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("#output").load("https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Project.html"); }); }); </script> <body> <div class="formClass"> <div id="output"> </div> <button type="button">Click to Load Content</button> </div> </body> </html> (Source: https://laratutorials.com/jquery-load-load-html-content-from-another-page-using-ajax/ ) AJAX cannot work from file:// but http:// (Source: https://stackoverflow.com/questions/16821432/loading-local-html-file-into-div) (Source: https://stackoverflow.com/questions/70254443/convert-js-to-autoload ) Due to security issues (same origin policy), javascript access to local files is restricted if without user interaction. https://stackoverflow.com/questions/18637418/trying-to-load-local-json-file-to-show-data-in-a-html-page-using-jquery _________________________________________________________________________________ Button load local html file (kinda iframe-y): --------------------------- <!DOCTYPE HTML> <div id="topBar"> <a href ="#" onclick="load_home()"> HOME </a> </div> <div id ="content"> </div> <script> function load_home() { document.getElementById("content").innerHTML='<object type="text/html" data="Search.html" ></object>'; } </script> (Source: https://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript#comment25679730_17636528) ______________________________________ Display variable in popup: -------------------------------------- } alert(urls) (Source: https://stackoverflow.com/questions/1487588/extract-all-links-from-a-string ) ______________________________________________________________________________- Load (scalable) image from user input (buttonpress): ------------------------------ <body> <form> <input type="text" id="imagename" value="https://image.jpg" /> <input type="button" id="btn" value="LatestDAimage"/> </form> <html> <script type="text/javascript"> document.getElementById('btn').onclick = function() { var val = document.getElementById('imagename').value, src = val , img = document.createElement('img'); img.src = src; img.setAttribute('width', '333px'); document.body.appendChild(img); } </script> </body> </html> (Source: https://stackoverflow.com/questions/226847/what-is-the-best-javascript-code-to-create-an-img-element ___________________________________________________ Load image from user input (buttonpress): ------------------------------ <body> <form> <input type="text" id="imagename" value="http://euobtl-44e3133c-aa9e-4b16-b7ca-6645b4610d29.png/v1/fill/w_250,h_250,strp/dreaming_of_virtual_sheep_by_ryedai1_deuobtl-250t.png " /> <input type="button" id="btn" value="LatestDAimage"/> </form> <html> <script type="text/javascript"> document.getElementById('btn').onclick = function() { var val = document.getElementById('imagename').value, src = ' val, img = document.createElement('img'); img.src = src; document.body.appendChild(img); } </script> </body> </html> (Source: https://stackoverflow.com/questions/17634019/javascript-load-an-image-from-url-and-display) ___________________________________________________ Autoclick button on pageload: ----------------------------- <script> window.onload = function(){ document.getElementById('btn').click(); var scriptTag = document.createElement("script"); scriptTag.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"; document.getElementsByTagName("head")[0].appendChild(scriptTag); } </script> (Source: https://stackoverflow.com/questions/50925683/javascript-auto-click-on-a-button-on-page-load/50925730 ) ______________________________________________________ Javascript load iframe: ------------------------ <div id="placeholder"></div> <script id="iframeTemplate" type="text/html"> <iframe src="..."> </iframe> </script> <script type="text/javascript"> var element, html, template; element = document.getElementById("placeholder"); template = document.getElementById("iframeTemplate"); html = template.innerHTML; element.innerHTML = html; </script> (Source: https://stackoverflow.com/questions/8726455/creating-an-iframe-using-javascript/8726513) ___________________________ JS open url ---------------- window.open("https://www.youraddress.com","_self") (Source: https://stackoverflow.com/questions/8454510/open-url-in-same-window-and-in-same-tab ) __________________ Read window url to variable: ----------- <script> var currentUrl = window.location.href; </script> _________________________________________________________________ Copy to clipboard: ------------------ function copyToClipboard(text) { const elem = document.createElement('textarea'); elem.value = text; document.body.appendChild(elem); elem.select(); document.execCommand('copy'); document.body.removeChild(elem); } (Source: https://newbedev.com/html-html-copy-to-clipboard-without-javascript-code-example) ______________________________________________________ Disable right click --------------------------- <script type="text/javascript"> <!-- // Created by smartgb.com, http://www.smartgb.com/free.php document.oncontextmenu = new Function("return false"); // --> </script> (Source: https://www.smartgb.com/free_javascript.php) ______________________ Display current month: --------------------------------- <p id="currmonth"></p> <script> const month = ["January","February","March","April","May","June","July","August","September","October","November","December"]; const d = new Date(); let name = month[d.getMonth()]; document.getElementById("currmonth").innerHTML = name; </script> </body> (Source: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_date_getmonth ) ____________________ Show image (or "do x") at certain season (month period): ------------------------- <div id="banner-container" style="width:400px;height:300px;"></div> <script> var currentTime = new Date(); var month = currentTime.getMonth() + 1; var total = month; // Summer if (total >= 6 && total <= 8) {document.getElementById("banner-container").style.backgroundImage = "url('summer.png')";} // Autumn else if (total >= 9 && total <= 11) {document.getElementById("banner-container").style.backgroundImage="url('fall.png')";} // Winter else if (total == 12 || total == 1 || total == 2) {document.getElementById("banner-container").style.backgroundImage = "url('winter.png')";} // Spring else if (total >= 2 && total <= 6) {document.getElementById("banner-container").style.backgroundImage = "url('spring.png')";} else {document.getElementById("banner-container").style.backgroundImage = "url('summer.png')";} </script> (Source: https://stackoverflow.com/questions/27176180/automatically-change-the-picture-by-month-with-javascript?noredirect=1&lq=1) _________________________________________________ Call js from within javascript: ------------------------------ <script> document.write('<script src="https://ry3yr.github.io/OSTR/myhomepage/snow.js"><\/script>'); </script> <body> </body> ====OR - call if month = december:=== <script> if (new Date().getMonth()===11) document.write('<script src="https://ry3yr.github.io/OSTR/myhomepage/snow.js"><\/script>'); </script> <body> </body> (Source: https://stackoverflow.com/questions/70357122/execute-js-if-month-is-december) _______________ Obfuscate ("encrypt") JS Code: ---------------------------- https://www.cleancss.com/javascript-obfuscate/ http://www.jsobfuscate.com/ _______________ Make a "view source button in css popup" ------------------------ https://css-tricks.com/make-a-view-source-button/ __________________ Source in new window: --------------------------- <button type ="button" onclick="viewSource()">List</button> <script> function viewSource(){; var source = "<html>"; source += document.getElementsByTagName('html')[0].innerHTML; source += "</html>"; source = source.replace(/</g, "&lt;").replace(/>/g, "&gt;"); source = "<pre>"+source+"</pre>"; sourceWindow = window.open('','Source of page','height=800,width=800,scrollbars=1,resizable=1'); sourceWindow.document.write(source); sourceWindow.document.close(); if(window.focus) sourceWindow.focus(); } </script> (Source: https://stackoverflow.com/questions/41945094/add-option-to-view-source-of-current-html-page ) _________________________ Load just containerpart of site into dom: -------------------------------- <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type="text/javascript"> { $(document).ready(function(){ $("#bitbucketissue").load("https://bitbucket.org/alceawisteria/ostr/issues?status=new&status=open #issues-list"); }); } </script> <div class="formClass"> <div id="bitbucketissue"> </div> (Source: https://stackoverflow.com/questions/74993624/loading-only-part-of-site-into-dom-via-jquery) ____________________________ Link to new site based on appended hashtag ------------------------------------------------------------------------ <a rel="me" href="https://pb.todon.de/@alcea"> </a><br> <script type="text/javascript"> if (location.href.indexOf("#underrated") != -1) { window.open("UnderratedContent.html", "_self"); } </script> (Source: https://stackoverflow.com/questions/298503/how-can-you-check-for-a-hash-in-a-url-using-javascript ) ----------------------------------------- Reenable purposely broken element: ------------------------------------------------------- <button id="mypxlbtn" onclick="myPXFDFunction()">Pixelfed</button> <script> function myPXFDFunction() { document.body.innerHTML = document.body.innerHTML.replace('pixlframe', 'iframe'); //document.getElementById('mypxlbtn').style.visibility = 'hidden'; } </script> <pixlframe src="https://pixelfed.de/aoikurayami/embed" width="80%" height="800" scrolling="yes" frameborder="0"></pixlframe><!--<script async defer src="https://pixelfed.de/embed.js"></script>--> ______________________________ Download #JSFiddle via #curl -------------------------------- curl "http://fiddle.jshell.net/${fiddleId}/show/" -H "Referer: http://fiddle.jshell.net/${fiddleId}/" --output "${fiddleId}.html" (Source: https://stackoverflow.com/questions/9851878/is-there-a-download-function-in-jsfiddle/ ) ______________ Easy Copy button ---------------------------- <button onclick="copyToClipboard()" style="background:transparent; border:transparent;">(C)</button> </div> <script> function copyToClipboard() { const str = "curl 'http://fiddle.jshell.net/GSSCD/203//show/' -H 'Referer: http://fiddle.jshell.net/GSSCD/203//' --output 'fiddle.html'" const el = document.createElement('textarea') el.value = str el.setAttribute('readonly', '') el.style.position = 'absolute' el.style.left = '-9999px' document.body.appendChild(el) el.select() document.execCommand('copy') document.body.removeChild(el) } </script> _______________ Slide Toggle --------------------- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").slideToggle(); }); }); </script> </head> <body> <p>Text</p> <button>Toggle </button> </body> ______________ Userinput formfield => create url ------------------------------------------------- <form> <input type="text" id="pixivurl" value="75406576"/> <input type="button" id="btn" value="pixivuserid"/> </form> <script type="text/javascript"> document.getElementById('btn').onclick = function() { var val = document.getElementById('pixivurl').value; var url = "https://rsshub.app/pixiv/user/" + val; var a = document.createElement('a'); var linkText = document.createTextNode(url); a.appendChild(linkText); a.title = "pixivuser"; a.target= '_blank'; a.href = url; a.style.display = 'block'; document.body.appendChild(a); } </script> _____________ Turn YT Channel ID into ChannelURLPlaylist ---------------------------------------------- <form> <input type="text" id="yturl" value="UCn-K7GIs62ENvdQe6ZZk9-w" /> <input type="button" id="btn" value="ChannelPlayListURL" /> </form> <script> document.getElementById('btn').onclick = function() { var val = document.getElementById('yturl').value; val = val.replace('UC', 'UU'); var url = "https://www.youtube.com/embed/videoseries?list=" + val; var a = document.createElement('a'); var linkText = document.createTextNode(url); a.appendChild(linkText); a.title = "yturl"; a.target = '_blank'; a.href = url; a.style.display = 'block'; document.body.appendChild(a); } </script> _______________ Random iFrame: ------------------------- <div id="bigdiv" style="position:fixed; top: 0px; left: 505px;"> <button id="btn" class="box">Random</button> <iframe id="frame" src="rss-scrolling-source01.html" frameborder="0" scrolling="no" height=65 width=400></iframe> </div> <script> var cat1 = [    "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/rss-scrolling-source01.html",    "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/rss-scrolling-source02.html" ]; var myFrame = document.getElementById("frame"); function getRandomUrl(myFrame) { var index = Math.floor(Math.random()*cat1.length); var url = cat1[index]; myFrame.src = url; } btn.addEventListener("click", function() { getRandomUrl(myFrame); }); </script> ___________________ Click button on pageload: -------------------------------------- <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ document.getElementById("btn").click(); });</script> _________________________________ Texteditor with save function --------------------------------------------- <!---http://fiddle.jshell.net/ourcodeworld/rce6nn3z/2//show--> <script type="text/javascript" src="/js/lib/dummy.js"></script> <link rel="stylesheet" type="text/css" href="/css/result-light.css"> <style id="compiled-css" type="text/css"> /* EOS */ </style> <script id="insert"></script> </head> <body> <textarea id="text-val" rows="4">Enter Text here</textarea><br/> <input type="button" id="dwn-btn" value="Download"/> <script type="text/javascript">//<![CDATA[ function download(filename, text) { var element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } // Start file download. document.getElementById("dwn-btn").addEventListener("click", function(){ // Generate download of hello.txt file with some content var text = document.getElementById("text-val").value; var filename = "hello.txt"; download(filename, text); }, false); //]]></script> <script> // tell the embed parent frame the height of the content if (window.parent && window.parent.parent){ window.parent.parent.postMessage(["resultsFrame", { height: document.body.getBoundingClientRect().height, slug: "rce6nn3z" }], "*") } // always overwrite window.name, in case users try to set it manually //window.name = "result" </script> </body> </html> _______________ Copy today date to clipboard: ------------------------------------------------ <a href="javascript:copydateToClipboard()">Date</a> <script> function copydateToClipboard() { var nowd = new Date().toUTCString().slice(0,16); const el = document.createElement('textarea') el.value = nowd el.setAttribute('readonly', '') el.style.position = 'absolute' el.style.left = '-9999px' document.body.appendChild(el) el.select() document.execCommand('copy') document.body.removeChild(el) }</script> _______________________ Days-since-online-counter --------------------------------------- Site online since <button id='counter' style="width:26px;height:20px;background:transparent; border:transparent;" onclick="window.open('https://web.archive.org/web/https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Startseite.html', '_blank');"></button> &nbsp;&nbsp;days. <!--<button id='today' ></button>--> <script src='https://code.jquery.com/jquery-2.2.4.min.js'></script> <script>$(document).ready(function(){ var oneDay = 24*60*60*1000; var start = new Date(2021, 06, 13); var now = new Date(); var elapsed = Math.round(Math.abs((now.getTime() - start.getTime())/(oneDay)-1)); $('#counter').html(` ${elapsed} `); var nowd = new Date().toUTCString().slice(0,16); $('#today').html(` ${nowd} `);});</script> ______________________________ Datepicker ---------------- <link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-3.6.0.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script> <script>$( function() { $( "#datepicker" ).datepicker({changeMonth: true,changeYear: true});} );</script> <p>Date: <input type="text" id="datepicker"></p> ______________________________ Random image on pageload: ------------------------------------------- <!----RandomImage---> <button id="myrdpbtn" style="background:transparent; border:transparent;" onclick="swap()">RandomPicture</button> <style type="text/css"> #banner {height:100%;object-fit: contain; //padding:0;margin:0;text-align:right; //position:relative; //position:absolute; top: 0px; left: 1200px; //background-position: center center; background-size: contain; background-repeat: no-repeat;}</style> <script type="text/javascript"> if (document.getElementById) { window.onload = swap }; function swap() { var numimages=8; rndimg = new Array( "https://m.box.com/file/903146245504/https%3A%2F%2Fapp.box.com%2Fs%2Fj7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png", "https://m.box.com/file/905690094898/https%3A%2F%2Fapp.box.com%2Fs%2Fj7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png", "https://cdnb.artstation.com/p/assets/images/images/055/144/127/large/ryedai1-2022-10-19-aoi-realist-no2.jpg?1666212593", "https://other00.deviantart.net/c476/o/2021/321/8/f/subaru_and_misora_by_pasc91.png", "https://m.box.com/file/900365515983/https%3A%2F%2Fapp.box.com%2Fs%2Fj7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png", "https://m.box.com/file/889506897379/https%3A%2F%2Fapp.box.com%2Fs%2Fj7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png", "https://m.box.com/file/903146245504/https%3A%2F%2Fapp.box.com%2Fs%2Fj7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png", "https://m.box.com/file/896387464705/https%3A%2F%2Fapp.box.com%2Fs%2Fj7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png" ); x=(Math.floor(Math.random()*numimages)); randomimage=(rndimg[x]); document.getElementById("banner").style.backgroundImage = "url("+ randomimage +")"; }</script> </head> <div id="banner""></div> _____________________ Random image on pageload (v2 15-7-23) --------------------------- (added dropdown picker) <button id="myrdpbtn" style="background:transparent; border:transparent;" onclick="swap()">RandomPicture</button> <select id="image-selector" style="width:250px;"> <option value="">Select an image</option> </select> <style type="text/css"> #banner { height:100%; object-fit: contain; background-size: contain; background-repeat: no-repeat; } </style> <script type="text/javascript"> if (document.getElementById) { window.onload = swap }; var urls = [ "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/arthost/2022-10-18-TheOrgOfTwo.png#01", "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/arthost/2022-10-19-Aoi-Realist-no2.png#02", "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/arthost/2023-03-01-KisaraRelease.png#03", "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/arthost/2023-03-19-PunkLuv.png#04", "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/arthost/2023-03-17-HappyAlcea.png#05", "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/arthost/2023-05-06-ShokaConfidentBusinessReaper.png#06", "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/arthost/2023-05-08-YuNAoiFlippedHappiness.gif#07", "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/arthost/2023-05-10-RollbackCea.png#08", "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/arthost/2023-05-11-HibikiMisoraSemiRealism-BoredMissy.png#09", "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/arthost/2023-05-19-MisoraSelfFromElse.png#10", "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/arthost/2023-05-21-LinkIntoVRAINSTime.png#11", "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/arthost/2023-05-21-ZeriouslyContentAlcea.png#12", "https://alceawisteria.codeberg.page/images/arthost/2023-06-22-ShokaHi.png#13", "https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/ca81d24e-918d-4918-bd5a-f5b53c49858b/dg0nhf2-77f59ee8-51d9-4e73-a016-ea7a9af7900a.png/v1/fill/w_1117,h_715/2023_06_23_happyyu_by_aoikurayami1_dg0nhf2-pre.png?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7ImhlaWdodCI6Ijw9ODIwIiwicGF0aCI6IlwvZlwvY2E4MWQyNGUtOTE4ZC00OTE4LWJkNWEtZjViNTNjNDk4NThiXC9kZzBuaGYyLTc3ZjU5ZWU4LTUxZDktNGU3My1hMDE2LWVhN2E5YWY3OTAwYS5wbmciLCJ3aWR0aCI6Ijw9MTI4MCJ9XV0sImF1ZCI6WyJ1cm46c2VydmljZTppbWFnZS5vcGVyYXRpb25zIl19.PFzoLqNOce2sMzH4IDpTYhxIvC7YT4TlKU5X_MYsb-Q#14", "https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/ca81d24e-918d-4918-bd5a-f5b53c49858b/dg2ph6q-5ba53964-efcb-4f30-9dd0-6f97520e11de.png/v1/fill/w_1117,h_715,q_70,strp/backhug_by_aoikurayami1_dg2ph6q-pre.jpg?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7ImhlaWdodCI6Ijw9ODIwIiwicGF0aCI6IlwvZlwvY2E4MWQyNGUtOTE4ZC00OTE4LWJkNWEtZjViNTNjNDk4NThiXC9kZzJwaDZxLTViYTUzOTY0LWVmY2ItNGYzMC05ZGQwLTZmOTc1MjBlMTFkZS5wbmciLCJ3aWR0aCI6Ijw9MTI4MCJ9XV0sImF1ZCI6WyJ1cm46c2VydmljZTppbWFnZS5vcGVyYXRpb25zIl19.aE2GYnZKfcTbmoUfWBm8t3RxnroMSTc6vn0Sokhov6o#15", "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/arthost/2022-11-02-RealistShoka.png" ]; var select = document.getElementById("image-selector"); for (var i = 0; i < urls.length; i++) { var option = document.createElement("option"); option.value = urls[i]; var filename = urls[i].substring(urls[i].lastIndexOf('/')+1); option.text = "Image " + (i+1) + " (" + filename + ")"; select.add(option); } function swap() { var imageSelector = document.getElementById("image-selector"); var selectedImage = imageSelector.options[imageSelector.selectedIndex].value; if (selectedImage) { document.getElementById("banner").style.backgroundImage = "url(" + selectedImage + ")"; } else { var numimages = urls.length; var x = Math.floor(Math.random() * numimages); var randomimage = urls[x]; document.getElementById("banner").style.backgroundImage = "url(" + randomimage + ")"; } } document.getElementById("image-selector").addEventListener("change", swap); </script> <div id="banner"></div> ______________________ Random background on pageload: -------------------------------------------------- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css"> <style> #random{ width: 100%; height: 100%; //border: 1px solid black; background-image: url(''); //background-position: center center; //background-size: cover; //background-repeat: no-repeat;} </style> <body> <body onload="randombg()"><div id="random" ></div> <script> function randombg(){ var random= Math.floor(Math.random() * 6) + 0; var bigSize = ["url('https://media1.giphy.com/media/l0HlVrqPItQH8D4iI/giphy.gif')", "url('https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/bgfiles/cool_stuff_anim.gif')", "url('https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/bgfiles/cool_stuff_anim.gif')", "url('https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/bgfiles/comments_anim.gif')", "url('https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/images/bgfiles/comments_anim.gif')", "url('https://media1.giphy.com/media/l0HlVrqPItQH8D4iI/giphy.gif')"]; document.getElementById("random").style.backgroundImage=bigSize[random];}</script> (Source: https://stackoverflow.com/questions/75237942/load-random-tiled-image-into-style-background/75239481#75239481 ) ________________ Convert page to source code: --------------------------------------------- <button id="mypxlbtn" style="background:transparent; border:transparent;" onclick="myPXXFDFunction()">Source!</button> <script> function myPXXFDFunction() { document.documentElement.innerHTML = `<pre>${document.documentElement.innerHTML.replace(/</g,"&lt;")}</pre>`; } </script> _______________ Change favicon ------------------------ <button id="button">Change favicon</button> <script>function changeFavicon() {var link; link = document.createElement('link'); link.type = 'image/x-icon'; link.rel = 'shortcut icon'; link.href = 'https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/favicon.ico'; document.getElementsByTagName('head')[0].appendChild(link);}; document.getElementById('button').addEventListener('click', function(event) { changeFavicon();}, false); document.body.addEventListener('online', function() { console.log('online')}, false); document.body.addEventListener('offline', function() { console.log('offline')}, false); </script> ___________________ Check if url string exists ------------------------------------- <script src="jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { if (window.location.href.indexOf("Startseiteplayer") > -1) { alert("You have the player open already !"); window.history.back(); } else { //window.open("Startseiteplayerrun.html","_self"); link = document.createElement("a"); link.href = "Startseiteplayerrun.html"; //link.target = "_blank"; link.click() ;}}); </script><br> <a href="index.html">home</a> _______________ Check if iframed ---------- <script> if ( window.location !== window.parent.location ) { alert("You have the player open already !"); window.history.back(); } else { // The page is not in an iframe } </script> <!---https://tommcfarlin.com/check-if-a-page-is-in-an-iframe/--> ________________ Allow user txt file open & display lines --------------------------------------------------- <script> const $output = document.getElementById('output') document.getElementById('file').onchange = function() { var file = this.files[0]; var reader = new FileReader(); reader.onload = function(progressEvent) { // Entire file const text = this.result; $output.innerText = text // By lines var lines = text.split('\n'); for (var line = 0; line < lines.length; line++) { console.log(lines[line]); } }; reader.readAsText(file); };</script> <input type="file" name="file" id="file"> <div id='output'> ...</div> (Source: https://stackoverflow.com/questions/23331546/how-to-use-javascript-to-read-local-text-file-and-read-line-by-line ) ______________________________ Display random line from file: --------------------------------------------- <!DOCTYPE html> <!--https://run.plnkr.co/plunks/6wCVvXqoIGl6hN6Q--> <html> <head> <meta charset="utf-8" /> <!--<link rel="stylesheet" href="style.css" />--> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <script> var lines; var randomNumber; var lastRandomNumber; $(document.body).ready(function () { // load the trivia from the server $.ajax({ url: 'https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Dayquotes.html' }).done(function(content) { // normalize the line breaks, then split into lines lines = content.replace(/\r\n|\r/g, '\n').trim().split('\n'); // only set up the click handler if there were lines found if (lines && lines.length) { $('#showLine').on('click', function () { // loop to prevent repeating the last random number while (randomNumber === lastRandomNumber) { randomNumber = parseInt(Math.random() * lines.length); // check to prevent infinite loop if (lines.length === 1) { break; } } // keep track of the last random number lastRandomNumber = randomNumber; // show the corresponding line $('#trivia').text(lines[randomNumber]); }); } }); }); </script> </head> <body><button id="showLine">Random!</button> <p id="trivia"></p></body> </html> (Source: https://jsfiddle.net/aoikurayami/1yhjods7/ ) _______________________ Random Line from file (autoclick + linksupport) -------------------------------------------- <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> var lines, randomNumber, lastRandomNumber; $(document.body).ready(function() { $.ajax({url: "https://alceawis.de/Daymusic_array.js"}).done(function(e) { lines = e.replace(/\r\n|\r/g, "\n").trim().split("\n"); if (lines.length) { $("#showLine").on("click", function() { for (; randomNumber === lastRandomNumber && (randomNumber = parseInt(Math.random() * lines.length), 1 !== lines.length);); lastRandomNumber = randomNumber; var line = lines[randomNumber].replace("{'quote': '", "").replace("'},", ""); $("#trivia").html(line); }).trigger("click"); document.getElementById("showLine").style.visibility = "hidden"; } }); }); </script> <button id="showLine">CurrListening</button> <p id="trivia"></p> (source: https://stackoverflow.com/questions/75279944/hiding-button-by-id-works-but-clicking-it-not/75279960#75279944) ______________________ Add background behind text element: ---------------------------------- <style>h39 { display: table; font-size:20px;background-color:white;}</style> <h39><p id="trivia"></p></h39> (Source: https://stackoverflow.com/questions/14310154/how-do-i-set-a-background-color-for-the-width-of-text-not-the-width-of-the-enti ) ______________________ Prevent accidental page reload: ----------------------------------------- window.onbeforeunload = function() { return "Are you sure you want to leave? Think of the kittens!"; } __________________________ Move / interact (with element),based on screen orientation: ------------------------------------------ <script>if(window.innerHeight > window.innerWidth){ document.write('<div id="bigdiv2" style="position:relative; top: 70px; left: -410px;">');} </script> _____________________________ Url with anti-cache string --------------------------------- <a href="javascript:cachereload()">LATEST</a> <script> function cachereload() { const url = new URL('http://alceawisteria.byethost7.com/PHP/0demo/2023-03-25-BoxNet/BoxCOMArt.php'); url.searchParams.set('reloadTime', Date.now().toString()); let a= document.createElement('a'); a.target= '_blank'; a.href= url.toString(); a.click(); } </script> iframe http: (only on localhost...) 1) Create file on https, with redirect redirect-to-http.html: <script> document.location.href ="http://alceawisteria.byethost7.com/PHP/0demo/2023-03-25-BoxNet/yourpage.html"; </script> 2) iframe it <iframe src="redirect-to-http.html"></iframe> (Source: https://stackoverflow.com/questions/18327314/how-to-allow-http-content-within-an-iframe-on-a-https-site ) _____________________________________ Render site in ajax popup: ------------------------------- <script src="https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/jquery.min.js"></script> <script> $.ajax({ url : "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/index.html", success : function(result){ alert(result); } }); </script> (Source: https://stackoverflow.com/questions/8197709/javascript-read-html-from-url-into-string ) _______________________________ Render Site via js xmlhttprequest fetch ------------------------------------------ <script> var req = new XMLHttpRequest(); req.open('GET', 'https://ry3yr.github.io', false); req.send(null); if(req.status == 200) //alert(req.responseText); document.write(req.responseText); </script> (Source: https://stackoverflow.com/questions/5299646/javascript-how-to-fetch-the-content-of-a-web-page ) ___________________________________________________ Self unlocking -truly encrypted html page-: ------------------------------------------------- 1) Encrypt html via: https://www.maxlaumeister.com/pagecrypt/ 2) Add to html beginning: Autosubmit: <script> window.onload = function(){ document.getElementById('submitPass').click(); var scriptTag = document.createElement("script"); scriptTag.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"; document.getElementsByTagName("head")[0].appendChild(scriptTag); } </script> 3) replace in html Autopass (replace in xx-protected.html) <input id="pass" type="password" name="pass" value="1234" autofocus> _______________________________ HTML5 Audioplayer / Musicplayer ------------------------------------------------------ (with playlist) https://codepen.io/craigstroman/pen/aOyRYx