/ Gists / JavaScript

Gists - JavaScript

On gists

Drag drop

JavaScript

demo.html #

<!-- https://jsbin.com/rideqiloge/edit?html,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" />
    <title>Drag and Drop Effect in JavaScript</title>

    <!-- Add some CSS Code -->
    <style>
      * {
        margin: 0px;
        padding: 0px;
      }
      body {
        background-color: black;
        height: 100vh;
        width: 100%;
      }
      .container {
        display: flex;
        justify-content: space-around;
        align-items: center;
        flex-wrap: wrap;
        height: 100vh;
        width: 100%;
      }
      .whiteBox {
        width: 150px;
        height: 150px;
        background-color: white;
        border: none;
        border-radius: 50%;
      }
      .imgBox {
        background: url("https://images.unsplash.com/photo-1469474968028-56623f02e42e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=874&q=80") no-repeat center center;
        height: 100%;
        width: 100%;
        background-size: cover;
        border: none;
        border-radius: 50%;
        cursor: pointer;
        display: grid;
        place-items: center;
      }
      .hold {
        border: 4px solid white;
      }
      .hide {
        display: none;
      }
    </style>
  </head>
  <body>

    <div class="container">
      <div class="whiteBox" id="box">
        <div class="imgBox" draggable="true"></div>
      </div>
      <div class="whiteBox" id="box"></div>
      <div class="whiteBox" id="box"></div>
      <div class="whiteBox" id="box"></div>
      <div class="whiteBox" id="box"></div>
    </div>

    <!-- Let's start to write script -->
    <script>

      // Access the HTML Elements
      let imgBox = document.querySelector(".imgBox");
      let whiteBoxes = document.getElementsByClassName("whiteBox");


      // When user start to drag the element ( Here, imgBox )
      // Event listeners for dragable imgBox element
      imgBox.addEventListener("dragstart", (e) => {

        e.target.className += " hold";
        setTimeout(() => {
          e.target.className = "hide";
        }, 0);
      });

      // When user ready to drop the element 
      imgBox.addEventListener("dragend", (e) => {
        e.target.className = " imgBox";
      });

      // Iterate all the white boxes
      for (Boxes of whiteBoxes) {
        Boxes.addEventListener("dragover", (e) => {
          e.preventDefault();
        });

        Boxes.addEventListener("drop", (e) => {
          e.target.append(imgBox);
        });
      }
    </script>
  </body>
</html>

On gists

Stacks / Queue

JavaScript

stack.js #

class Stack {
    #items = []

    push(item) {
        this.#items.push(item)
    }

    pop() {
        if(this.isEmpty()) return 'Underflow'
        return this.#items.pop()
    }

    isEmpty() {
        return this.#items.length === 0
    }

    get length() {
        return this.#items.length
    }

    getItems() {
        return this.#items
    }

    prettify() {
        let resultString = ''
        for(let i = 0; i < this.#items.length; i++)
            resultString += this.#items[i] + ' '
        return resultString
    }
}

let foods = new Stack

foods.push('pizza')
foods.push('hamburger')
foods.push('kebab')
foods.push('kufte')

console.log(foods.length) // 4

console.log(foods.getItems()) // [ 'pizza', 'hamburger', 'kebab', 'kufte' ]

console.log(foods.prettify()) // pizza hamburger kebab kufte

console.log(foods.pop()) // kufte
console.log(foods.pop()) // kebab
console.log(foods.pop()) // hamburger
console.log(foods.pop()) // pizza

console.log(foods.length) // 0

On gists

Before, Prepend, Append, After (insertAdjacentElement) ... (*Text, *Html)

JavaScript

demo.html #

<!-- https://jsbin.com/pajoyovilu/3/edit?html,css,js,console,output -->


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
	
	
	<button onclick="placeTo('beforebegin')">before</button>
	<button onclick="placeTo('afterbegin')">prepend</button>
	<button onclick="placeTo('beforeend')">append</button>
	<button onclick="placeTo('afterend')">after</button>
	
	
	<div id="x">
		<div>START</div>
		<AA>aa</AA>
		<BB>bb</BB>
		<CC>cc</CC>
		<div>END</div>
		
