Guideline for moving from jQuery to vanilla JavaScript

jQuery is still a useful and pragmatic library, but chances are increasingly that you’re not dependent on using it in your projects to accomplish basic tasks like selecting elements, styling them, animating them, and fetching data—things that jQuery was great at. With broad browser support of ES6 (over 96% at the time of writing), now is probably a good time to move away from jQuery.

[Practical and clear reference with the most common jQuery patterns and their equivalent translations in vanilla JS](https://tobiasahlin.com/blog/move-from-j...

Jasmine: Test that an object is an instance of a given class

To test that an object was constructed by a given constructor function, use jasmine.any(Klass):

describe('plus()', function() {
  it ('returns a number', function() {
    let result = plus(1, 2)
    expect(result).toEqual(jasmine.any(Number))
  })
})

Also see Expecting objects as method invocation arguments.

screenfull.js: Simple wrapper for cross-browser usage of the JavaScript Fullscreen API

Using the JS fullscreen API is painful because all browers use different methods and events and you need to use lots of boilerplate code to make your application work in all browsers.

The "screenfull" library wraps that for you, including events.

Examples

The linked GitHub repo contains some information. You basically use the library like this:

// Make an element go fullscreen
screenfull.request(element)

// Leave fullscreen
screenfull.exit()

...

How to get the currently selected text in Javascript

Simple:

window.getSelection().toString();

Browser support: IE9+, Android 4.3+, Safari 5+

tesseract.js: Pure Javascript OCR for 62 Languages

This might be relevant for us since we're often managing customer documents in our apps.

I played around with the library and this is what I found:

  • A 200 DPI scan of an English letter (500 KB JPEG) was processed in ~6 seconds on my desktop PC. It does the heavy lifting in a Web worker so you're rendering thread isn't blocked.
  • It detected maybe 95% of the text flawlessly. It has difficulties with underlined text or tight table borders.
  • When you feed ...

Javascript: Read params from url

There is no build in functionally in jQuery and Prototype to extract params from a url.

  1. You can use this library (not tested): jquery-deparam

  2. Use Unpoly and the following code snippet

An intro to Javascript promises

Promises are the new way™ to express "Do this, and once you're done, do that". In contrast to callbacks, promises are easily chainable. From the readme of Q, an early implementer of the pattern:

The callback approach is called an “inversion of control”. A function that accepts a callback instead of a return value is saying, “Don’t call me, I’ll call you.”. Promises un-invert the inversion, cleanly separating the input arguments from control flow arguments. This simplifies the use and creation of APIs, p...

Javascript: Wait until an image has finished loading

The attached ImageLoader helper will start fetching an image and return an image that is resolved once the image is loaded:

ImageLoader.load('/my/image.png').then(function(image) {
  ...
});

The image argument that is yielded to the promise callback is an HTMLImageElement. This is the kind of object you get when you call new Image().

Delay your Jasmine tests until the document is ready

To delay your entire Jasmine test suite until the DOM is ready, add the following:

beforeAll(function(done) {
  $(done);
});

Infinitely nested hashes in Javascript (Coffeescript)

The NestedHash class allows you to read and write hashes of any depth. Examples:

hash = {}
NestedHash.write hash, 'a', 'b', 'c', 'value' # => { a: { b: { c: 'value' } } }
NestedHash.read hash, 'a', 'b', 'c' # => 'value'
NestedHash.read hash, 'a' # => { b: { c: 'value' } }
NestedHash.read hash, 'foo', 'bar' # => undefined

Inspired by victusfate.

Code

class @NestedHash

  @read: (objekt, keys...) ->
    if objekt and keys.length
      @read objekt[keys[0]], keys[1...]...
    ...

Jasmine: Reset the location when testing code that uses pushState / replaceState

When testing code that uses pushState / replaceState, your browser will appear to navigate away from http://localhost:3000/specs (or wherever you run your Jasmine tests). This is inconvenient, since reloading the document will no longer re-run the test suite.

To remedy this, copy the attached file to a place like spec/javascripts/helpers and #= require it from your tests. It will store the current location before every test and reset if afterwards (using location.replaceState).

BubbletreeJS: A Javascript data visualization library

BubbleTree is a library for interactive visualization of hierarchical data. Originally developed mainly for spending data, the library is now completely independent from the OpenSpending platform. BubbleTree is built on top of jQuery and RaphaelJS.

See the Demo or the tutorial.

Techniques for authentication in AngularJS applications

Article about implementing authentication (current_user) and authorization (access rights) in AngularJS.

Has an surprising amount of practical and understandable code.

Making Sass talk to JavaScript with JSON | CSS-Tricks

Crazy hack. Might be useful one day.

The code required has since been extracted into a library.

Don't use "self" as a Javascript variable

You might sometimes use self to capture the context of this before it is destroyed by some function.

Unfortunately self is also an alias for window, the global top-level object. Save your future self some headaches and use another name like me instead (Coffeescript chose to use _this).

Howto remove the location hash without causing the page to scroll

Set the hash to a dummy hash which doesn't hit any id at your page, for example:

window.location.hash = "_";

Note

  • If you'd set the hash to "" it causes the page to scroll to the top because the hash "#" by itself is equivalent to "_top".
  • If you'd set window.location.href = "..." to get rid of the "#", you cause the browser to reload the page what is most likely not intended.

Upgrading Rails 2 from 2.3.8 through 2.3.18 to Rails LTS

This card shows how to upgrade a Rails 2 application from Rails 2.3.8 through every single patch level up to 2.3.18, and then, hopefully, Rails LTS.

2.3.8 to 2.3.9

This release has many minor changes and fixes to prepare your application for Rails 3.

Step-by-step upgrade instructions:

  1. Upgrade rails gem
  2. Change your environment.rb so it says RAILS_GEM_VERSION = '2.3.9'
  3. Change your ...

Chart.js - a promising JavaScript charting library with MIT-license

Chart.js seems to be a good alternative to Google's Chart API and other commercial chart drawing libraries.

  • good looking charts
  • canvas based (means less memory consumptive, but no interactivity out of the box)
  • highly configurable
  • good API and documentation
  • just 4.5 kilobytes
  • MIT license
  • Browser support: all browsers supporting the canvas element (for IE8 and below, use the polyfill as describes in the [chart.js documentation...

Detect effective horizontal pixel width on a mobile device with Javascript

So you want to find out how many horizontal pixels you have available on a mobile device. This is super difficult because:

How to test if an element has scrollbars with JavaScript (Cucumber step inside)

The basic idea is pretty simple: an element's height is accessible via the offsetHeight property, its drawn height via scrollHeight -- if they are not the same, the browser shows scrollbars.

var hasScrollbars = element.scrollHeight != element.offsetHeight;

So, in order to say something like...

Then the element "#dialog_content" should not have scrollbars

... you can use this step (only for Selenium scenarios):

Then /^the element "([^\"]+)" should( not)? have scrollbars$/ do |selector, no_scrollbars|
  scroll_heig...

How to find out the currently focused DOM element with JavaScript

This works in all relevant browsers:

document.activeElement

You can use this in your Selenium steps, for example, to assert that a form field is or is not focused.

Updated: Check whether an element is visible or hidden with Javascript

  • Added information about what jQuery considers "visible"
  • Added a solution for Prototype
  • Added a patch for Prototype that replaces the useless Element#visible() method with an implementation that behaves like jQuery.