Guest User

Untitled

a guest
Apr 23rd, 2020
447
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const resetAnimation = (item) => {
  2.     if (item && item.style) {
  3.         item.style.animation = "none";
  4.         item.offsetHeight;
  5.         item.style.animation = null;
  6.     }
  7. };
  8.  
  9. const formatDateForm = (date) => {
  10.     // Format to Tháng ngày, năm
  11.     const monthName = [
  12.         "Một",
  13.         "Hai",
  14.         "Ba",
  15.         "Bốn",
  16.         "Năm",
  17.         "Sáu",
  18.         "Bảy",
  19.         "Tám",
  20.         "Chín",
  21.         "Mười",
  22.         "Mười một",
  23.         "Mười hai",
  24.     ];
  25.  
  26.     const dateData = date.split("/");
  27.     const formattedDateData = dateData.map((e, index) => {
  28.         if (index !== 1 && e.length < 2) e = `0${e}`;
  29.  
  30.         return e;
  31.     });
  32.  
  33.     return `Tháng ${monthName[formattedDateData[1]]} ${formattedDateData[0]}, ${
  34.         formattedDateData[2]
  35.     }`;
  36. };
  37.  
  38. const dateConverter = (date) => {
  39.     const d = new Date(date);
  40.     const convertedDate = `${d.getDate()}/${d.getMonth()}/${d.getFullYear()}`;
  41.     return formatDateForm(convertedDate);
  42. };
  43.  
  44. // hide all elements specified
  45. const hideAllSpecifiedElements = (...el) =>
  46.     [...el].forEach((e) => (e.style.display = "none"));
  47.  
  48. // get the scroll position of the current page
  49. const getScrollPosition = (el = window) => ({
  50.     x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
  51.     y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop,
  52. });
  53.  
  54. // Ví dụ:
  55. getScrollPosition(); // {x: 0, y: 20}
  56.  
  57. // Scroll to top smoothly
  58. const scrollToTop = () => {
  59.     const c = document.documentElement.scrollTop || document.body.scrollTop;
  60.     if (c > 0) {
  61.         window.requestAnimationFrame(scrollToTop);
  62.         window.scrollTo(0, c - c / 8);
  63.     }
  64. };
  65.  
  66. // Check if the elements specified is visible in the viewport
  67. const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
  68.     const { top, left, bottom, right } = el.getBoundingClientRect();
  69.     const { innerHeight, innerWidth } = window;
  70.     return partiallyVisible
  71.         ? ((top > 0 && top < innerHeight) ||
  72.                 (bottom > 0 && bottom < innerHeight)) &&
  73.                 ((left > 0 && left < innerWidth) ||
  74.                     (right > 0 && right < innerWidth))
  75.         : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
  76. };
  77.  
  78. // e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}
  79. elementIsVisibleInViewport(el); // false - (not fully visible)
  80. elementIsVisibleInViewport(el, true); // true - (partially visible)
  81.  
  82. // Fetch all images within an element
  83. const getImages = (el, includeDuplicates = false) => {
  84.     const images = [...el.getElementsByTagName("img")].map((img) =>
  85.         img.getAttribute("src")
  86.     );
  87.     return includeDuplicates ? images : [...new Set(images)];
  88. };
  89.  
  90. // Figure out if the device is a mobile device or a desktop/laptop?
  91. const detectDeviceType = () =>
  92.     /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
  93.         navigator.userAgent
  94.     )
  95.         ? "Mobile"
  96.         : "Desktop";
  97.  
  98. // Get URL Params
  99. const getURLParameters = (url) =>
  100.     [...new URL(url).searchParams].reduce(
  101.         (obj, [key, value]) => (
  102.             (obj[key] = key in obj ? [].concat(obj[key], value) : value), obj
  103.         ),
  104.         Object.create(null)
  105.     );
  106.  
  107. // Encode a set of form element as an object?
  108. const formToObject = (form) =>
  109.     Array.from(new FormData(form)).reduce(
  110.         (acc, [key, value]) => ({
  111.             ...acc,
  112.             [key]: value,
  113.         }),
  114.         {}
  115.     );
  116.  
  117. formToObject(document.querySelector("#form")); // { email: 'test@email.com', name: 'Test Name' }
  118.  
  119. // Remove event listener from an element
  120. const offEventListener = (element, event, func, opts = false) =>
  121.     element.removeEventListener(event, func, opts);
  122.  
  123. // Format the given number of milliseconds
  124. const formatTime = (ms) => {
  125.     if (ms < 0) ms = -ms;
  126.     const time = {
  127.         day: Math.floor(ms / 86400000),
  128.         hour: Math.floor(ms / 3600000) % 24,
  129.         minute: Math.floor(ms / 60000) % 60,
  130.         second: Math.floor(ms / 1000) % 60,
  131.         millisecond: Math.floor(ms) % 1000,
  132.     };
  133.     return Object.entries(time)
  134.         .filter((val) => val[1] !== 0)
  135.         .map(([key, val]) => `${val} ${key}${val !== 1 ? "s" : ""}`)
  136.         .join(", ");
  137. };
  138.  
  139. // Ví dụ:
  140. // formatTime(34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
  141.  
  142. // Get the difference between two dates
  143. const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
  144.     (dateFinal - dateInitial) / (1000 * 3600 * 24);
  145.  
  146. // Ví dụ:
  147. // getDaysDiffBetweenDates(new Date("2020-04-20"), new Date("2020-04-22")) // 2
  148.  
  149. // Remove duplicate object in array
  150. const removeDuplicateObjectInArray = (list) =>
  151.     list.filter((item, index) => {
  152.         const _item = JSON.stringify(item);
  153.         return (
  154.             index ===
  155.             list.findIndex((obj) => {
  156.                 return JSON.stringify(obj) === _item;
  157.             })
  158.         );
  159.     });
  160.  
  161. // Copy to clipBoard
  162. const copyToClipboard = (str) => {
  163.     const el = document.createElement("textarea");
  164.     el.value = str;
  165.     el.setAttribute("readonly", "");
  166.     el.style.position = "absolute";
  167.     el.style.left = "-99999px";
  168.     document.body.appendChild(el);
  169.     const selected =
  170.         document.getSelection().rangeCount > 0
  171.             ? document.getSelection().getRangeAt(0)
  172.             : false;
  173.     el.select();
  174.     document.execCommand("copy");
  175.     document.body.removeChild(el);
  176.     if (selected) {
  177.         document.getSelection().removeAllRanges();
  178.         document.getSelection().addRange(selected);
  179.     }
  180. };
  181.  
  182. const toggleClass = (el, className) =>
  183.     el && el.classList && el.classList.toggle(className);
  184.  
  185. toggleClass(document.querySelector("p.dark"), "dark"); // This will remove class dark from p element
  186.  
  187. const validateEmail = (email) => {
  188.     const re = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/;
  189.     return re.test(String(email).toLowerCase());
  190. };
  191.  
  192. const smoothScroll = (element) =>
  193.     document.querySelector(element).scrollIntoView({ behavior: "smooth" });
  194.  
  195. smoothScroll("#container"); // scrolls smoothly to the element with the id container
  196.  
  197. const removeNonASCII = (str) => str.replace(/[^\x20-\x7E]/g, "");
  198.  
  199. const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];
  200.  
  201. // Example
  202. // getStyle(document.querySelector("p"), "font-size"); // '16px'
  203.  
  204. const encodeStr = (encodeStr) => {
  205.     try {
  206.         encodeStr = encodeStr.toString().toLowerCase().trim();
  207.         encodeStr = encodeStr.replace(
  208.             /à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g,
  209.             "a"
  210.         );
  211.         encodeStr = encodeStr.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ.+/g, "e");
  212.         encodeStr = encodeStr.replace(/ì|í|ị|ỉ|ĩ/g, "i");
  213.         encodeStr = encodeStr.replace(
  214.             /ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ.+/g,
  215.             "o"
  216.         );
  217.         encodeStr = encodeStr.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u");
  218.         encodeStr = encodeStr.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y");
  219.         encodeStr = encodeStr.replace(/đ/g, "d");
  220.  
  221.         encodeStr = encodeStr.replace(/[^\w\s]/gi, "");
  222.         encodeStr = encodeStr.replace(/\(|\)|\:/g, "");
  223.         encodeStr = encodeStr.replace(/\//g, "-");
  224.         encodeStr = encodeStr.replace(/^\-+|\-+$/g, "");
  225.         encodeStr = encodeStr.replace(/ /g, "-");
  226.         encodeStr = encodeStr.replace(/-+-/g, "-");
  227.  
  228.         return encodeStr;
  229.     } catch (err) {
  230.         return "";
  231.     }
  232. };
  233.  
  234. encodeStr("Những javascript snippet code xịn xò mà bạn nên biết"); // nhung-javascript-snippet-code-xin-xo-ma-ban-nen-biet
RAW Paste Data