Original sentence: Https://Wangdoc.Com/javascript/index.Html
Other common events
Resource Event
beforeunload event
beforeunload
Before triggering event window, documents, resources will be uninstalled. It can be used to prevent users from accidentally unloading resources.
If the event object's returnValue
properties 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 beforeunload
event, 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 unload
events, other things should not listen: the user to modify the form has not been saved to leave.
unload event
unload
In the event window is closed or document
triggered when an object to be unloaded. It triggers the order came in beforeunload
, pagehide
behind the event.
unload
When 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 beforeunload
event, once used the unload
event, 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
load
Event triggered when a page or a resource loading. Note that page or resource loaded from the browser cache, and will not trigger load
events.
window.addEventListener('load', function(event) {
console.log('所有资源都加载完成');
});
error
Event is triggered when a page fails to load or resource. abort
Event is triggered when the user cancels the loading.
These three events actually belong to the progress of events, not only in the document
objects, 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 document
objects, window
objects, XMLHttpRequestUpload objects will trigger load
event and the error
event.
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 load
later events. When loaded from the cache, load
the event will not be triggered because the pages in the cache usually look load
like 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 persisted
property 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) {
// ...
}
});
pagehide
Events and pageshow
event 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 unload
after the event listener function, the page will not be saved in the cache, and use pagehide
the event, the page will be stored in the cache.
pagehide
Examples of events also has a persisted
property, 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 pageshow
events and pagehide
event triggers before the main page.
Note that these two events only in the browser's history
triggered when an object is changed, it does not matter with the page is visible.
popstate event
popstate
Event in the browser's history
trigger to switch the current record explicitly object to occur. Note that the call history.pushState()
or history.replaceState()
, and will not trigger popstate
events. The event only if the user in history
an 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 state
property, preservation history.pushState
methods, and history.replaceState
methods to add the current record of the state
object.
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, pushState
the method to history
add two records, then replaceState
replace the current method of recording off. Therefore, two consecutive back
method, the current entry will be returned to the original URL, it does not come with state
the object, so the event state
property null
, and then forward two records, went back to replaceState
the recording method to add.
For the first time the browser page loads, whether to trigger popstate
event processing is not the same, Firefox does not trigger the event.
hashchange event
hashchange
In the event the URL hash part (ie #
rear part of the number, including the #
number) triggered when changes occur. The event usually window
listening on the object.
hashchange
The event instance has two unique properties: oldURL
properties and newURL
attributes, 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 document
trigger 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 load
event 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 DOMContentLoaded
event.
document.addEventListener('DOMContentLoaded', function (event) {
console.log('DOM 生成');
});
// 这段代码会推迟触发 DOMContentLoaded 事件
for(var i = 0; i < 1000000000; i++) {
// ...
}
readystatechange event
readystatechange
Document object and event when the XMLHttpRequest object readyState
is triggered when the property changes. document.readyState
There 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, load
upcoming events trigger).
document.onreadystatechange = function () {
if (document.readyState === 'interactive') {
// ...
}
}
This event can be seen as DOMContentLoaded
an event of another implementation method.
Window events
scroll event
scroll
Events 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 requestAnimationFrame
or setTimeout
control the frequency of the triggering event, and can be combined customEvent
to 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 throttle
function is used to control the frequency of trigger events, requestAnimationFrame
methods to ensure that each page redraw (60 times per second), it will only trigger a scroll
listener function events. In other words, the above method will scroll
trigger frequency event, limited to 60 times per second. Specifically, it is scroll
an event as long as the frequency is less than 60 times per second, it will trigger optimizedScroll
event to perform optimizedScroll
monitor function events.
Use setTimeout
method, 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 scroll
event will execute scrollThrottler
the 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 throttle
writing 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 scroll
trigger frequency event, limited to once every second.
lodash
Library provides a ready-made throttle
function can be used directly.
window.addEventListener('scroll', _.throttle(callback, 1000));
Earlier in this book we introduced debounce
the concept, throttle
and it is the difference that throttle
is "cutting" to ensure the implementation only once over a period of time, and debounce
is "anti-shake", to be executed after the end of continuous operation. Scroll to the page, for example, debounce
have to wait until the user stops scrolling after the execution, throttle
it is if you've been scrolling web page, or will perform during scrolling.
resize event
resize
Event when changing the size of the browser window trigger, mainly in the window
subject 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 scroll
events, by throttle
triggering a function of frequency control events.
fullscreenchange event, fullscreenerror event
fullscreenchange
Events when entering or exiting full screen mode is triggered, the event occurs on document
an object above.
document.addEventListener('fullscreenchange', function (event) {
console.log(document.fullscreenElement);
});
fullscreenerror
Event 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 ClipboardEvent
examples of interface. ClipboardEvent
One 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 document
objects 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, occurfocus
before the event. This event bubbling.focusout
: Element nodes that will trigger loses focus, occurblur
before the event. This event bubbling.
These four events are inherited FocusEvent
interface. FocusEvent
Examples has the following properties.
FocusEvent.target
: The target node of the event.FocusEvent.relatedTarget
: For thefocusin
event, the return node loses focus; for thefocusout
event, will return to accept the focus node; forfocus
andblur
events returnsnull
.
Because focus
and blur
events do not bubble, can only be triggered during the capture phase, so addEventListener
the 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. CustomEvent
In 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 isnull
.
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 build
events. After the trigger event, it is monitored, so that the output of the event instance detail
attribute (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 detail
properties.