Like it and see. Make it a habit

In this paper,GitHub Github.com/qq449245884…Has included more categories of previous articles, as well as a lot of my documentation and tutorial material. Welcome Star and Perfect, you can refer to the examination points for review in the interview, I hope we can have something together.

This article mainly introduces 24 ES6 methods, these methods are quite practical, please remember this book, from time to time to read.

1. How do I hide all specified elements

const hide = (el) => Array.from(el).forEach(e => (e.style.display = 'none')); // Example: Hide all '<img>' elements on the page? hide(document.querySelectorAll('img') copy the codeCopy the code

2. How do I check if the element has the specified class?

Each node in the PAGE DOM has a classList object, which programmers can use to add, delete, and modify CSS classes on the node. With classList, programmers can also use it to determine whether a node is assigned a CSS class.

Const hasClass = (el, className) => el.classList. Contains (className)'p.special'), 'special') / /trueCopy the codeCopy the code

3. How to switch an element’s class?

const toggleClass = (el, Toggle (className) => el.classlist. toggle(className); toggleClass(document.querySelector();'p.special'), 'special') Copy codeCopy the code

4. How do I obtain the scroll position of the current page?

const getScrollPosition = (el = window) => ({ x: el.pageXOffset ! == undefined ? el.pageXOffset : el.scrollLeft, y: el.pageYOffset ! == undefined ? el.pageYOffset : el.scrollTop }); / / examples/getScrollPosition (); // {x: 0, y: 200} copy codeCopy the code

5. How do I scroll smoothly to the top of the page

const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if(c > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, c - c / 8); } // Example scrollToTop() copies the codeCopy the code

Tell the browser window. RequestAnimationFrame () – you want to perform an animation, and required the browser until the next redraw calls the specified callback function to update the animation. This method takes as an argument a callback function that is executed before the browser’s next redraw.

RequestAnimationFrame: Advantage: It is up to the system to determine the timing of the callback function. If the refresh frequency is 60Hz, the callback function will be executed at each refresh interval without frame loss or stalling.

6. How do I check if the parent element contains child elements?

const elementContains = (parent, child) => parent ! == child && parent.contains(child); / / examples/elementContains (document. QuerySelector ('head'), document.querySelector('title')); 
// true
elementContains(document.querySelector('body'), document.querySelector('body')); 
// falseCopy the codeCopy the code

7. How do I check whether the specified element is visible in the viewport?

const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
  const { top, left, bottom, right } = el.getBoundingClientRect();
  const { innerHeight, innerWidth } = window;
  returnpartiallyVisible ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right >  0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; }; / / examples/elementIsVisibleInViewport (el); / / need visible elementIsVisibleInViewport (el,true); // For full screen (top, bottom, left, right) see the copy codeCopy the code

8. How do I get all the images in an element?

const getImages = (el, includeDuplicates = false) => {
  const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));
  returnincludeDuplicates ? images : [...new Set(images)]; }; // Example: includeDuplicates istrueGetImages (document,true); / / /'image1.jpg'.'image2.png'.'image1.png'.'... ']
getImages(document, false); / / /'image1.jpg'.'image2.png'.'... 'Copy codeCopy the code

9. How to determine whether the device is a mobile device or a desktop/laptop?

const detectDeviceType = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    ? 'Mobile'
    : 'Desktop'; / / examples/detectDeviceType (); //"Mobile" or "Desktop"Copy the codeCopy the code

10.How to get the current URL?

Const currentURL = () => window.location.href // instance currentURL() //'https://google.com'Copy the codeCopy the code

11. How to create an object that contains the current URL parameters?

const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), {} ); / / examples/getURLParameters ('http://url.com/page?n=Adam&s=Smith'); // {n: 'Adam', s: 'Smith'}
getURLParameters('google.com'); // {} copy the codeCopy the code

12. How do I turn a set of form elements into objects?

const formToObject = form => Array.from(new FormData(form)).reduce( (acc, [key, value]) => ({ ... acc, [key]: value }), {} ); / / examples/formToObject (document. QuerySelector ('#form')); 
// { email: '[email protected]', name: 'Test Name'} Duplicate codeCopy the code

13. How do I retrieve a set of properties indicated by a given selector from an object?

