Autonomía digital y tecnológica

Código e ideas para una internet distribuida

Linkoteca. Javascript

Detecting the Safari browser: The user-agent of the Safari browser is “Safari”. This value is passed to indexOf() method to detect this value in the user-agent string. One additional check is required in the case of the Safari browser as the user-agent of the Chrome browser also includes the Safari browser’s user-agent. If both the user-agents of Chrome and Safari are in the user-agent, it means that the browser is Chrome, and hence the Safari browser value is discarded.

interact.js takes a slightly different approach compared to most drag and drop libraries. To give you as much control as possible, it tries to provide a simple, flexible API that gives you all the pointer event data you’ll need to move elements around.

The library doesn’t even do any moving at all! This is great because you decide exactly what feedback your users get. You can drag elements, draw on a canvas or (if you really need to) scroll the page.

The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON.

const myList = document.querySelector("ul");
const myRequest = new Request("products.json");

  .then((response) => response.json())
  .then((data) => {
    for (const product of data.products) {
      const listItem = document.createElement("li"); 
      listItem.appendChild(document.createElement("strong")).textContent = product.Name; 
      listItem.append(` can be found in ${product.Location}. Cost: `); 
      listItem.appendChild(document.createElement("strong")).textContent = `£${product.Price}`; 

The Function.prototype.bind() method lets you establish a fixed this context for all subsequent calls — bypassing problems where it’s unclear what this will be, depending on the context from which your function was called. Note, however, that you’ll need to keep a reference to the listener around so you can remove it later.

class Something {
  name = "Something Good";
  constructor(element) {
    // bind causes a fixed `this` context to be assigned to `onclick2`
    this.onclick2 = this.onclick2.bind(this);
    element.addEventListener("click", this.onclick1, false);
    element.addEventListener("click", this.onclick2, false); // Trick
  onclick1(event) {
    console.log(; // undefined, as `this` is the element
  onclick2(event) {
    console.log(; // 'Something Good', as `this` is bound to the Something instance

const s = new Something(document.body);

Thousands of developers use Medusa’s open-source commerce modules and tools to build rich, reliable, and performant commerce applications without reinventing core commerce logic.

We build modularized commerce logic like carts, products, and order management and provide tools to orchestrate them for powerful ecommerce websites, POS applications, commerce-enabled products, and everything in between.

Our modules are incredibly portable and can run in modern JavaScript environments, unlocking new infrastructure for unparalleled scalability and performance, while bringing commerce enablement to new layers of your stack.

This tutorial is meant for D3 v5-v7.

This tutorial is a quick intro to D3.js, a Javascript library for creating interactive data visualizations in the browser. D3 is built on top of common web standards like HTML, CSS, and SVG.

This is not designed to be a deep dive — this tutorial will teach you how to learn D3 and give you a high-level understanding of this powerful tool.

Broadly speaking there are 4 steps to setting up a force simulation:

  • create an array of objects
  • call forceSimulation, passing in the array of objects
  • add one or more force functions (e.g. forceManyBody, forceCenter, forceCollide) to the system
  • set up a callback function to update the element positions after each tick

I’ve just had a nice experience improving and modernizing a large JavaScript codebase in a WordPress plugin. The original code was written in an old-fashioned way with jQuery in a single large file. Using modern EcmaScript and tools like Webpack, I was able to split it into modules and improve the code structure. The new code is much more readable and maintainable, and of course, fewer bugs. In this tutorial, I’ll show you how I did that.

ECMAScript 2015 or ES2015 is a significant update to the JavaScript programming language. It is the first major update to the language since ES5 which was standardized in 2009. Therefore, ES2015 is often called ES6.

cola.js (A.K.A. «WebCoLa») is an open-source JavaScript library for arranging your HTML5 documents and diagrams using constraint-based optimization techniques.

It works well with libraries like D3.js, svg.js, and Cytoscape.js. The core layout is based on a complete rewrite in Javascript of the C++ libcola library.

It also has an adaptor for d3.js that allows you to use cola as a drop-in replacement for the D3 force layout. The layout converges to a local optimum unlike the D3 force layout, which forces convergence through a simple annealing strategy. Thus, compared to D3 force layout:

Basic check is simple, wait for the ended event. This is so simple you can just google it.

Now to check that user played full video an extensive analysis would be needed checking if he played every second of it. That’s not necessary however, it should be enough that user:

  • played as many seconds as the video is long
  • played to the end of the video

This snippet demonstrates exactly that. The video will not be marked as fully played if you just skip to the end. Playing the beginning over and over will also not mark it fully played

In the first parts we focus on the basics. We set up a development environment with running compilation of our code. And the basics of how to register a block and the necessary PHP parts of it as well. We’ll learn about the huge library of components and methods available to us from WordPress Gutenberg.

Moving on we’ll learn about how to add sections and settings for our block in the editor sidebar (Inspector) as well as customizing the toolbar. Along the way we’ll touch a lot of different input types and how to use Gutenberg’s component for these. And of course we’ll learn how to save, update and output the saved information to our block – and how that works behind the scenes.

At the end we’ll look at more advanced things like dynamic blocks and how to use PHP to render the block output. And finally how to make post queries inside the editor – allowing the user to select a post from a list for render.

Extensibility is key, and we can’t build the next generation of the WordPress Editor without making it extensible. What does “making it extensible” mean? Does this mean providing hooks and filters in JavaScript the same way we do in PHP? Does this mean allowing plugins to extend and tweak any UI component used by Gutenberg? Does this mean adding filters to the REST API? Does this mean Giving access to an Editor object to manipulate the editor’s content?

There’s no clear answer to all these questions. Extensibility is a very difficult problem and unless you build it with real use-cases in mind, you’re more likely to get it wrong. (and being stuck with it for a long time).

Asynchronous requests will wait for a timer to finish or a request to respond while the rest of the code continues to execute. Then when the time is right a callback will spring these asynchronous requests into action.


One use for generators is that they allow you to have async code looking like sync.

Instead of returning with a return, generators have a yield statement. It stops the function execution until a .next is made for that function iteration. It is similar to .then promise that only executes when resolved comes back.


This method seems like a mix of generators with promises. You just have to tell your code what functions are to be async. And what part of the code will have to await for that promise to finish.

The async and await keywords are a great addition to Javascript. They make it easier to read (and write) code that runs asynchronously. That includes things like:

API calls (using fetch or a library like axios);
Timeouts (though these need a little extra work); or
Reading/writing files if you’re using NodeJS.

I’m going to assume you’re familiar with Promises and making a simple async/await call. Where it can get tricky is when we have a whole bunch of tasks in an array. You might run through the array expecting calls to run one-by-one. But instead, they run through all together and don’t wait for each individual item to resolve. Or, you might find yourself with the opposite problem. You run through your array in a loop, wanting them to run in parallel. But instead, it waits and does them one by one. And sometimes, you try something and it doesn’t work at all. The program just continues after the loop instead of waiting until the calls are all done. You end up wondering if there’s something you’re missing.

Promises simplify deferred and asynchronous computations. A promise represents an operation that hasn’t completed yet.

A promise can be:

fulfilled – The action relating to the promise succeeded
rejected – The action relating to the promise failed
pending – Hasn’t fulfilled or rejected yet
settled – Has fulfilled or rejected

Promise is used to overcome issues with multiple callbacks and provide better way to manage success and error conditions.

Promise is an object which is returned by the async function like ajax. Promise object has three states

pending :- means the async operation is going on.
resovled :- async operation is completed successfully.
rejected :- async operation is completed with error.

There are two parts using a promise object. Inside async function (Part1) and where its called (Part2).

Part1 — Inside Async function,

Promise object is created.
Async function returns the promise object
If async is done successfully, promise object is resolved by calling its resolve method.
If async is done with error, promise object is rejected by calling its rejected method.

Part2 — Outside Async function

Call the function and get the promise object
Attach success handler, error handler on the promise object using then method

Cross Domain Call

By Default, AJAX cannot make cross domain call, browser will reject the calls to the different domain. In order to make cross domain call there are two options

Using CORS

Both the options requires some server changes. It cannot be done purely using javascript.

CORS is the new way to deal with cross origin AJAX request. github api are CORS enabled. In order to enable CORS, response should contain Access-Control-Allow-Origin header with the domain value or * to work for all. Github has set as *.

JSONP can also be used if CORS cannot be enabled by server or for old browsers. JSONP actually uses script tag to get the data from the server. Script is allowed to be fetched from any domain, So in JSONP, we need to create a script with the url as src and the server has to wrap the response in a callback function. Response sent by server is actually a javascript code which contains data inside a wrapper function. In JSONP, there is no ajax call being made.

Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

A common need is to execute two or more asynchronous operations back to back, where each subsequent operation starts when the previous operation succeeds, with the result from the previous step. We accomplish this by creating a promise chain.

Promises solve a fundamental flaw with the callback pyramid of doom, by catching all errors, even thrown exceptions and programming errors. This is essential for functional composition of asynchronous operations.

First I take the whole CSV file and split it into an array of lines. Then, I take the first line, which should be the headers, and split that by a comma into an array. Then, I loop through all the lines (skipping the first one) and inside, I loop through the headers and assign the values from each line to the proper object parameters. At this point, you probably want to just return the JavaScript object, but you can also JSON.stringify the result and return the JSON object.

Building cross-platform desktop applications comes with a unique set of challenges that can stand in your way when you are trying to transform your ideas into software. Web apps avoid some of these hurdles, but they have limitations that make them impractical for building native desktop applications. Electron lets you harness the best parts of these technologies to build beautiful, cross-platform desktop applications using HTML, JavaScript, and CSS.

This is part of a series of examples that describe the basic operation of the D3.js force layout.

…linkDistance tells the force layout the desired distance between connected nodes. It may seem strange that D3 doesn’t simply compel all links to be that distance. The force layout, however, takes other factors into account as well, which sometimes prevents it from achieving the exact link distance in all cases.

…charge, so named because it’s a property that acts like electrical charge on the nodes. With force-directed graphs in particular, charge causes nodes in the graph to repel each other. This behavior is generally desirable because it tends to prevent the nodes from overlapping each other in the visualization.

It only does PNG, but Firefox has a way to capture the whole page built in: Shift-F2 brings up a command prompt, which includes a screenshot command. For instance, screenshot –clipboard –fullpage as I was writing this answer produced

If you want something designed to be automated, phantomjs has page.render() which takes a filename and an optional options object, with format and quality entries; the example given is

page.render('google_home.jpeg', {format: 'jpeg', quality: '100'});