Are these infrequent Web API s really useful? Don't ask, they are useful.

Keywords: Front-end Mobile Attribute less network

This article lists some of the less common Web API s, which contain a lot of content, so the content of compatibility will not appear in this article, you can consult them by yourself. The following cases can match the motion map as much as I can, in order to avoid the content is dry and tedious, but if the content is wrong, please spray or correct it personally.

Method List

  1. querySelector (element query down, return one)
  2. querySelectorAll (elements query downward, multiple returns)
  3. closest (element up query)
  4. dataset (Gets a collection of attributes prefixed with "data-" for elements)
  5. URLSearchParams (query parameters)
  6. Hidden (hidden element)
  7. contenteditable
  8. spellCheck
  9. classList (Class Name Controller)
  10. GetBounding ClientRect (element spatial structure details)
  11. contains (to determine whether the specified element is included)
  12. online state
  13. battery state
  14. vibration (Equipment vibration)
  15. page visibility
  16. Device Orientation
  17. toDataUrl (Canvas content to base64)
  18. CusmEvent
  19. Notification (desktop notification)
  20. Full Screen
  21. orientation

Break through one by one

1. querySelector

It's 9102. Are you still using getElementById?

Gets the element in the specified element that matches the css selector:

// Acting on document
document.querySelector("#nav ";// Get the element id="nav "in the document
document.querySelector(".nav"); // Get the class="nav" element in the document
document.querySelector("#nav li:first-child ";// Get the first Li element below id="nav "in the document

// It can also work on other elements.
let nav = dodocument.querySelector("#nav");
nav.querySelector("li"); // If there are more than one li, return the last Li

Note: In any case, only one element is returned, and if there are more than one element, only the last one is returned.

2. querySelectorAll

Gets all elements in the specified element that match the css selector:

let list = document.querySelectorAll("li");  // NodeList(2) [li, li] Here we assume that two are returned

Note: The returned value is an array of classes. The native method of the array (forEach, map, etc.) cannot be used. It needs to be converted:

Array.from(list).map();

3. closest

In contrast to querySelector, this element can be queried up, i.e., to the parent element:

document.querySelector("li").closest("#nav");

4. dataset

Just like the native Wechat applet, it can get the set of attributes prefixed with "data-" on the label:

<p data-name="Spider-Man" data-age="16"></p>
document.querySelector("p").dataset; // {name: Spider-Man, age: `16'}

Note: Although getAttribute method can be used to obtain any attribute value, but the nature is different. This is a development specification problem. Every custom attribute should be added data-prefix.

5. URLSearchParams

Suppose the url parameter of the browser is "? name = Spider-Man & age = 16"

new URLSearchParams(location.search).get("name"); // Spider-Man

6. hidden

This is an html attribute that specifies whether the element is hidden or not, as shown in css display: none:

< div hidden > I was hidden </div >
document.querySelector("div").hidden = true / false;

7. contenteditable

An element can be edited by the user:

< p contenteditable > I am a P element, but I can also be edited</p>

The results are as follows:

If this property meets the style tag, it will produce a very wonderful story:
contenteditable and user-modify can also play like this.

8. speelcheck

It is also an html attribute that specifies whether the input is checked for Chinese Pinyin:

<!-- The default is true,Can be omitted -->
<textarea spellcheck="true"></textarea>

The results are as follows:

Settings are not checked:

<textarea spellcheck="false"></textarea>

The results are as follows:

9. classList

This is an object that encapsulates many methods for manipulating element class names:

<p class="title"></p>
let elem = document.querySelector("p");

// Added class name
elem.classList.add("title-new"); // "title title-new"

// Delete the class name
elem.classList.remove("title"); // "title-new"

// Switching class names (deleted or increased, often used for some switching operations, such as display/hide)
elem.classList.toggle("title"); // "title-new title"

// Substitution class name
elem.classList.replace("title", "title-old"); // "title-new title-old"

// Does it contain the specified class name?
elem.classList.contains("title"); // false

10. getBoundingClientRect

Spatial information of the specified element on the current page can be obtained:

elem.getBoundingClientRect();

// Return
{
  x: 604.875,
  y: 1312,
  width: 701.625,
  height: 31,
  top: 1312,
  right: 1306.5,
  bottom: 1343,
  left: 604.875
}

Note: Top is the distance from the top of the document, and Y is the distance from the top of the visual window (browser screen). If the browser scrolls, the top value remains unchanged, the y value will change.

11. contains

You can determine whether the specified element contains the specified child elements:

<div>
  <p></p>
</div>
document.querySelector("div").contains(document.querySelector("p")); // true

12. online state

Monitor the current network state changes, and then execute the corresponding method:

window.addEventListener("online", xxx);

window.addEventListener("offline", () => {
  alert("You're disconnected!");
});

The effect of PC end is as follows:

The effect of mobile end is as follows:

Use scenario: prompt the user to disconnect the network, a bullet box directly frightens the user

13. battery state

Get the battery status of the device:

navigator.getBattery().then(battery => console.log(battery));

// Return
{
  charging, // Is it charging?
  chargingTime, // Time required to be fully charged
  dischargingTime, // Current power usage time
  level, Residual electricity

  onchargingchange, // Monitoring Charging State Change
  onchargingtimechange, // Monitor the change of time required to be fully charged
  ondischargingtimechange, // Monitor current power usage time changes
  onlevelchange // Monitor changes in electricity
}

Use scenario: to remind the user that the power is full, or in order to make the user feel safe, when the power is less than 99%, a bullet box will prompt "it's time to recharge"?

14. vibration

Hip-hop, make the equipment vibrate:

// Shake once
navigator.vibrate(100);

// Continuous vibration, 200 ms vibration, 100 ms suspension, 300 ms vibration
navigator.vibrate([200, 100, 300]);

The effect is as follows: Sorry, you have to use your own hand to grasp the mobile phone in order to feel it;

Use scenarios: Provide sensory feedback through vibration, such as continuous vibration to remind users when they haven't touched the screen for too long

15. page visibility

As the name implies, this API is used to monitor page visibility changes. Switching in the label bar on the PC side, minimizing triggers, and cutting in the mobile side to the background triggers. It is understood that the page disappears.

document.addEventListener("visibilitychange", () => {
  console.log(`Page visibility: ${document.visibilityState}`);
});

The effect of PC end is as follows:

The effect of mobile end is as follows:

Scenario: When the program cuts to the background, if there is a video playing or some animation execution, you can pause first.

16. deviceOrientation

Gyroscope, the direction of the device, also known as gravity induction, is the solution to the failure of the API on IOS devices. The domain name protocol is changed to https.

alpha, beta and gamma from left to right respectively.

window.addEventListener("deviceorientation", event => {
  let {
    alpha,
    beta,
    gamma
  } = event;

  console.log(`alpha: ${alpha}`);
  console.log(`beta: ${beta}`);
  console.log(`gamma: ${gamma}`);
});

The effect of the mobile end is as follows (the mobile phone is constantly turning at this time):

Use Scene: Some elements on the page need to be moved according to the mobile phone swing to achieve parallax effect, such as the interface where King Glory enters the game, the mobile phone rotates the background map will follow (vii)

17. toDataURL

The API of canvas converts the contents of the canvas into an image address of base64.

let canvas = document.querySelector("canvas");
let context = canvas.getContext("2d");

// Draw something
...

let url = canvas.toDataURL("image/png"); // Converting Canvas Content to base64 Address

When using tag a to download pictures, the links between pictures are cross-domain (pictures are my Nugget avatar). Instead of downloading, they can preview pictures:

<img src="xxx">

<button>
  <a href="xxx" download="avatar">Download pictures</a>
</button>

The results are as follows:

Encapsulate the following code to solve the problem

const downloadImage = (url, name) => {
  // Instance canvas
  let canvas = document.createElement("canvas");
  let context = canvas.getContext("2d");

  // Instantiate a picture object
  let image = new Image();
  image.crossOrigin = "Anonymous";
  image.src = url;

  // When the picture is loaded
  image.onload = () => {
    // Draw pictures on canvas
    canvas.height = image.height;
    canvas.width = image.width;
    context.drawImage(image, 0, 0);

    // Converting the contents of the canvas to base64 addresses
    let dataURL = canvas.toDataURL("image/png");

    // Create a label to simulate clicks for download
    let a = document.createElement("a");
    a.hidden = true;
    a.href = dataURL;
    a.download = name;

    document.body.appendChild(a);
    a.click();
  }
}

The results are as follows:

Or convert the current DOM into images for download, often used to generate posters:
html2canvas

18. customEvent

Custom events, just like on and emit in vue;

Listen for custom events:

window.addEventListener("follow", event => {
  console.log(event.detail); // Output {name: Front End Cosmological Intelligence Agency"}
});

Send custom events:

window.dispatchEvent(new CustomEvent("follow", {
  detail: {
    name: "Front End Cosmological Intelligence Agency"
  }
}));

19. notification

Desktop notifications on the PC side, such as Wechat on the Web side, will appear in the lower right corner when receiving a message (although you minimize the browser), because this notification is independent of the browser and is a native control of the system;

const notice = new Notification("Front End Cosmological Intelligence Agency", {
  body: "These 20 are not commonly used Web API Is it really useful??,Don't ask. Asking is useful.🈶",
  icon: "My Nugget Head",
  data: {
    url: "https://www.baidu.com"
  }
});

// Click Callback
notice.onclick = () => {
  window.open(notice.data.url); // When the user clicks on the notification, open Baidu website in the browser
}

The results are as follows:

Note: To successfully initiate notifications, first of all, the user's authorization is required.

Notification.requestPermission(prem => {
  prem == "granted" // Agree!
  prem == "denied" // refuse
})

Therefore, a request is made to the user before the call is made:

let permission = Notification.permission;

if (permission == "granted") {
  // Have agreed to start sending notification
  ...
} else if (permission == "denied") {
  // No, I can't.
} else {
  // In other states, you can resend authorization prompts
  Notification.requestPermission();
}

20. fullScreen

Full screen? A previous project just works on it, not only on document Element, but also on specified elements.

/**
 * @method launchFullScreen Open Full Screen
 * @param {Object} elem = document.documentElement Elements of action
 */
const launchFullScreen = (elem = document.documentElement) => {
  if(elem.requestFullScreen) {
    elem.requestFullScreen();
  } else if(elem.mozRequestFullScreen) {
    elem.mozRequestFullScreen();
  } else if(elem.webkitRequestFullScreen) {
    elem.webkitRequestFullScreen();
  }
}

There's nothing to introduce on the documentElement, which is equivalent to F11 opening the full screen:

So what is the effect of acting on a specified element?

Just like the rendering, it opens the full screen directly and only displays the specified elements. The width and height of the elements fill the whole screen.

When closing the full screen, it should be noted that the document object is used uniformly:

/**
 * @method exitFullScreen Close the full screen
 */
const exitFullScreen = () => {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitCancelFullScreen) {
    document.webkitCancelFullScreen();
  }
}

Use scenarios: Users need to focus on something, such as the full screen of the code editing area.

21. orientation

It can monitor the change of rotation direction of user's mobile device.

 window.addEventListener("orientationchange", () => {
  document.body.innerHTML += `<p>Angle value after screen rotation: ${window.orientation}</p>`;
}, false);

The results are as follows:

css can also be used for media queries:

/* Vertical screen style */
@media all and (orientation: portrait) {
  body::after {
    content: "Vertical screen"
  }
}

/* Horizontal screen style */
@media all and (orientation: landscape) {
  body::after {
    content: "Horizontal screen"
  }
}

Scenarios: Pages require users to open horizontal screens for better experience, such as the active pages in King Glory (vii)

summary

In fact, there are a lot of uncommon, some I did not find or write, such as geoLocation, execCommand execution commands, etc. Welcome to add, the previous articles are related to css, the latter articles do not write CSS first, for a lot of content we have written, want to write some new, but inevitably will rush. Sudden ~

Last, Public Number

At the end of this article, I hope the above will help you a little. If you like it, please remember to pay attention to it.

Wechat Public's "Front End Cosmological Intelligence Agency" will update the latest and practical front-end skills/technical articles from time to time. Welcome to pay attention. I will send more good articles to you and encourage you! A kind of

Posted by Xyphon on Fri, 23 Aug 2019 04:05:03 -0700