const get = (from, ... selectors) => [...selectors].map(s => s .replace(/\[([^\[\]]*)\]/g,'. $1.)
      .split('. ') .filter(t => t ! = =' ')
      .reduce((prev, cur) => prev && prev[cur], from)
  );
const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test'}}; // Example get(obj,'selector.to.val'.'target[0]'.'target[2].a'); / / /'val to select', 1, 'test'Copy codeCopy the code

14. How to call the provided function after waiting for the specified time?

const delay = (fn, wait. args) =>setTimeout(fn, wait. args); delay(function(text) {
    console.log(text);
  },
  1000,
  'later'); // Prints after 1 second'later'Copy the codeCopy the code

15. How do I trigger a specific event on a given element and optionally pass custom data?

const triggerEvent = (el, eventType, detail) => el.dispatchEvent(new CustomEvent(eventType, { detail })); / / examples/triggerEvent (document. GetElementById ('myId'), 'click');
triggerEvent(document.getElementById('myId'), 'click', { username: 'bob'}); Copy the codeCopy the code

CustomEvent functions include Event, CustomEvent, and dispatchEvent

// Issue a resize built-in Event window.dispatchEvent('resize'Var Event = new Event();'build');
var elem = document.querySelector('#id'Elem.addeventlistener ()'build'.function (e) { ... }, false); Elem. DispatchEvent (event); Copy the codeCopy the code

CustomEvent can create a more highly CustomEvent, along with some data, as follows:

var myEvent = new CustomEvent(eventname, options); Options can be: {detail: {... }, bubbles:true// Whether bubble cancelable:false// Whether to cancel the default event} copy codeCopy the code

The detail can hold some initialization information that can be called when triggered. Other attributes define whether the event has bubbling and so on.

While built-in events are triggered by the browser based on certain actions, custom events need to be triggered manually. The dispatchEvent function is used to trigger an event:

element.dispatchEvent(customEvent); Copy the codeCopy the code

The above code says that the customEvent event is triggered on element.

// add an appropriate event listener
obj.addEventListener("cat".function(e) { process(e.detail) });
 
// create and dispatch the event
var event = new CustomEvent("cat", {"detail": {"hazcheeseburger":true}}); obj.dispatchEvent(event); $(element).on($(element))'myCustomEvent'.function() {}); $(element).trigger('myCustomEvent'); // In addition, you can also pass more parameter information when triggering custom events: $("p" ).on( "myCustomEvent".function( event, myName ) {
  $( this ).text( myName + ", hi there!" );
});
$( "button" ).click(function() {$("p" ).trigger( "myCustomEvent"["John"]); }); Copy the codeCopy the code

16. How do I remove event listeners from elements?

const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts);

const fn = () => console.log('! ');
document.body.addEventListener('click', fn);
off(document.body, 'click', fn); Copy the codeCopy the code

17. How do I get a readable format for a given number of milliseconds?

const formatDuration = ms => {
  if (ms < 0) ms = -ms;
  const time = {
    day: Math.floor(ms / 86400000),
    hour: Math.floor(ms / 3600000) % 24,
    minute: Math.floor(ms / 60000) % 60,
    second: Math.floor(ms / 1000) % 60,
    millisecond: Math.floor(ms) % 1000
  };
  returnObject.entries(time) .filter(val => val[1] ! == 0) .map(([key, val]) => `${val} ${key}${val ! = = 1? 's' : ''}`)
    .join(', '); }; / / examples/formatDuration (1001); //'1 second, 1 millisecond'
formatDuration(34325055574); 
// '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'Copy the codeCopy the code

18. How do I get the difference (in days) between two dates?

const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); GetDaysDiffBetweenDates (new Date('2017-12-13'), new Date('2017-12-22')); // 9 Copy the codeCopy the code

19. How do I make GET requests to passed urls?

const httpGet = (url, callback, err = console.error) => {
  const request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send();
};

httpGet(
  'https://jsonplaceholder.typicode.com/posts/1', console.log ); / / {"userId": 1, "id": 1, "title": "sample title"."body": "my text"} Duplicate codeCopy the code

20. How do I make a POST request on a passed URL?

const httpPost = (url, data, callback, err = console.error) => {
  const request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.setRequestHeader('Content-type'.'application/json; charset=utf-8');
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send(data);
};

const newPost = {
  userId: 1,
  id: 1337,
  title: 'Foo',
  body: 'bar bar bar'
};
const data = JSON.stringify(newPost);
httpPost(
  'https://jsonplaceholder.typicode.com/posts', data, console.log ); / / {"userId": 1, "id": 1337, "title": "Foo"."body": "bar bar bar"} Duplicate codeCopy the code

21. How do I create a counter with a specified range, step, and duration for a specified selector?

const counter = (selector, start, end, step = 1, duration = 2000) => {
  let current = start,
    _step = (end - start) * step < 0 ? -step : step,
    timer = setInterval(() => {
      current += _step;
      document.querySelector(selector).innerHTML = current;
      if (current >= end) document.querySelector(selector).innerHTML = end;
      if (current >= end) clearInterval(timer);
    }, Math.abs(Math.floor(duration / (end - start))));
  returntimer; }; / / examples/counter ('#my-id', 1, 1000, 5, 2000); // Let the element 'id= "my-id" create a 2-second timer copy codeCopy the code

22. How do I copy strings to the clipboard?

  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly'.' ');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  const selected =
    document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
  if(selected) { document.getSelection().removeAllRanges(); document.getSelection().addRange(selected); }}; / / examples/copyToClipboard ('Lorem ipsum'); 
// 'Lorem ipsum'Copied code to clipboardCopy the code

23. How do I determine whether a page’s browser TAB is focused?

const isBrowserTabFocused = () => ! document.hidden; / / examples/isBrowserTabFocused (); //trueCopy the codeCopy the code

24. How do I create a directory (if no directory exists)?

const fs = require('fs'); const createDirIfNotExists = dir => (! fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined); / / examples/createDirIfNotExists ('test'); Copy the codeCopy the code

Most of the above methods are very practical, can solve a lot of development process problems, we make good use of it.

The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.

Dev. To/madarsbiss /…

Source: Dev

communication

This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.


Author: Front-end xiaozhi


Link: https://juejin.cn/post/6844904080868016142


Source: Nuggets


Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.