/ Gists

Gists

On gists

Async/Await Tricks

JavaScript

index.js #

/*
@url https://levelup.gitconnected.com/7-simple-async-await-tricks-for-developers-who-hate-asynchronous-javascript-fe370ac7fe72
*/

// 1. Use Promise.allSettled() for Safer Batch Processing
const results = await Promise.allSettled([
  fetchData1(),
  fetchData2(),
  fetchData3(),
]);
results.forEach(result => {
  if (result.status === 'fulfilled') {
    console.log('Success:', result.value);
  } else {
    console.error('Failed:', result.reason);
  }
});


// 2. Use Timeouts to Prevent Hanging Promises
const withTimeout = (promise, ms) =>
  Promise.race([
    promise,
    new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), ms)),
  ]);

try {
  const data = await withTimeout(fetchData(), 5000);
} catch (err) {
  console.error(err.message); // "Timeout" if it takes too long
}


// 3. Sequential Loops with Async/Await
const urls = ['url1', 'url2', 'url3'];
for (const url of urls) {
  const data = await fetch(url);
  console.log(data);
}


// 4. Dynamic Delays with await
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
console.log('Start');
await delay(2000); // Waits 2 seconds
console.log('End');


// 5. Always Use try...catch Inside Async Functions
async function fetchData(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) throw new Error('Fetch failed');
    return await response.json();
  } catch (err) {
    console.error('Error:', err.message);
    return null;
  }
}


// 6. await Outside Loops to Batch Workloads
const urls = ['url1', 'url2', 'url3'];
const responses = await Promise.all(urls.map(url => fetch(url)));
const data = await Promise.all(responses.map(res => res.json()));
console.log(data);


// 7 ... fking yield => dont care

On gists

HTML 5: Restricted datalist

JavaScript HTML

index.html #

<!DOCTYPE html>
<html lang="cs">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Výběr s Datalist</title>
  <script>
    function validateInput(input) {
      const datalist = document.getElementById('fruit-list');
      const options = datalist.getElementsByTagName('option');
      const values = Array.from(options).map(option => option.value);

      if (!values.includes(input.value)) {
        input.value = ''; // Vymaže hodnotu, pokud není v datalistu
      }
    }
  </script>
</head>
<body>
  <form>
    <label for="fruit">Vyberte ovoce:</label>
    <input type="text" id="fruit" name="fruit" list="fruit-list" oninput="validateInput(this)">
    <datalist id="fruit-list">
      <option value="Jablko">
      <option value="Banán">
      <option value="Třešně">
      <option value="Datle">
    </datalist>
    <button type="submit">Odeslat</button>
  </form>
</body>
</html>

On gists

HTML 5 - role

HTML

index.txt #

@link https://www.w3.org/TR/wai-aria-1.1/#role_definitions

banner: Hlavní záhlaví stránky.
complementary: Doplňkový obsah.
contentinfo: Informace o obsahu stránky (patička).
main: Hlavní obsah stránky.
navigation: Navigace.
search: Vyhledávací formulář.
article: Samostatný článek nebo příspěvek.
region: Oblast obsahu, která má svůj vlastní význam.
alert: Důležité zprávy nebo upozornění.
dialog: Dialogové okno.
button: Tlačítko.
link: Odkaz.
form: Formulář.
tab: Karta v kartách.
tabpanel: Obsah karty.



On gists

Transformace (transform) does not change flow

CSS CSS trick

index.html #

	<div>
		<figure>
				<img src="http://picsum.photos/400/400?grayscale" alt="">
			<figcaption>
				Nakej popis
			</figcaption>
		</figure>
		
		
	</div>

On gists

Pipeline operator

JavaScript

index.js #

/* https://medium.com/@asierr/javascripts-pipeline-operator-the-game-changer-for-cleaner-code-e9eb46179510 */

const first = (x) => x + 1 
const second = (x) => x + 2 
const last = (x) => x + 1000 


const x = 0

const result = first(second(last(x)))
const result2 = x |> increment |> square |> double;


console.log(result)
console.log(result2)



/* examples */

// before
fetch('/api/data')
  .then(response => response.json())
  .then(data => transformData(data))
  .then(filteredData => display(filteredData));

// after
fetch('/api/data')
  .then(response => response.json())
  |> transformData
  |> display;


// after with await
const data = await fetchData() |> parseData |> processData


// before
const slug = replaceSpaces(toLowerCase(trim(userInput)));

// after
const slug = userInput |> trim |> toLowerCase |> replaceSpaces;

On gists

Composed Path

JavaScript

index.js #

document.querySelector('button').addEventListener('click', (e) => {
  console.log(e.composedPath())
})

On gists

Sandbox skeleton (demo code) tailwind, alpine

Popular ⭐ Tailwind CSS Alpine.js

index.html #

<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <title>Sandbox - RJ</title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="https://unpkg.com/@tailwindcss/browser@4"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
  </head>
  <body>
  
   <!-- Code here ... -->
   
   
    
  </body>
</html>

On gists

Glowing button

CSS CSS trick

index.css #

/*
https://jsbin.com/jonekutuja/edit?html,css,output
*/

/* 
  Project: CSS Glowing Button
  Created: Sunday, 06 March 2022
  Author: Jamshid Elmi 
  Tutorial: https://youtu.be/b_8fHNIHFk4
*/
html, body {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #161616;
  overflow: hidden;
  /* transform: scale(1.5); */
}

/* button */
.btn {
  margin: 100px;
  padding: 15px 40px;
  border: none;
  outline: none;
  color: #FFF;
  cursor: pointer;
  position: relative;
  z-index: 0;
  border-radius: 12px;
}
.btn::after {
  content: "";
  z-index: -1;
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #333;
  left: 0;
  top: 0;
  border-radius: 10px;
}
/* glow */
.btn::before {
  content: "";
  background: linear-gradient(
    45deg,
    #FF0000, #FF7300, #FFFB00, #48FF00,
    #00FFD5, #002BFF, #FF00C8, #FF0000
  );
  position: absolute;
  top: -2px;
  left: -2px;
  background-size: 600%;
  z-index: -1;
  width: calc(100% + 4px);
  height:  calc(100% + 4px);
  filter: blur(8px);
  animation: glowing 20s linear infinite;
  transition: opacity .3s ease-in-out;
  border-radius: 10px;
  opacity: 0;
}

@keyframes glowing {
  0% {background-position: 0 0;}
  50% {background-position: 400% 0;}
  100% {background-position: 0 0;}
}

/* hover */
.btn:hover::before {
  opacity: 1;
}

.btn:active:after {
  background: transparent;
}

.btn:active {
  color: #000;
  font-weight: bold;
}

On gists

Neon button

CSS CSS trick

index.html #

<!-- https://jsbin.com/liyigoniku/edit?html,css,output -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Neon Button</title>
</head>
<body>
  <a class="neon">Neon</a>
</body>
</html>

On gists

@property like fake replacement for animation ;)

CSS trick

index.css #

/*
https://yuanchuan.dev/time-uniform-for-css-animation
*/


@property --t {
  syntax: "<number>";
  initial-value: 0;
  inherits: true;
}


@keyframes animate-time {
  from { --t: 0 }
  to   { --t: 31536000000 }
}

/* Put animation to :root so we can use --t everywhere */
:root {
  animation: animate-time 31536000000ms linear infinite;
}

div {
  background: red;
  width: 100px;
  height: 100px;
  margin: 5rem;
  
}

.second {
   background: hsl(
    calc(var(--t) * .072), 60%, 60%
  );
}

div.first {
  transform: rotate(
    calc(var(--t) / 1000 / 10 * 1turn)
  );
}