	</div>
</body>
</html>

On gists

Debounced method in Vue (settimeout), fetch with cors mode

JavaScript Vue.js

example.js #

  methods: {
    search() {
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        this.findSong()
      }, 500)
    },

    async findSong() {
      let headers = new Headers()
      headers.append('Content-Type', 'application/json')
      headers.append('Accept', 'application/json')
      headers.append('Origin', 'http://vue3.rjwebdesign.cz')
      headers.append('GET', 'POST', 'OPTIONS')

      let q = encodeURI(this.q)
      if (!this.q) {
        return
      }

      //console.log(q)
      // return

      const response = await fetch(`https://itunes.apple.com/search?term=${q}&limit=50`, {
        mode: 'cors',
        method: 'POST',
        headers: headers
      }).catch(err => console.log(err))

      const data = await response.json()
      this.songs = data.results.filter(item => item.kind == 'song')
      console.log(this.songs)
    },

On gists

ES6: Template system in literal

JavaScript ES 6

example.js #

let post = {
    title: 'JavaScript Template Literals',
    excerpt: 'Introduction to JavaScript template literals in ES6',
    body: 'Content of the post will be here...',
    tags: ['es6', 'template literals', 'javascript']
};


let {title, excerpt, body, tags} = post;

let postHtml = `<article>
<header>
    <h1>${title}</h1>
</header>
<section>
    <div>${excerpt}</div>
    <div>${body}</div>
</section>
<footer>
    <ul>
      ${tags.map(tag => `<li>${tag}</li>`).join('\n      ')}
    </ul>
</footer>`;

window['out'].innerHTML = postHtml

On gists

Promises, Await / Async, Callbacks

JavaScript

demo1.html #

<!--https://www.loginradius.com/blog/engineering/callback-vs-promises-vs-async-await/-->

<!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" />
        <title>Document</title>
    </head>
    <body>
        <script type="module">
            // 1 Promises - way 1

            // Promise1
            const promise1 = new Promise((resolve, reject) => {
                const condition = true;
                if (condition) {
                    setTimeout(function () {
                        resolve('Promise is resolved!'); // fulfilled
                    }, 300);
                } else {
                    reject('Promise is rejected!');
                }
            });

            // Promise2
            const promise2 = function () {
                return new Promise(function (resolve, reject) {
                    const message = `Hi, How are you!`;

                    resolve(message);
                });
            };

            // Test = chaining
            const testPromise = function () {
                promise1
                    .then(promise2)
                    .then(successMsg => {
                        console.log('Success:' + successMsg);
                    })
                    .catch(errorMsg => {
                        console.log('Error:' + errorMsg);
                    });
            };

            testPromise();

            // 2 Async / Await  = way 2
            async function testPromise2() {
                try {
                    let message = await promise1;
                    let message2 = await promise2();
                    console.log(message);
                    console.log(message2);
                } catch (error) {
                    console.log('Error:' + error.message);
                }
            }

            // we call it ...
            (async () => {
                await testPromise2();
            })();
        </script>
    </body>
</html>

On gists

Ajax / Fetch()

JavaScript

examples.js #

/**
 * Fetch
 * 
 * RESTFul API - https://jsonplaceholder.typicode.com/
 * Docs - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
 */

fetch('https://jsonplaceholder.typicode.com/comments/1')
    .then(response => response.json())
    .then(data => console.log(data))

fetch('https://jsonplaceholder.typicode.com/comments', {
        method: "POST",
        body: JSON.stringify({
            postId: 1,
            name: 'Dylan',
            email: 'dylansemail310@gmail.com',
            body: 'That was dope!'
        })
    })
    .then(response => response.json())
    .then(data => console.log(data))
    
    
    
    /*
    examples
    */
    
  fetch('https://api.example.com/items')
  .then(res => res.json())
  .then(data => {
    console.log(data) 
  })
  .catch(err => {
    console.log('Error:', err)
  })
  

// POST  
const body = {title: 'Foo', body: 'Bar'};

fetch('https://api.example.com/items', {
  method: 'POST', 
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(body)
})
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.log(err))
  
  
  
