Những dòng code được sử dụng hữu ích khi lập trình với JS

MVT
Đang cập nhật

1. How to hide all elements in the component in javascipt?

const hide = (...el) => [...el].forEach(e => e.style.display = "none")
//example
hide(document.querySelectorAll("p"))

2. Check if the element contains a certain class or not?

const hasClass = (el, className) => el.classList.contains(className); //true or false
//example
hasClass(document.querySelector("a.link-item", "active");

3. Toggle Class

const toggleClass = (el, className) => el.classList.toggle(className);
//example
toggleClass(document.querySelector("div.modal","open"));

4. How to get the position of current page's scroll ?

const getScrollPosition = (el = window) => ({
  x : el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
  y : el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
})
//example
getScrollPosition()

5. How to make a smooth scroll to top page ?

const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if(c > 0 ){
    window.requestAnimationFrame(scrollToTop)
    window.scrollTo(0, c - c/8);
  }

6. How to check if the parent element contains the child element ?

const checkHasChild = (parentEl, childEl) => parentEl !== childEl && parentEl.contains(childEl);

//example
elementContains(document.querySelector('head'), document.querySelector('title')); 
// true
elementContains(document.querySelector('body'), document.querySelector('body'));
// false

7. How to check if specified element is visible in viewport?

const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
  const {top, left, bottom, right} = el.getBoundingClientRect();
  const {innerHeight, innerWidth} = window; 
  return partiallyVisible ? 
    ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth &&) && (right > 0 && right < innerWidth)) :
   top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
}

8. How to find all images in an element ?

 const getImages = (el, includeDuplicates = false) => {
   const images = [...el.getElementsByTagName("img")].map((img) => img.getAttribute("src"));
   return includeDuplicates ? images : [...new Set(images)];
 };

getImages(document, true)
getImages(document)

9. How to know current device is mobile device or desktop/ laptop?

const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? "Mobile" : "Desktop";

//example
detectDeviceType() // Desktop

10. How to get current URL?

const currentUrl = () => window.location.href ; 
currentUrl()

11. How to create an Object containing the parameters of the current URL ?

const getURLParameters = url => (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
);

//example
getURLParameters("https://mvthang-official.netlify.app/archieves?year=2021&month=2") // {year: "2021", month: "2"}

12.How to encode a set of form elements as an object?

cosnt formToObject = form => Array.from(new FormData(form)).reduce((acc, [key,value]) => ({...acc, [key] : value}), {} )

//example
formToObject(document.getElementById("form"))
//{name: "John Doe", email: "john_doe@email.com", position: "Developer"}

13. How to retrieve a set of properties specified by a given selector from an object?

const get = (from, ...selectors) =>
  [...selectors].map(s =>
    s
      .replace(/\[([^\[\]]*)\]/g, '.$1.')
      .split('.')
      .filter(t => t !== '')
      .reduce((prev, cur) => prev && prev[cur], from)
  );
const obj = { selector: { to: { val: "John Doe" } }, target: [1, 2, { a: 'test' }] };

// Example
get(obj, 'selector.to.val', 'target[0]', 'target[2].a'); // ['John Doe', 1, 'test']

14. How to call a function after a period of time (in milliseconds)?

const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);
delay(function(text){
  alert(text);
}, 1000, "Call me")

15. How to trigger a specific event on a certain element, optionally passing custom data?

//Case 1 : without injecting data

//example
<body>
<button id="btn" onClick="alert('Call Me')">Click me</button>
</body>
<script>
const triggerEventWithoutData = (el, eventType) => el.dispatchEvent(eventType);
triggerEventWithoutData(document.getElementById("btn"), "click")//Call Me
</script>

//Case 2: Inject data

<body>
<button id="btn">Click me</button>
</body>
<script>
   const data = {
      username : "John Doe",
      email : "johndoe@email.com",
      country : "usa"
    }
const triggerEventWithData = (el, eventType, data) => el.dispatchEvent(new CustomEvent(eventType, data))
 triggerEvent(document.getElementById("btn"),"click", console.log(data)) // {username: "John Doe", email: "johndoe@email.com", country: "usa"}

16. How to remove an event listener from an element?

const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts);
const fn = () => console.log("!");
document.body.addEventListener("click", fn);
off(document.body, "click", fn);

17. How to get a readable format of a given millisecond number?

const formatDuration = ms => {
  if (ms < 0) ms = -ms;
  const time = {
    day: Math.floor(ms / 86400000),
    hour: Math.floor(ms / 3600000) % 24,
    minute: Math.floor(ms / 60000) % 60,
    second: Math.floor(ms / 1000) % 60,
    millisecond: Math.floor(ms) % 1000
  };
  return Object.entries(time)
    .filter(val => val[1] !== 0)
    .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
    .join(', ');
};

// Example
formatDuration(1001); // '1 second, 1 millisecond'
formatDuration(34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
formatDuration(Date.now()) //18665 days, 9 hours, 18 minutes, 38 seconds, 709 milliseconds

18. How to calculate the number of days between a given date?

const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>  (dateFinal - dateInitial) / (1000 * 3600 * 24);

// Example
getDaysDiffBetweenDates(new Date('2021-02-01'), new Date('2021-05-22')); //110

19. How to request to URL with GET method ?

const httpGet = (url, callback, err = console.error) => {
  const request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send();
};
//Example
httpGet(
  'https://www.w3schools.com/',
  console.log
);

20. How to request to URL with POST method ?

const httpPost = (url, data, callback, err = console.error) => {
  const request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send(data);
};

const newPost = {
  userId: 1,
  id: 1,
  title: 'new Title',
  body: 'new Content body'
};
const data = JSON.stringify(newPost);
httpPost(
  'http://localhost:5000/post',
  data,
  console.log
); 

// Logs: {"userId": 1, "id": 1, "title": "new Title", "body": "new Content body"}

21. How to create a counter with specified range, step, and duration for specified selector?

const counter = (selector, start, end, step = 1, duration = 2000) => {
  let current = start,
    _step = (end - start) * step < 0 ? -step : step,
    timer = setInterval(() => {
      current += _step;
      document.querySelector(selector).innerHTML = current;
      if (current >= end) document.querySelector(selector).innerHTML = end;
      if (current >= end) clearInterval(timer);
    }, Math.abs(Math.floor(duration / (end - start))));
  return timer;
};

// Ví dụ
counter('#my-id', 1, 1000, 5, 2000); // Create the counter with 2 seconds to "#my-id"

22. How to copy strings to clipboard ?

const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly', '');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  const selected =
    document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
  if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
  }
};

// Ví dụ
copyToClipboard('Example String'); //This "Example String" has been copied to clipboard

23. How to know if a page's browser tab is in focus?

const isBrowserTabFocused = () => !document.hidden;

// Example
isBrowserTabFocused(); // true

24. How to create a folder if it doesn't exist ?

const fs = require("fs")
const createDirIfNotExists = dir => !fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined;
createDirIfNotExists('test');

Bài viết có liên quan