Hello Folks 👋
What's up friends, this is SnowBit here. I am a young passionate and self-taught frontend web developer and have an intention to become a successful developer. I love building web applications with different technologies.
Today, I am here with some good JS one-liners for you to look like a pro that might help you in your next project. Let's go 🚀
Toggle Boolean
Toggling boolean, turning true to false or vice versa.
const toggleBool = (val) => (val = !val)
toggleBool(false) //true
Random Boolean
Generate a random boolean.
const randomBool = () => Math.random() >= 0.5;
randomBool() //true
Scroll to Top
Scroll to the top of the page.
const scrollToTop = () => window.scroll(0,0)
Detect dark mode
Returns true when dark mode is enabled.
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
Get user-selected text
Returns the selected text.
const getSelectedText = () => window.getSelection().toString();
Difference between two dates
const dif = (d1, d2) => Math.ceil(Math.abs(d1.getTime() - d2.getTime()) / 86400000)
dif(new Date("2006-02-24"), new Date ("2022-02-24"))
Random HEX color
const hexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
This was it for this article, I hope this article helped you. Feel free to share more in the comments below. Thank you for reading!
I am on Twitter @codewithsnowbit. Give it a follow.
Comments (0)