16 Front-End Code Snippets Worth Checking Out

16-front-end-code-snippets-worth-checking-out

In daily development, we all have some commonly used code snippets. They can be directly copied and used in various projects, which is very convenient. If you’ve taken over someone else’s project, you may notice some identical utility-class methods across projects. These are the commonly used code snippets of previous developers.

Now, the front-end community is well-developed. There are many great libraries like lodash, dayjs, etc., which can meet our needs for handling arrays, dates, etc. This article won’t repeat those common snippets.

1. Detect Clicks Outside an Element

When hiding pop-ups or collapsing dropdowns, use the contains method instead of layer-by-layer checking.

 id="ele">Content

2. Quickly Open the Official Website

To view a third-party library’s homepage or code repository, use these npm commands:

# Open the homepage
npm home PACKAGE_NAME
# E.g., for React
npm home react

# Open the code repository
npm repo PACKAGE_NAME
# E.g., for React
npm repo react

3. One-Time Event Listener

Besides removing the listener in the event function, you can use the once parameter.

 id="btn">Click

4. Format Seconds into HH:mm:ss

For scenarios like showing audio/video duration, format seconds like this:

const formatSeconds = (s) =>
  [parseInt(s / 60 / 60), parseInt((s / 60) % 60), parseInt(s % 60)].join(":").replace(/b(d)b/g, "0$1");
const seconds = 3661;
console.log(formatSeconds(seconds));

To show relative time like “Just now”, try the timeago.js library.

5. Convert URL Parameters to an Object

Instead of using the query-string library, use the URLSearchParams API.

const getUrlParams = (query) =>
  Array.from(new URLSearchParams(query)).reduce(
    (p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),
    {}
  );
const query = "?a=1&b=2&a=3";
console.log(getUrlParams(query));

6. Open a New Tab

When opening an external link, set rel="noopener noreferrer" to avoid security risks.

 href="https://example.com" target="_blank" rel="noopener noreferrer">Open

 onclick="openNewTab()">Open with window.open

7. Display Uploaded Images

Use the FileReader API’s readAsDataURL method to show uploaded images.

 type="file" id="uploaded-file" />
 id="result">

8. File Download

Using the tag’s download attribute can trigger a download, but it has limitations.

 href="https://dev.to/path/to/file" download>Download

 onclick="download('https://example.com/file')">Download with JS

You can also set the response header on the server or use Blob and createObjectURL in the browser.

const data = JSON.stringify({ message: "Hello" });
const blob = new Blob([data], { type: "application/json" });
const url = window.URL.createObjectURL(blob);
download(url);
window.URL.revokeObjectURL(url);

9. Cache Results

Cache function results for complex calculations.

const memoize = (fn) =>
  (
    (cache = Object.create(null)) =>
    (arg) =>
      cache[arg] || (cache[arg] = fn(arg))
  )();
const complexCalculation = (num) => {
  let sum = 0;
  for (let i = 1; i <= num; i++) {
    sum += i;
  }
  return sum;
};
const memoizedCalculation = memoize(complexCalculation);
console.log(memoizedCalculation(10));
console.log(memoizedCalculation(10));

10. Multi-Line Ellipsis

Use CSS to truncate text with ellipses for single or multi-line.

.truncate-single {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.truncate-multi {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
 class="truncate-single">Long single-line text...
class="truncate-multi">Long multi-line text... Long multi-line text...

11. Select the Last Few Elements

Use CSS selectors to target specific elements.

li:nth-child(-n + 3) {
  text-decoration: underline;
}
li:nth-child(n + 2):nth-child(-n + 5) {
  color: #2563eb;
}
li:nth-last-child(-n + 2) {
  text-decoration-line: line-through;
}
  • Item 1
  • Item 2
  • Item 3
  • Item 4
  • Item 5

12. Scrollbar Styles

Customize scrollbar styles with CSS or a third-party library like better-scroll.

::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}
::-webkit-scrollbar-track {
  border-radius: 10px;
  background-color: #fafafa;
}
::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: rgb(191, 191, 191);
}
body {
  scrollbar-width: thin;
  scrollbar-color: #718096 #edf2f7;
}

13. Percentage Calculation-Largest Remainder Method

Use the largest remainder method to ensure percentage sums equal 1.

function getPercentWithPrecision(valueList, precision) {
  const digits = Math.pow(10, precision);
  const sum = valueList.reduce((total, cur) => total + cur, 0);
  const votesPerQuota = valueList.map((val) => (val / sum) * 100 * digits);
  const seats = votesPerQuota.map((val) => Math.floor(val));
  const remainder = votesPerQuota.map((val) => val - Math.floor(val));
  const totalSeats = 100 * digits;
  let currentSeats = votesPerQuota.reduce((total, cur) => total + Math.floor(cur), 0);
  while (totalSeats - currentSeats > 0) {
    let maxIdx = -1;
    let maxValue = Number.NEGATIVE_INFINITY;
    for (var i = 0; i < remainder.length; i++) {
      if (maxValue < remainder[i]) {
        maxValue = remainder[i];
        maxIdx = i;
      }
    }
    seats[maxIdx]++;
    remainder[maxIdx] = 0;
    currentSeats++;
  }
  return seats.map((val) => `${(val / totalSeats) * 100}%`);
}
const values = [56, 12, 48, 56];
console.log(getPercentWithPrecision(values, 2));

14. Limit Concurrency

Limit the number of concurrent requests when making many requests.

async function asyncPool(poolLimit, iterable, iteratorFn) {
  const ret = [];
  const executing = new Set();
  for (const item of iterable) {
    const p = Promise.resolve().then(() => iteratorFn(item, iterable));
    ret.push(p);
    executing.add(p);
    const clean = () => executing.delete(p);
    p.then(clean).catch(clean);
    if (executing.size >= poolLimit) {
      await Promise.race(executing);
    }
  }
  return Promise.all(ret);
}
const timeout = (i) => new Promise((resolve) => setTimeout(() => resolve(i), i));
asyncPool(2, [1000, 5000, 3000, 2000], timeout).then((results) => {
  console.log(results);
});

15. UUID Generation

Generate unique identifiers with this code.

const uuid = (a) =>
  a
    ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16)
    : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid);
console.log(uuid());

16. Open Modal and Prevent Body Scroll

Prevent the body from scrolling when opening a modal.

 onclick="openModal()">Open Modal
 id="modal" style="display: none;">Modal Content

Original article link: https://en.kelen.cc/posts/16-front-end-code-snippets-worth-checking-out

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
i-couldn’t-find-a-job,-so-i-made-a-saas-my-accident

I couldn’t find a job, so I made a SaaS my accident

Next Post
how-i-made-toggle-transition-to--element

How I made toggle transition to
element

Related Posts