🪄

Code Snippets

 
 
Get the selected text
JavaScript
const getSelectedText = () => window.getSelection().toString();

getSelectedText(); // 'Lorem ipsum'
Copy text to clipboard with JavaScript
JavaScript
const copyToClipboard = (str) => {
  if (navigator && navigator.clipboard && navigator.clipboard.writeText)
    return navigator.clipboard.writeText(str);
  return console.log("The Clipboard API is not available.");
};
JavaScript to test if WebAssembly is supported
JavaScript
function isWebAssemblySupported() {
  try {
    if (typeof WebAssembly === "object") {
      const module = new WebAssembly.Module(
        new Uint8Array([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00])
      );
      if (module instanceof WebAssembly.Module) {
        const moduleInstance = new WebAssembly.Instance(module);
        return moduleInstance instanceof WebAssembly.Instance;
      }
    }
  } catch (err) {}
  return false;
}

console.log(
  isWebAssemblySupported()
    ? "WebAssembly is supported"
    : "WebAssembly is not supported"
);

if (typeof WebAssembly.instantiateStreaming === "function") {
  console.log("You can use the WebAssembly.instantiateStreaming function");
} else {
  console.log(
    "The WebAssembly.instantiateStreaming function is not available. You need to use WebAssembly.instantiate instead."
  );
}
Save Canvas to Image
JavaScript
// convert canvas to base64 URL
var url = canvas.toDataURL("image/png");
Img.src = url;
// Convert base64 to file object
var arr = url.split(",");
var mime = arr[0].match(/:(.*?);/)[1]; // get file type
var bstr = atob(arr[1]); // base64 decode
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n--) {
  u8arr[n] = bstr.charCodeAt(n);
}
// file content、file name、file type
var file = new File([u8arr], "filename", { type: mime });
// download file through a tag
var aDom = document.createElement("a");
aDom.download = file.name; // set file name
let href = URL.createObjectURL(file);
// convert file object to UTF-16 string
aDom.href = href; // put it into href
document.body.appendChild(aDom);
aDom.click();
document.body.removeChild(aDom);
URL.revokeObjectURL(href); // realse file hook
Smooth-scroll element into view
JavaScript
const smoothScroll = (element) =>
  document.querySelector(element).scrollIntoView({
    behavior: "smooth",
  });

smoothScroll("#fooBar"); // scrolls smoothly to the element with the id fooBar
smoothScroll(".fooBar");
// scrolls smoothly to the first element with a class of fooBar
Handle click outside the element
JavaScript
const onClickOutside = (element, callback) => {
  document.addEventListener("click", (e) => {
    if (!element.contains(e.target)) callback();
  });
};

onClickOutside("#my-element", () => console.log("Hello"));
// Will log 'Hello' whenever the user clicks outside of #my-element
Toggle full-screen mode
JavaScript
const fullscreen = (mode = true, el = "body") =>
  mode
    ? document.querySelector(el).requestFullscreen()
    : document.exitFullscreen();

fullscreen(); // Opens `body` in fullscreen mode
fullscreen(false); // Exits fullscreen mode
Check the preferred language of the current user
JavaScript
const detectLanguage = (defaultLang = "en-US") =>
  navigator.language ||
  (Array.isArray(navigator.languages) && navigator.languages[0]) ||
  defaultLang;

detectLanguage(); // 'nl-NL'
Check the preferred color scheme of the user
JavaScript
const prefersDarkColorScheme = () =>
  window &&
  window.matchMedia &&
  window.matchMedia("(prefers-color-scheme: dark)").matches;

prefersDarkColorScheme(); // true
Check if the device supports touch events
JavaScript
const supportsTouchEvents = () => window && "ontouchstart" in window;

supportsTouchEvents(); // true
Check if a element is within view
Rust
const checkIsElementInViewport = (el) => {
    const rect = el.getBoundingClientRect();
    return (
      (rect.top <= 0 && rect.bottom >= 0) ||
      (rect.bottom >=
        (window.innerHeight || document.documentElement.clientHeight) &&
        rect.top <=
          (window.innerHeight || document.documentElement.clientHeight)) ||
      (rect.top >= 0 &&
        rect.bottom <=
          (window.innerHeight || document.documentElement.clientHeight))
    );
  }
Detecting whether an element is partially or full visible
JavaScript
function isFullyVisible(el) {
  var elementBoundary = el.getBoundingClientRect();
  var top = elementBoundary.top;
  var bottom = elementBoundary.bottom;
  return top >= 0 && bottom <= window.innerHeight;
}
Queries whether or not the document is allowed to use camera API by the Permissions Policy
TypeScript
// First, get the Feature Policy object
const featurePolicy = document.featurePolicy;

// Then query feature for specific
const allowed = featurePolicy.allowsFeature("camera");

if (allowed) {
  console.log("FP allows camera.");
} else {
  console.log("FP does not allows camera.");
}
When a user has left the page
JavaScript
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "visible") {
    // page is visible
  } else {
    // page is hidden
  }
});
Keep a page’s state synced across different tabs and windows to enhance user experience or for security reasons
JavaScript
const broadcast = new BroadcastChannel("new_channel");
broadcast.onmessage = ({ data, origin }) => {
  console.log(`${origin} says ${data}`);
};

broadcast.postMessage("Example message");
Remove all the events bind to a button(intrinsic listeners are preserved)
JavaScript
button.replaceWith(button.cloneNode(true));
Remove all the events using abortController
JavaScript
const button = document.getElementById("button");
const controller = new AbortController();
const { signal } = controller;

button.addEventListener("click", () => console.log("clicked!"), { signal });
window.addEventListener("resize", () => console.log("resized!"), { signal });
document.addEventListener("keyup", () => console.log("pressed!"), { signal });

// Remove all listeners at once:
controller.abort();
Apply tailwind styles by CSS selectors
CSS
@tailwind components;
@tailwind utilities;
@layer components {
  #__next {
    @apply h-full bg-red-500;
  }
  html,
  body {
    @apply h-full;
  }
}
Check JS value types
JavaScript
Object.prototype.toString.call(2); // "[object Number]"
Object.prototype.toString.call(""); // "[object String]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(Math); // "[object Math]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(function () {}); // "[object Function]"
Generate a random Id
CSS
Math.floor(Math.random() * Date.now())
Get the current scroll position
JavaScript
// Get the current horizontal scroll position
var scrollLeft = window.scrollX || window.pageXOffset || document.documentElement.scrollLeft;

// Get the current vertical scroll position
var scrollTop = window.scrollY || window.pageYOffset || document.documentElement.scrollTop;