• Post category:JavaScript
  • Reading time:5 mins read

Today we will share the 7 useful One-Liners JavaScript code that you should know.

JavaScript One-Liners Code

  1. Check if the current user has touch events supported
  2. Copy text to clipboard
  3. Reverse a string
  4. Check if the current tab is in view/focus
  5. Scroll to top of the page
  6. Generate a random string
  7. 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..!!

Leave a Reply