Web storage objects localStorage and sessionStorage allow to save key/value pairs in the browser.… a full browser restart (for localStorage).… Let’s see how it works.
localStorage demo.The main features of localStorage are:
Shared between all… Summary.Web storage objects localStorage and sessionStorage allow to store key/value pairs in the browser… localStorage
sessionStorage
Shared between all tabs and windows with the same origin
Visible within
A Proxy object wraps another object and intercepts operations, like reading/writing properties and others… , set trap for writing a property into target, and so on.… The has trap intercepts in calls.
has(target, property)
target – is the target object, passed as the… The apply(target, thisArg, args) trap handles calling a proxy as function:
target is the target object… object and the proxy.
Normally it goes upwards till <html>, and then to document object, and some events even reach window… Target phase – the event reached the target element.… Here’s the picture, taken from the specification, of the capturing (1), target (2) and bubbling (3) phases… and triggers there (target phase), and then it goes up (bubbling phase), calling handlers on its way… The target triggers at the end of the first and at the beginning of the second phase.
Outer target: USER-CARD – document event handler gets shadow host as the target.… <slot> and upwards.… All touch events and pointer events also have composed: true.… true for it to bubble up and out of the component.… …And so on.
If the DOM-element of the logs display window is still accessible and kept in memory, create and send… unregistration of objects and their cleanup callbacks.… Creating “memories” and albums.
Video montage from a series of photos.
…and much more.… decide to change one of the images and create a new one.… implementation and operation of the garbage collector.
used one of them (admin) to get into it and make changes.… We’ll mention that in the chapter Property flags and descriptors.… and copying them on the primitive level.… It copies the properties of all source objects into the target dest, and then returns it as the result… Summary.Objects are assigned and copied by reference.
That’s why Map and Set also exist.… So we should use map methods: set, get and so on.
Map can also use objects as keys.… And the standard iteration for map returns same key/value pairs as map.entries().… For example, we have visitors coming, and we’d like to remember everyone.… then the target object.
Node.js provides server-side features, and so on.… stylesheets, that explains how they are represented as objects, and how to read and write them.… CSSOM specification
Describes stylesheets and style rules, manipulations with them, and their binding… It takes the DOM specification and extends it with many additional properties and methods.… q=whatwg+localstorage, https://google.com?q=mdn+localstorage.
This property complements target.… When a mouse leaves one element for another, one of them becomes target, and the other one – relatedTarget… Each event has the information about both target and relatedTarget:
Resultscript.jsstyle.cssindex.html… And there are hundreds of cells.… out of table cells and inside them.
The secret of reliability and simplicity of a coffee machine – all details are well-tuned and hidden… , and dangerous (it can electrocute).… Internal and external interface.In object-oriented programming, properties and methods are split into… Until now we were only using public properties and methods.… The code constantly undergoes development and improvement.
The underlying Range and Selection objects are easy to grasp, and then you’ll need no recipes to make… lt;b> and 3.… We’ve already seen setStart and setEnd, here are other similar methods.… Optional arguments start and end, if provided, set the range start and end, otherwise user selection… For input, textarea: additional methods and properties.
Export and import directives have several syntax variants.… Most JavaScript style guides don’t recommend semicolons after function and class declarations.… It makes code support and refactoring easier.… modules together and optimize them to speedup loading.… Summary.Here are all types of export that we covered in this and previous articles.
from the chapter Garbage collection, JavaScript engine keeps a value in memory while it is “reachable” and… properties of an object or elements of an array or another data structure are considered reachable and… It occupies memory and may not be garbage collected.… Like Set, it supports add, has and delete, but not size, keys() and no iterations.… WeakSet is the absence of iterations, and the inability to get all current content.
Before we get into JavaScript’s ways of dealing with styles and classes – here’s an important rule.… JavaScript can modify both classes and style properties.… That’s more flexible and easier to support.
className and classList.Changing a class is one of the most… infers style.marginLeft and style.marginTop from it.… The browser takes the computed value and makes all units fixed and absolute, for instance: height:20px
There may be any pattern instead of X and Y.… If it’s not so, then the potential match is skipped, and the search continues.… =\s), and there’s 30 somewhere after it (?… That is: match everything, in any context, and then filter by context in the loop.… , so we know where exactly in the text it is, and can check the context.
bold), and previous remembered contexts are below.… And the optimization may be unneeded and totally not worth the efforts.… And they, potentially, can split even more.… And that’s sometimes required to optimize stuff.… But for many tasks a recursive solution is fast enough and easier to write and support.
When the browser loads the page, it “reads” (another word: “parses”) the HTML and generates DOM objects… But technically no one limits us, and if there aren’t enough, we can add our own.… The attributes collection is iterable and has all the attributes of the element (standard and non-standard… ) as objects with name and value properties.… What if we use a non-standard attribute for our purposes and later the standard introduces it and makes
New proposals to the language appear regularly, they are analyzed and, if considered worthy, are appended… to the list at https://tc39.github.io/ecma262/ and then progress to the specification.… It can parse (“read and understand”) modern code and rewrite it using older syntax constructs, so that… A transpiler would analyze our code and rewrite height ?? 100 into (height !… It “fills in” the gap and adds missing implementations.
Regular expressions are patterns that provide a powerful way to search and replace in text.… Regular Expressions.A regular expression (also “regexp”, or just “reg”) consists of a pattern and optional… The “long” syntax:
And the “short”… And, finally, if there are no matches, null is returned (doesn’t matter if there’s flag g or not).… A regular expression consists of a pattern and optional flags: g, i, m, u, s, y.
It stores the date, time and provides methods for date/time management.… We can set out-of-range values, and it will auto-adjust itself.… So it’s faster and doesn’t put pressure on garbage collection.… And then you probably won’t need microbenchmarks at all.… Date and time in JavaScript are represented with the Date object.
TextDecoder object allows one to read the value into an actual JavaScript string, given the buffer and… label – the encoding, utf-8 by default, but big5, windows-1251 and… …And then decode:
input – BufferSource… This options tells TextDecoder to memorize “unfinished” characters and decode them when the next chunk
A File object inherits from Blob and is extended with filesystem-related capabilities.… FileReader.FileReader is an object with the sole purpose of reading data from Blob (and hence File too… text string with the given encoding (utf-8 by default).
readAsDataURL(blob) – read the binary data and… The most widely used events are for sure load and error.… In addition to Blob methods and properties, File objects also have name and lastModified properties,
Let’s say we have a string like +7(903)-123-45-67 and want to find all numbers in it.… A quantifier is appended to a character (or a character class, or a [...] set etc) and specifies how… r looks for o followed by zero or one u, and then r.
So, colou?… r finds both color and colour:… Depends on how tolerant we can be to “extra” matches and whether it’s difficult or not to remove them
For instance, [a-z] is a character in range from a to z, and [0-5] is a digit from 0 to 5.… similar characters,
Join_Control (Join_C) – two special codes 200c and 200d, used in ligatures, e.g.… Unicode properties are covered in more details in the article Unicode: flag "u" and class \… They are denoted by a caret character ^ at the start and match any character except the given ones.… And if we need a backslash, then we use \\, and so on.
Specification.The ECMA-262 specification contains the most in-depth, detailed and formalized information… MDN (Mozilla) JavaScript Reference is the main manual with examples and other information.… To see their support among browser-based and other engines, see:
https://caniuse.com – per-feature tables… caniuse.com/#feat=cryptography.
https://kangax.github.io/compat-table – a table with language features and
Getters and setters.Accessor properties are represented by “getter” and “setter” methods.… It is readable and writable.… the access is done via getter and setter.… a setter and tweak its behavior.… We can try to find all such places and fix them, but that takes time and can be hard to do if that code
Run it and see what really happens.… and switches elsewhere.… ads and evils pages.… The main window and the popup can freely read and modify each other if they have the same origin.… Events focus and blur allow to track switching in and out of the window.
And it may be a better choice for such task.… down, and then keyup – when it’s released.
event.code and event.key.The key property of the event object… The event.key is exactly the character, and it will be different.… again, and then when it’s released we finally get keyup.… The browser opens the “Save Page” dialog (Ctrl+S)
…and so on.
The first thing to do is to locate quoted strings, and then we can replace them.… ; and her "broom".… So the first match is "witch" and her "broom".… and ??… , and so on… until it finally reaches " class="doc">.
But an object property is actually a more flexible and powerful thing.… In this chapter we’ll study additional configuration options, and in the next we’ll see how to invisibly… true, then listed in loops, otherwise not listed.
configurable – if true, the property can be deleted and… The returned value is a so-called “property descriptor” object: it contains the value and all the flags… returns all property descriptors including symbolic and non-enumerable ones.
Forms and control elements, such as <input> have a lot of special properties and events.… That’s a so-called “named collection”: it’s both named and ordered.… This is typical with radio buttons and checkboxes.… So a form references all elements, and elements reference the form.… We can use document.createElement('option') and set attributes manually.
So the sum is 284px plus left and right paddings, total 324px.… But as we know from the chapter Styles and classes, we can read CSS-height and width using getComputedStyle… And there’s one more reason: a scrollbar.… And clientWidth/clientHeight take that into account.… But Firefox shows 300px, while Chrome and Edge show less.
But most environments have the internal scheduler and provide these methods.… In particular, they are supported in all browsers and Node.js.
setTimeout.The syntax:… And here sayHi() runs the function, and the result of its execution is passed to setTimeout.… In this case the engine waits for func to complete, then checks the scheduler and if the time is up,… /setTimeout, an internal reference is created to it and saved in the scheduler.
And asynchronous generators make it even more convenient.… Let’s see a simple example first, to grasp the syntax, and then review a real-life use case.… It calls range[Symbol.asyncIterator]() once, and then its next() for values.… object, so it’s both synchronously (for..of) and asynchronously (for await..of) iterable.… Then we can use that link for the next request, to get more commits, and so on.
For instance, we have Article objects and need a function to compare them.… And for the second one we can make a static method of the class.… methods.Static properties and methods are inherited.… For instance, Animal.compare and Animal.planet in the code below are inherited and accessible as Rabbit.compare… As a result, inheritance works both for regular and static methods.
The for…of and for…in loops
A small announcement for advanced readers.… This article covers only basic loops: while, do..while and for(..;..;..).… See for…of and iterables for looping over arrays and iterable objects.
Otherwise, please read on.… , while it’s truthy, execute it again and again.… body
alert(i)
Runs again and again while the condition is truthy.
How do we find the width and height of the browser window?… How do we get the full width and height of the document, including the scrolled out part?… But there are additional methods and peculiarities to consider.… Width/height of the window.To get window width and height, we can use the clientWidth/clientHeight of… If it occupied some space, then that space is now free and the content “jumps” to fill it.
The “Same Origin” (same site) policy limits access of windows and frames to each other.… The idea is that if a user has two pages open: one from john-smith.com, and another one is gmail.com,… It has some JavaScript and a form.
Please note that nothing works.… both agree and call corresponding JavaScript functions.… It triggers when postMessage is called (and targetOrigin check is successful).
And then, only if onupgradeneeded handler finishes without errors, openRequest.onsuccess triggers, and… And it can’t be both version 1 and 2.… We should listen for it and close the old database connection (and probably suggest a page reload, to… And then we can do updates depending on what exists and what doesn’t.… , and we fail to do the 2nd.
They can be passed around, used as objects, and now we’ll see how to forward calls between them and decorate… …And for objects that are both iterable and array-like, such as a real array, we can use any of them,… Because we are calling hash(arguments), and arguments object is both iterable and array-like, but not… Append glue and this[1].
Append glue and this[2].
…Do so until this.length items are glued.… E.g. a decorator may count how many times a function was invoked and how much time it took, and expose
it is usually used to validate the form before sending it to the server or to abort the submission and… We can use it to dynamically create and send our own forms to server.… The handler can check the data, and if there are errors, show them and call event.preventDefault(), then… In the form below:
Go into the text field and press Enter.… Relation between submit and
We need to wait until the script loads, and only then we can call it.… It triggers after the script was loaded and executed.… …And what if the loading failed?… , save errors and provide an interface to access and analyze them.… Summary.Images <img>, external styles, scripts and other resources provide load and error events
Understanding how event loop works is important for optimizations, and sometimes for the right architecture… When a user moves their mouse, the task is to dispatch mousemove event and execute handlers.… …and so on.… …and so on.… And its overall execution time isn’t much longer.
The caret ^ and dollar $ characters have special meaning in a regexp. They are called “anchors”.… The caret ^ matches at the beginning of the text, and the dollar $ – at the end.… The pattern ^Mary means: “string start and… That is: two digits, then a colon, and then another two digits.… Anchors have “zero width”
Anchors ^ and $ are tests. They have zero width.
…and so on.
In this chapter we’ll learn how to do the same.… And also, how to pass arrays to such functions as parameters.… And it still works, we can find it in the old code.… And that would get ugly.
Spread syntax to the rescue!… and iterables.
If the regexp doesn’t have flag g, then it returns the first match as an array with capturing groups and… the regexp has flag g, then it returns an array of all matches as strings, without capturing groups and… The swiss army knife for searching and replacing.… It will be called for each match, and the returned value will be inserted as a replacement.… …And so on.
If there are no matches, regexp.exec returns null and resets regexp.lastIndex to 0.
A browser supports not only HTML, but also XML and SVG.… For instance, DOMString, boolean and so on.… For instance, let’s compare tagName and nodeName for the document and a comment node:… As the content is “zeroed-out” and rewritten from the scratch, all images and other resources will be… And so on.
And, as it happens with strings, that may lead to odd results.… We’ll see that a bit later, in the article Sets and ranges [...].… And Number property means that it’s a digit: maybe Arabic or Chinese, and so on.… …And so on.… and {n} we’ll see how to look for numbers that contain many digits.
Taking something and dragging and dropping it is a clear and simple way to do many things, from copying… , dragend, and so on.… So we hide it and immediately show again.… And handle the drop when it happens.… And so on.
Then your code will work well with both touch and mouse devices.… When the user moves and then removes a finger, we get pointermove and pointerup events with the same… ” process, and no more pointermove events are generated.… Now we can add the code to actually move the ball, and our drag’n’drop will work for mouse devices and… For drag’n’drops and complex touch interactions that the browser may decide to hijack and handle on its
Only first 50 results are shown.