javascript: Other common events

Original sentence: Https://Wangdoc.Com/javascript/index.Html

Other common events

Resource Event

beforeunload event

beforeunloadBefore triggering event window, documents, resources will be uninstalled. It can be used to prevent users from accidentally unloading resources.

If the event object's returnValueproperties is a non-empty string, then the browser will pop up a dialog box asking the user whether to offload the resource. However, the user-specified string may not be displayed, the browser will display predefined string. If the user clicks "Cancel" button, the resources will not be uninstalled.

window.addEventListener('beforeunload', function (event) {
  event.returnValue = '你确定离开吗?';
});

In the above code, if the user to close the window, the browser will pop up a window asking the user to confirm.

Browser behavior of this event is very inconsistent, and some browser calls event.preventDefault()will pop-up dialog box. IE browser need to explicitly returns a non-null string, the dialog box will pop up. Also, most browsers do not display the specified text in the dialog box to show only the default text. Accordingly, the following wording may be used, to achieve maximum compatibility.

window.addEventListener('beforeunload', function (e) {
  var confirmationMessage = '确认关闭窗口?';

  e.returnValue = confirmationMessage;
  return confirmationMessage;
});

Note that many mobile browsers default to ignore this event, the desktop browser there are ways to ignore this event. So, it might not take effect, can not rely on it to prevent the user closes the window. In addition, once the use of the beforeunloadevent, the browser will not cache the current page, use the "back" button to re-request to the server page. This is because the purpose of this event listeners generally modify the initial state, then the initial page cache no sense.

Basically, the only one where you can listen for unloadevents, other things should not listen: the user to modify the form has not been saved to leave.

unload event

unloadIn the event window is closed or documenttriggered when an object to be unloaded. It triggers the order came in beforeunload, pagehidebehind the event.

unloadWhen an event occurs, the document is in a particular state. All the resources still exists, but is not visible to the user, UI interaction of all invalid. This event is not canceled, even if the monitor function which throws an error can not be stopped unloading document.

window.addEventListener('unload', function(event) {
  console.log('文档将要卸载');
});

On the phone, the browser or the system may be discarded directly on the page, then the event will not happen. And with the beforeunloadevent, once used the unloadevent, the browser will not cache the current page, ditto. Therefore, under no circumstances should rely on this event, specify the code to be executed when the page unload, consider not using this event.

load events, error events

loadEvent triggered when a page or a resource loading. Note that page or resource loaded from the browser cache, and will not trigger loadevents.

window.addEventListener('load', function(event) {
  console.log('所有资源都加载完成');
});

errorEvent is triggered when a page fails to load or resource. abortEvent is triggered when the user cancels the loading.

These three events actually belong to the progress of events, not only in the documentobjects, but also occurs in a variety of external resources above. Browse the Web is a process to load a variety of resources, image (image), stylesheets (style sheet), script (script), video (video), audio (audio), Ajax request (XMLHttpRequest) and so on. These resources and documentobjects, windowobjects, XMLHttpRequestUpload objects will trigger loadevent and the errorevent.

session of historical events

pageshow event, pagehide event

By default, the browser in the current session (session) cache page when the user clicks "forward / back" button, the browser will load the page from the cache.

pageshow event triggered when the page loads, including the first two cases loading and loading from the cache. If you want to specify the page is loaded each time the code runs (not from either the browser cache), the listener function can be placed in this event.

When first loaded, it triggers the order came in loadlater events. When loaded from the cache, loadthe event will not be triggered because the pages in the cache usually look loadlike after listening function event run, so do not repeated. Similarly, if the page is loaded, initialization script JavaScript within the page (such as DOMContentLoaded event listener function) from the cache will not be executed.

window.addEventListener('pageshow', function(event) {
  console.log('pageshow: ', event);
});

pageshow event has a persistedproperty that returns a Boolean value. When the page is first loaded, this property is false; when the page is loaded from the cache, this property is true.

window.addEventListener('pageshow', function(event){
  if (event.persisted) {
    // ...
  }
});

pagehideEvents and pageshowevent similar to the trigger when the user through the "Forward / Back" button to leave the current page. It differs from the unload event is that, if you define an object in the window unloadafter the event listener function, the page will not be saved in the cache, and use pagehidethe event, the page will be stored in the cache.

pagehideExamples of events also has a persistedproperty, set this property true, it means you want to save the page in the cache; set false, indicating that the page is not stored in the cache, then if the unload event is set listener function, the function will be after the event pagehide run Now.

If the page contains <frame>or <iframe>elements of the <frame>page pageshowevents and pagehideevent triggers before the main page.

Note that these two events only in the browser's historytriggered when an object is changed, it does not matter with the page is visible.

popstate event

