Home >Web Front-end >CSS Tutorial >Front-End Code Snippets Worth Checking Out

Front-End Code Snippets Worth Checking Out

Patricia Arquette
Patricia ArquetteOriginal
2025-01-26 10:06:10845browse

Front-End Code Snippets Worth Checking Out

In daily development, we will accumulate some commonly used code snippets, which can be directly copied and pasted into various projects for use, which is very convenient. If you have taken over other people's projects, you may notice that the same tools and methods exist in some projects. These are common code snippets accumulated by previous developers.

Now that the front-end community has matured, excellent libraries such as lodash and dayjs can meet our needs for processing arrays, dates, etc. This article will not repeat these common fragments.

  1. Detect click outside element

When hiding the pop-up box or collapsing the drop-down menu, use the contains method instead of checking layer by layer.

<code class="language-javascript">// 代码示例 (此处省略)</code>
  1. Quickly open the official website

To view the homepage or code repository of a third-party library, you can use these npm commands:

Open homepage

npm home PACKAGE_NAME

For example, for React

npm home react

Open the code repository

npm repo PACKAGE_NAME

For example, for React

npm repo react

  1. One-time event listener

In addition to removing the listener in the event function, you can also use the once parameter.

<code class="language-javascript">// 代码示例 (此处省略)</code>
  1. Format seconds as HH:mm:ss

In scenarios such as displaying audio/video duration, you can format seconds like this:

<code class="language-javascript">const formatSeconds = (s) =>
  [parseInt(s / 60 / 60), parseInt((s / 60) % 60), parseInt(s % 60)].join(":").replace(/\b(\d)\b/g, "0");
const seconds = 3661;
console.log(formatSeconds(seconds));</code>

To display relative time like "just now", you can try the timeago.js library.

  1. Convert URL parameters to objects

No need to use query-string library, use URLSearchParams API directly:

<code class="language-javascript">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));</code>
  1. Open new tab

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

<code class="language-html"><a href="https://example.com" rel="noopener noreferrer" target="_blank">打开</a></code>
<code class="language-javascript">function openNewTab() {
  window.open("https://example.com", "newTab", "noopener,noreferrer");
}</code>
  1. Show uploaded images

Use the readAsDataURL method of the FileReader API to display the uploaded image.

<code class="language-javascript">// 代码示例 (此处省略)</code>
  1. File download

Using the download attribute of the tag can trigger a download, but it has some limitations.

<code class="language-html"><a download="" href="https://www.php.cn/link/8b89afaf8e00e0a46ea4d76ac473b1a2">下载</a></code>
<code class="language-javascript">function download(url) {
  const link = document.createElement("a");
  link.download = "file name";
  link.href = url;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}</code>

You can also set response headers on the server side, or on the browser side using Blob and createObjectURL.

<code class="language-javascript">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);</code>
  1. Cached results

Cache function results for complex calculations.

<code class="language-javascript">const memoize = (fn) =>
  (
    (cache = Object.create(null)) =>
    (arg) =>
      cache[arg] || (cache[arg] = fn(arg))
  )();
// 代码示例 (此处省略)</code>
  1. Multi-line ellipsis

Use CSS to truncate text to ellipses, on single or multiple lines.

<code class="language-css">.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;
}</code>
  1. Select the last few elements

Use CSS selectors to target specific elements.

<code class="language-css">li:nth-child(-n + 3) {
  text-decoration: underline;
}
// 代码示例 (此处省略)</code>
  1. Scroll bar style

Customize scroll bar styles using CSS or third-party libraries like better-scroll.

<code class="language-javascript">// 代码示例 (此处省略)</code>
  1. Percentage Calculation-Maximum Remainder Method

Use the maximum remainder method to ensure that the percentages sum to 1.

<code class="language-javascript">// 代码示例 (此处省略)</code>
  1. Limit concurrency

Limit the number of concurrent requests when making a large number of requests.

<code class="language-javascript">const formatSeconds = (s) =>
  [parseInt(s / 60 / 60), parseInt((s / 60) % 60), parseInt(s % 60)].join(":").replace(/\b(\d)\b/g, "0");
const seconds = 3661;
console.log(formatSeconds(seconds));</code>
  1. UUID generation

Use this code to generate a unique identifier.

<code class="language-javascript">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));</code>
  1. Open modal and prevent body from scrolling

Prevent body scrolling when opening the modal.

<code class="language-html"><a href="https://example.com" rel="noopener noreferrer" target="_blank">打开</a></code>

Original link: https://www.php.cn/link/d9d838896ca0a5e16e7efa2439943fbd

The above is the detailed content of Front-End Code Snippets Worth Checking Out. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn