7 JavaScript One-Liners that you should know
Today we will share the 7 useful JavaScript One-Liners that you should know.
Checkout more articles on JavaScript
7 JavaScript One-Liners
- Check if the current user has touch events supported
- Copy text to clipboard
- Reverse a string
- Check if the current tab is in view/focus
- Scroll to top of the page
- Generate a random string
- Check if the current user is on an Apple device
1. Check if the current user has touch events supported
Use the following function to check the touch support.
1 2 3 4 | const isTouchSupported = () => ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch); isTouchSupported(); // Output: true/false // It will return true if touch events are supported, false if not. |
2. Copy text to clipboard
Use the navigator
to copy text to the clipboard.
Suggested article: How to copy text to the clipboard using JavaScript
1 | const copyTextToClipboard = async text => await navigator.clipboard.writeText(text); |
3. Reverse a string
Use the single line of code using split()
, reverse()
& join()
methods to reverse a string.
1 2 3 | const reverseStr = str => str.split('').reverse().join(''); reverseStr(“Clue Mediator”); // Output: rotaideM eulC |
4. Check if the current tab is in view/focus
We can check if the current tab is in view/focus by using the document.hidden
property.
1 2 3 4 | const isBrowserTabInView = () => document.hidden; isBrowserTabInView(); // Output: true/false // It’s returns true or false depending on if the tab is in view/focus. |
5. Scroll to top of the page
Use the window.scrollTo()
method to change the scroll position.
Suggested article: Animated sticky header on scroll using JavaScript
1 2 3 4 | const scrollToTop = () => window.scrollTo(0, 0); scrollToTop(); // It will scroll the browser to the top of the page. |
6. Generate a random string
Using the Math.random()
, we can generate a random string.
Suggested article: Generate a random password using JavaScript
1 2 3 | const getRandomStr = () => Math.random().toString(36).slice(2); getRandomStr(); // Output: zgtgfqialz |
7. Check if the current user is on an Apple device
We can use navigator.platform
to check if the current user is on an Apple device.
1 2 3 4 | const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform); console.log(isAppleDevice); // Output: true/false // It will return true if user is on an Apple device |
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