Using regular expressions in JavaScript
Regular expressions in Javascript are represented by a RegExp object. There also is a regex literal as in many other languages: /regex/. However, they are used slightly differently.
Regex literal
- Usage:
/foo+/ - Shorthand for creating a regular expression object
RegExp() object
- Usage:
RegExp("foo+")ornew RegExp("foo+") - No surrounding slashes required (they're the literal markers)
- Since the argument is a string, backslashes need to be escaped as well:
RegExp("\\d+")
Gotchas
- Regex objects [never eq...
IFrame Resizer
A JS library that allows you to embed an iframe that automatically shrinks or expands to match its content.
(Untried.)
jQuery: How to attach an event handler only once
With "attaching an event handler once" you possibly mean one of these two things:
Register a function for an event, and discard it once that event has happened
Use one instead of on.
$(element).one('eventName', function() { ... });
It has the same API has on.
When code is run multiple times that registers a function for an event, do that only once
With jQuery, you can de-register callbacks. You can use that to achieve registering a function only once.
function myAction() { ... }; // defined somewhere globally o...
Lazy-loading images
Note
This card does not reflect the current state of lazy loading technologies. The native lazy attribute could be used, which is supported by all major browsers since 2022.
Since images are magnitudes larger in file size than text (HTML, CSS, Javascript) is, loading the images of a large web page takes a significant amount of the total load time. When your internet connection is good, this is usually not an issue. However, users with limited bandwidth (i.e. on mobile) need to mine their data budget...
Ag: Very fast grep replacement
Ag (aka "the silver searcher") is a very fast replacement for grep.
It will parse your .gitignore for additional speedup. To ignore even more files (node_modules, *.min.js etc), add an .ignore with syntax identical to .gitignore.
See Faster Grepping in Vim for hints about vim integration.
AngularJS: How to force Content-Type on GET and DELETE requests
While you usually do not need a Content-Type on GET request (which have a blank body), an external API may still force you to send one.
Angular's $http service will strip that header when the request data (body) is blank. [1] This is possibly a misconception of RFC2616.
Here is how to send GET requests with a Content-Type header in Angular.
Example
Consider this request:
$http({ me...
Show or hide a jQuery element given a condition
If you have jQuery code like this:
if (condition) {
$element.show();
} else {
$element.hide();
}
... you can shorten this to:
$element.toggle(condition);
A case for Redactor
Redactor is yet another WYSIWYG editor. It definitely has its weak points, but I want to point out that it has clear strengths, too.
Pro
- Simple and beautiful interface.
- Outstandingly organized source code. Have never seen a JS library that was this structured.
- Clear, comprehensive and searchable API documentation. Filled with code examples.
- Easily customizable: specify toolbar buttons, pass various callbacks, etc.
- Features a collection of great [plugins](ht...
Keeping web applications fast
Our applications not only need to be functional, they need to be fast.
But, to quote Donald Knuth,
premature optimization is the root of all evil (or at least most of it) in programming
The reasoning is that you should not waste your time optimizing code where it does not even matter. However, I believe there are some kinds of optimizations you should do right away, because
- they are either obvious and easy
- or they are very hard to do optimize later
This is an attempt to list some of those things:
On the server
...
Escape a string for transportation in a URL
To safely transport an arbitrary string within a URL, you need to percent-encode characters that have a particular meaning in URLs, like & or =.
If you are using Rails URL helpers like movies_path(:query => ARBITRARY_STRING_HERE), Rails will take care of the encoding for you. If you are building URLs manually, you need to follow this guide.
Ruby
In Ruby, use CGI.escape:
# ✅ good
CGI.escape('foo=foo&bar=bar')
=> "foo%3Dfoo%26bar%3Dbar"
Do not ever use `URI.en...
Improving browser rendering performance
As the web is being used for more and more tasks, expectations rise. Not only should web pages offer rich interaction, they must be responsive in both size and interaction.
This imposes a paradoxon that needs to be solved by building performing applications. It's not enough any more to have your web site do crazy stuff, it is also required to do it crazy fast. This card is intended to give you an introduction to this emerging aspect of web development.
Read this introductory [performance study on Pinterest](http://www.smashingmagazine.com/...
Installing Node.js / npm under Ubuntu with nvm (with yarn)
I recommend install Node.js using nvm. This way you can have multiple Node versions in your ~/.nvm. You also won't need to install global packages with sudo anymore.
Node via nvm will automatically bring npm. yarn will automatically be available if corepack is enabled for node.
Installing nvm
DigitalOcean has a HOWTO for installing nvm on Ubuntu (16.04, [18.04](https://www.digitalocean.com/community/tutorials/how-to-...
Migrating legacy jQuery code to .on() and .off()
If you need to upgrade code that uses the old jQuery methods bind, delegate, live, unbind and die, the attached article has examples how to migrate to the new on and off versions.
Bootstrap 4 is coming
What's new
- Moved from Less to Sass. Bootstrap now compiles faster than ever thanks to Libsass, and we join an increasingly large community of Sass developers.
-
Improved grid system. We’ve added a new grid tier to better target mobile devices and completely overhauled our semantic mixins.
Opt-in flexbox support is here. The future is now—switch a boolean variable and recompile your CSS to take advantage of a flexbox-based grid system and components. - Dropped wells, thumbnails, and panels for cards. Cards are a brand new co...
Flash-Free Clipboard for the Web
Unfortunately, Web APIs haven’t provided the functionality to copy text to the clipboard through JavaScript, which is why visiting GitHub with Flash disabled shows an ugly grey box where the button is supposed to be. Fortunately, we have a solution. The editor APIs provide document.execCommand as an entry point for executing editor commands. The "copy" and cut" commands have previously been disabled for web pages, but with Firefox 41, which is currently in Beta, and slated to move to release in mid-September, it is becoming available to Ja...
include_tags with the asset pipeline
You can include files from app/assets or from the public folder with javascript_include_tag. The subtle difference that tells rails how to build the path correctly is a single slash at the beginning of the path:
<%= javascript_include_tag('ckeditor/config') %> # for assets/ckeditor/config.js
<%= javascript_include_tag('/ckeditor/ckeditor') %> # for public/ckeditor/ckeditor.js
This also applies to stylesheet_link_tag.
Note that when you refer to a Javascript or stylesheet in /assets you need to add it to [the list of asse...
Bootswatch: Paper
Free Bootstrap theme resembling Material Design.
Bootswatch offers Sass and Less files, so the theme can easily be integrated into your usual Rails application.
Implements only Bootstrap features which means that some Material stuff is missing, but also that you can easily use or replace the theme.
Does not come with extra JavaScript; some effects like button click ripples are implemented via CSS.
Also check out their other themes which can be used in a similar fashion.
Jasmine: Testing complex types for equality
Jasmine comes with two matchers that test for equality. The first is toBe:
expect(first).toBe(second)
toBe passes when first === second. Unfortunately this is useless for non-primitive values because JavaScript is a horrible language.
However, Jasmine comes with another matcher toEqual:
expect(first).toEqual(second)
This matcher behaves as a human would expect for types like the following:
- Arrays
- Objects
- Nested array/object constructs
- Regular expressions...
Mocking time in Jasmine specs
The easiest way to freeze or travel through time in a Jasmine spec is to use the built-in jasmine.clock().
- After
jasmine.clock().install()you can use it to controlsetTimeoutandsetInterval. - Using
jasmine.clock().mockDate()you can mocknew Date()(which returns the current time in Javascript)
While you can use SinonJS Fake timers, using the built-in Jasmine clock will save you an extra dependency.
Pierce through Javascript closures and access private symbols
If you are writing any amount of Javascript, you are probably using closures to hide local state, e.g. to have private methods.
In tests you may find it necessary to inspect a variable that is hidden behind a closure, or to mock a private method using Jasmine spies.
You can use the attached Knife helper to punch a hole into your closure, through which you can read, write or mock local symbols:
klass = (->
privateVariable = 0
privateMethod = ->
...
JavaScript events: target vs currentTarget
tl;dr: Use event.currentTarget unless you are absolutely certain that you need event.target.
Since it hasn't been written down in this deck before, here it goes:
When working with JavaScript Event objects, the DOM element that triggered the event is attached to them. [1]
However, there are 2 "opinions" on which element that would be:
- The element that the user interacted with (
event.target), - or the element that the event listener is bound to (
event.currentTarget).
Note that both can be, but not...