js-one-liners js-one-liners

by Anonymous

Detect Dark mode

const isDarkmode =
window.matchMedia && window.matchMedia("(prefers-color-scheme:dark)").match;

With this you can check if the user is using dark mode (and then you can update some functionality according to the dark mode)

Check if an element is focused

const el = document.querySelector("text-input");
const isFocus = el == document.activeElement;

/*
isFocus = true [if el has the focus]
isFocus = false [if el doesn't have the focus]
*/

to detect if the element has the foucs in javascript, we can use read-only property activeElement of the document object.

Generate Random string

const generateRandomString = Math.random().toString(36).slice(2);
console.log(generateRandomString);

/*The output string will be - 8v43x19vso5 (Note it will be random)*/

if you need a temporary unique id for something this will help you to generate a random string for you.

Get the domain name from an email address

let email = "abc@gmail.com";
let getDomain = email.substring(email.indexOf("@") + 1);
console.log(getDomain);

/* The output string will be - gmail.com */

we can use the substring method to get the domain name from an email address.