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

Front-End Code Snippets Worth Checking Out

Patricia Arquette
Release: 2025-01-26 10:06:10
Original
885 people have browsed it

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.

// 代码示例 (此处省略)
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  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.

// 代码示例 (此处省略)
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  1. Format seconds as HH:mm:ss

In scenarios such as displaying audio/video duration, you can 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");
const seconds = 3661;
console.log(formatSeconds(seconds));
Copy after login
Copy after login

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:

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));
Copy after login
Copy after login
  1. Open new tab

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

<a href="https://example.com" rel="noopener noreferrer" target="_blank">打开</a>
Copy after login
Copy after login
function openNewTab() {
  window.open("https://example.com", "newTab", "noopener,noreferrer");
}
Copy after login
  1. Show uploaded images

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

// 代码示例 (此处省略)
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  1. File download

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

<a download="" href="https://www.php.cn/link/8b89afaf8e00e0a46ea4d76ac473b1a2">下载</a>
Copy after login
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);
}
Copy after login

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

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);
Copy after login
  1. Cached results

Cache function results for complex calculations.

const memoize = (fn) =>
  (
    (cache = Object.create(null)) =>
    (arg) =>
      cache[arg] || (cache[arg] = fn(arg))
  )();
// 代码示例 (此处省略)
Copy after login
  1. Multi-line ellipsis

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

.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;
}
Copy after login
  1. Select the last few elements

Use CSS selectors to target specific elements.

li:nth-child(-n + 3) {
  text-decoration: underline;
}
// 代码示例 (此处省略)
Copy after login
  1. Scroll bar style

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

// 代码示例 (此处省略)
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  1. Percentage Calculation-Maximum Remainder Method

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

// 代码示例 (此处省略)
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  1. Limit concurrency

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

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));
Copy after login
Copy after login
  1. UUID generation

Use this code to generate a unique identifier.

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));
Copy after login
Copy after login
  1. Open modal and prevent body from scrolling

Prevent body scrolling when opening the modal.

<a href="https://example.com" rel="noopener noreferrer" target="_blank">打开</a>
Copy after login
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template