// FILE UPLOAD
const formData = new FormData();
formData.append('file', fileInput.files[0]);

fetch('https://api.example.com/upload', {
  method: 'POST',
  body: formData
});


// With Async/Await
async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/items');
    const data = await response.json();
    console.log(data);
  } catch(err) {
    console.log('Error:', err);
  }
}

fetchData();


// Fetching From Multiple Sources
async function get() {

  const [userRes, postsRes] = await Promise.all([
    fetch('/user'),
    fetch('/posts')
  ]);
  
  const user = await userRes.json();
  const posts = await postsRes.json();

  return {user, posts};

}

const data = await get();


// ERRORS
fetch('https://api.example.com/items')
  .then(res => {
    // Handle response
  })
  .catch(err => {
    console.log('Fetch Error :-S', err);  
  });
  
  
  fetch('https://api.example.com/items')
  .then(res => {
    if (!res.ok) {
      throw new Error('Bad status code'); 
    }
   
    return res.json()
  })
  .then(data => {
    console.log(data); 
  })
  .catch(err => {
    console.log('Error:', err); 
  });
  
  
  
  
  // full config with cors and auth

  fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token123'
  },
  body: JSON.stringify({ name: 'Alice', age: 25 }),
  mode: 'cors',
  cache: 'no-cache',
  credentials: 'same-origin'
});





//  Built-In Request Abortion Mechanism
const controller = new AbortController();
const signal = controller.signal;

fetch('https://api.example.com/data', { signal })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('Request was cancelled');
    } else {
      console.error('Request failed:', error);
    }
  });
// Cancel the request after 3 seconds
setTimeout(() => controller.abort(), 3000);





// Improved Error Handling
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

On gists

Loops speed comparision

JavaScript

loops.js #

const numbers = [...Array(10000000)].map(
  (_, index) => index + 1
);
function measurePerf(label, method) {
  console.time(label);
  method();
  console.timeEnd(label);
}
measurePerf('filter', () => {
  const evens = numbers.filter((num) => num % 2 === 0);
});
measurePerf('forEach', () => {
  const evens = [];
  numbers.forEach((num) => {
    if (num % 2 === 0) {
      evens.push(num);
    }
  });
});
measurePerf('for...of', () => {
  const evens = [];
  for (const num of numbers) {
    if (num % 2 === 0) {
      evens.push(num);
    }
  }
});
measurePerf('for', () => {
  const evens = [];
  for (let i = 0; i < numbers.length; i++) {
    const num = numbers[i];
    if (num % 2 === 0) {
      evens.push(num);
    }
  }
});

On gists

Download file via JavaScript

JavaScript

download.js #

// https://javascript.plainenglish.io/how-to-download-a-file-using-javascript-fec4685c0a22

function downloadFile(url, fileName) {
  fetch(url, { method: 'get', mode: 'no-cors', referrerPolicy: 'no-referrer' })
    .then(res => res.blob())
    .then(res => {
      const aElement = document.createElement('a');
      aElement.setAttribute('download', fileName);
      const href = URL.createObjectURL(res);
      aElement.href = href;
      aElement.setAttribute('target', '_blank');
      aElement.click();
      URL.revokeObjectURL(href);
    });
};


downloadFile('https://www.google-analytics.com/analytics.js', 'gooleAnalytics.js')

On gists

Play/Pause video on scroll

JavaScript

on-scroll.js #

    window.addEventListener("load", videoScroll);
    window.addEventListener("scroll", videoScroll);

    function videoScroll() {
      if (document.querySelectorAll("video[autoplay]").length > 0) {
        let windowHeight = window.innerHeight,
            videoEl = document.querySelectorAll("video[autoplay]");

        for (let i = 0; i < videoEl.length; i++) {
          let thisVideoEl = videoEl[i],
              videoHeight = thisVideoEl.clientHeight,
              videoClientRect = thisVideoEl.getBoundingClientRect().top;

          if (videoClientRect <= windowHeight - videoHeight * 0.5 && videoClientRect >= 0 - videoHeight * 0.5) {
            thisVideoEl.play();
          } else {
            thisVideoEl.pause();
          }
        }
      }
    }