One-Liners JavaScript code that you should know
Today we will share the 7 useful One-Liners JavaScript code that you should know.
- How To Encode and Decode Strings with Base64 in JavaScript
- How to get day name from Date in JavaScript
- Restrict or Disable browser back button using JavaScript
- How to get first N elements of an array in JavaScript
- Get current location in JavaScript using Geolocation API
- 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.
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 to Clipboard in JavaScript
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.
const reverseStr = str => str.split('').reverse().join('');
reverseStr(“Code Premix”); // Output: ximerP edoC
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.
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 in JavaScript
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: Random Password Generator using JavaScript
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.
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..!!