popstateEvent in the browser's historytrigger to switch the current record explicitly object to occur. Note that the call history.pushState()or history.replaceState(), and will not trigger popstateevents. The event only if the user in historyan explicit switching between recording trigger, such as a mouse click on the "Back / Forward" button, or call in a script history.back(), history.forward(), history.go()when triggered.

The event object has a stateproperty, preservation history.pushStatemethods, and history.replaceStatemethods to add the current record of the stateobject.

window.onpopstate = function (event) {
  console.log('state: ' + event.state);
};
history.pushState({page: 1}, 'title 1', '?page=1');
history.pushState({page: 2}, 'title 2', '?page=2');
history.replaceState({page: 3}, 'title 3', '?page=3');
history.back(); // state: {"page":1}
history.back(); // state: null
history.go(2);  // state: {"page":3}

In the above code, pushStatethe method to historyadd two records, then replaceStatereplace the current method of recording off. Therefore, two consecutive backmethod, the current entry will be returned to the original URL, it does not come with statethe object, so the event stateproperty null, and then forward two records, went back to replaceStatethe recording method to add.

For the first time the browser page loads, whether to trigger popstateevent processing is not the same, Firefox does not trigger the event.

hashchange event

hashchangeIn the event the URL hash part (ie #rear part of the number, including the #number) triggered when changes occur. The event usually windowlistening on the object.

hashchangeThe event instance has two unique properties: oldURLproperties and newURLattributes, respectively, before and after the full URL changes.

// URL 是 http://www.example.com/
window.addEventListener('hashchange', myFunction);

function myFunction(e) {
  console.log(e.oldURL);
  console.log(e.newURL);
}

location.hash = 'part2';
// http://www.example.com/
// http://www.example.com/#part2

Page status events

DOMContentLoaded event

Page download and parse is completed, the browser will documenttrigger DOMContentLoaded event on the object. At this time, only complete analytical web page (DOM entire page is generated), all external resources (stylesheets, scripts, iframe, etc.) may not have the download is complete. In other words, this event than the loadevent occurred much earlier time.

document.addEventListener('DOMContentLoaded', function (event) {
  console.log('DOM生成');
});

Note that the script once clogged, will delay the trigger Pages JavaScript scripts are executed synchronously DOMContentLoadedevent.

document.addEventListener('DOMContentLoaded', function (event) {
  console.log('DOM 生成');
});

// 这段代码会推迟触发 DOMContentLoaded 事件
for(var i = 0; i < 1000000000; i++) {
  // ...
}

readystatechange event

readystatechangeDocument object and event when the XMLHttpRequest object readyStateis triggered when the property changes. document.readyStateThere are three possible values: loading(page loading), interactive(web page has been parsed, but is still in external resources loading state) and complete(pages and all external resources is over loaded, loadupcoming events trigger).

document.onreadystatechange = function () {
  if (document.readyState === 'interactive') {
    // ...
  }
}

This event can be seen as DOMContentLoadedan event of another implementation method.

Window events

scroll event

scrollEvents when a document or document element scroll trigger, mainly in the user drags the scroll bar.

window.addEventListener('scroll', callback);

The event will be a substantial trigger continuously, so there should not be very computationally expensive operation among its monitor function. The recommended practice is to use requestAnimationFrameor setTimeoutcontrol the frequency of the triggering event, and can be combined customEventto throw a new event.

(function () {
  var throttle = function (type, name, obj) {
    var obj = obj || window;
    var running = false;
    var func = function () {
      if (running) { return; }
      running = true;
      requestAnimationFrame(function() {
        obj.dispatchEvent(new CustomEvent(name));
        running = false;
      });
    };
    obj.addEventListener(type, func);
  };

  // 将 scroll 事件重定义为 optimizedScroll 事件
  throttle('scroll', 'optimizedScroll');
})();

window.addEventListener('optimizedScroll', function() {
  console.log('Resource conscious scroll callback!');
});

The above code, the throttlefunction is used to control the frequency of trigger events, requestAnimationFramemethods to ensure that each page redraw (60 times per second), it will only trigger a scrolllistener function events. In other words, the above method will scrolltrigger frequency event, limited to 60 times per second. Specifically, it is scrollan event as long as the frequency is less than 60 times per second, it will trigger optimizedScrollevent to perform optimizedScrollmonitor function events.

Use setTimeoutmethod, can be placed at greater intervals.

(function() {
  window.addEventListener('scroll', scrollThrottler, false);

  var scrollTimeout;
  function scrollThrottler() {
    if (!scrollTimeout) {
      scrollTimeout = setTimeout(function () {
        scrollTimeout = null;
        actualScrollHandler();
      }, 66);
    }
  }

  function actualScrollHandler() {
    // ...
  }
}());

The above code, each scrollevent will execute scrollThrottlerthe function. The function which has a timer setTimeout, trigger once every 66 milliseconds (15 times per second) real task execution actualScrollHandler.

The following is a more general throttlewriting function.

function throttle(fn, wait) {
  var time = Date.now();
  return function() {
    if ((time + wait - Date.now()) < 0) {
      fn();
      time = Date.now();
    }
  }
}

window.addEventListener('scroll', throttle(callback, 1000));

The above code will scrolltrigger frequency event, limited to once every second.

lodashLibrary provides a ready-made throttlefunction can be used directly.

window.addEventListener('scroll', _.throttle(callback, 1000));

Earlier in this book we introduced debouncethe concept, throttleand it is the difference that throttleis "cutting" to ensure the implementation only once over a period of time, and debounceis "anti-shake", to be executed after the end of continuous operation. Scroll to the page, for example, debouncehave to wait until the user stops scrolling after the execution, throttleit is if you've been scrolling web page, or will perform during scrolling.

resize event

resizeEvent when changing the size of the browser window trigger, mainly in the windowsubject above.

var resizeMethod = function () {
  if (document.body.clientWidth < 768) {
    console.log('移动设备的视口');
  }
};

window.addEventListener('resize', resizeMethod, true);

The event will continuously trigger a lot, so it seems most of the above scrollevents, by throttletriggering a function of frequency control events.

fullscreenchange event, fullscreenerror event

fullscreenchangeEvents when entering or exiting full screen mode is triggered, the event occurs on documentan object above.

document.addEventListener('fullscreenchange', function (event) {
  console.log(document.fullscreenElement);
});

fullscreenerrorEvent triggered when browser can not switch to full screen mode.

Clipboard events

The following three events were related event clipboard operations.

  • cut: The selected content is removed from the document, triggered when added to the clipboard.
  • copy: When copying trigger action.
  • paste: Clipboard contents pasted into the document after the trigger.

These three events are ClipboardEventexamples of interface. ClipboardEventOne instance attribute clipboardData, a DataTransfer object data stored in the clip. Specific API interfaces and methods of operation, please refer to "drag event" DataTransfer object part.

document.addEventListener('copy', function (e) {
  e.clipboardData.setData('text/plain', 'Hello, world!');
  e.clipboardData.setData('text/html', '<b>Hello, world!</b>');
  e.preventDefault();
});

The above code allows copied into the clipboard, all data specified by the developer, not the data the user wants to copy.

Focus Events

Focus events occur in the element nodes and documentobjects above, related to gaining or losing focus. It includes the following four events.

  • focus: After triggering element node has the focus, the event does not bubble.
  • blur: After triggering element node loses focus, the event does not bubble.
  • focusin: Element node will be triggered when the focus, occur focusbefore the event. This event bubbling.
  • focusout: Element nodes that will trigger loses focus, occur blurbefore the event. This event bubbling.

These four events are inherited FocusEventinterface. FocusEventExamples has the following properties.

  • FocusEvent.target: The target node of the event.
  • FocusEvent.relatedTarget: For the focusinevent, the return node loses focus; for the focusoutevent, will return to accept the focus node; for focusand blurevents returns null.

Because focusand blurevents do not bubble, can only be triggered during the capture phase, so addEventListenerthe third parameter of the method needs to be set true.

form.addEventListener('focus', function (event) {
  event.target.style.background = 'pink';
}, true);

form.addEventListener('blur', function (event) {
  event.target.style.background = '';
}, true);

For the above code form text input box, set the background color to accept focus, removing the background color loses focus.

CustomEvent Interface

CustomEvent interfaces for generating a custom event instance. Those events predefined browser, although can be generated manually, but often can not bind data on the event. If you need to trigger events at the same time, passing the specified data, you can use a custom event object CustomEvent interfaces generated.

Browser native in the CustomEvent()constructor, to generate CustomEvent event instance.

new CustomEvent(type, options)

CustomEvent()Constructor takes two parameters. The first argument is a string that represents the name of the event, this is a must. The second parameter is the configuration object event, this parameter is optional. CustomEventIn addition to receiving the configuration object configuration properties Event event, only one of their own property.

  • detail: Accompanying data represents an event of default it is null.

Below is an example.

var event = new CustomEvent('build', { 'detail': 'hello' });

function eventHandler(e) {
  console.log(e.detail);
}

document.body.addEventListener('build', function (e) {
  console.log(e.detail);
});

document.body.dispatchEvent(event);

The above code, we manually defined buildevents. After the trigger event, it is monitored, so that the output of the event instance detailattribute (i.e., a string hello).

Here is another example.

var myEvent = new CustomEvent('myevent', {
  detail: {
    foo: 'bar'
  },
  bubbles: true,
  cancelable: false
});

el.addEventListener('myevent', function (event) {
  console.log('Hello ' + event.detail.foo);
});

el.dispatchEvent(myEvent);

Code is also described above, the event CustomEvent example, in addition to having Event interface instance attributes, also have detailproperties.

Guess you like

Origin www.cnblogs.com/wbyixx/p/12499334.html