High-level Javascript frameworks: Backbone vs. Ember vs. Knockout

This is a very general introduction to MV* Javascript frameworks. This card won't tell you anything new if you are already familiar with the products mentioned in the title.

As web applications move farther into the client, Javascript frameworks have sprung up that operate on a higher level of abstraction than DOM manipulation frameworks like jQuery and Prototype. Such high-level frameworks typically offer support for client-side view rendering, routing, data bindings, etc. This is useful, and when you write a moderately complex Javascript ...

Why your javascripts should be executed after the dom has been loaded

Most of the JavaScript snippets have code that manipulates the DOM. For that reason dom manipulating javascript code should have been executed after the DOM has loaded completely. That means when the browser has finished HTML parsing and built the DOM tree. At that time, you can manipualte the DOM although not all resources (like images) are fully loaded.

The following snippets show how you can do this with plain JavaScript, jquery or prototype ([dom ready ...

JavaScript: Don't throw synchronous exceptions from functions that return a Promise

TLDR: A function is hard to use when it sometimes returns a promise and sometimes throws an exception. When writing an async function, prefer to signal failure by returning a rejected promise.

The full story

When your function returns a promise ("async function"), try not to throw synchronous exceptions when encountering fatal errors.

So avoid this:

function foo(x) {
  if (!x) {
    throw "No x given"
  } else
    return new Promise(funct...

Drag'n'drop in trees: I went to town

For my Gem Session project Holly I ran the Ironman of drag'n'drop implementations:

  • Dragging in nested lists
  • User-definable order of items
  • Complicated item elements with super-custom CSS and other Javascript functionality
  • Items that can be both leaves and containers of other items
  • has_ancestry on the server side

Things I learned:

  • Be ready to write a lot of CSS. You need to indicate what is being dragged, where it will be dropped, if it is dropped above, below o...

How to access before/after pseudo element styles with JavaScript

Accessing pseudo elements via JavaScript or jQuery is often painful/impossible. However, accessing their styles is fairly simple.

Using getComputedStyle

First, find the element in question.

let element = document.querySelector('.my-element') // or $('.my-element').get(0) when using jQuery

Next, use JavaScript's getComputedStyle. It takes an optional 2nd argument to filter for pseudo elements.

let style = window.getComputedStyle(element, '::before')
let color = style.getPropertyValue('background-color...

Listening to bubbling events in Prototype is easy

If you come across an (older) application that is using Prototype instead of jQuery, you may often see events bound to single elements only, like this:

$('foo').observe('change', updateThings);
$('bar').observe('change', updateThings);
$('baz').observe('change', updateThings);

If you are calling only one method in each case, this is unnecessarily ugly. Also, when your page contents have been replaced via AJAX (like sections of a form after choosing something), those event hooks will no longer wo...

Check that an element is hidden via CSS with Spreewald

If you have content inside a page that is hidden by CSS, the following will work with Selenium, but not when using the Rack::Test driver. The Selenium driver correctly only considers text that is actually visible to a user.

Then I should not see "foobear"

This is because the Rack::Test driver does not know if an element is visible, and only looks at the DOM.

Spreewald offers steps to check that an element is hidden by CSS:

Then "foo" should be hidden

You can also check that an el...

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()

...

Colcade is a lightweight Masonry alternative

Masonry is a famous library to dynamically arrange a grid of items that have different aspect ratio, like horizontal and vertical images.
Colcade is an alternative masonry-layouting library, developed by the same developer, but with a more modern approach.

It is said to have better performance while being smaller and having no dependencies. It automagically detects jQuery and defines a jQuery initializer, if present.
However, it offers [a few less features](https:...

How to test print stylesheets with Cucumber and Capybara

A print stylesheet is easy to create. Choose a font suited for paper, hide some elements, done. Unfortunately print stylesheets often break as the application is developed further, because they are quickly forgotten and nobody bothers to check if their change breaks the print stylesheet.

This card describes how to write a simple Cucumber feature that tests some aspects of a print stylesheets. This way, the requirement of having a print stylesheet is manifested in your tests and cannot be inadvertedly removed from the code. Note that you can...

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

Howto: Select2 with AJAX

Select2 comes with AJAX support built in, using jQuery's AJAX methods.
...
For remote data sources only, Select2 does not create a new element until the item has been selected for the first time. This is done for performance reasons. Once an has been created, it will remain in the DOM even if the selection is later changed.

If you have a huge collection of records for your select2 input, you can populate it via AJAX in order to not pollute your HTML with lots of <option> elements.

All you have to do is to provide...

How to solve Selenium focus issues

Selenium cannot reliably control a browser when its window is not in focus, or when you accidentally interact with the browser frame. This will result in flickering tests, which are "randomly" red and green. In fact, this behavior is not random at all and completely depends on whether or not the browser window had focus at the time.

This card will give you a better understanding of Selenium focus issues, and what you can do to get your test suite stable again.

Preventing accidental interaction with the Selenium window
--------------------...

Jasmine: Testing AJAX calls that manipulate the DOM

Here is a Javascript function reloadUsers() that fetches a HTML snippet from the server using AJAX and replaces the current .users container in the DOM:

window.reloadUsers = ->
  $.get('/users').then (html) ->
    $('.users').html(html)

Testing this simple function poses a number of challenges:

  • It only works if there is a <div class="users">...</div> container in the current DOM. Obviously the Jasmine spec runner has no such container.
  • The code requests /users and we want to prevent network interaction in our uni...

Implementing social media "like" buttons: Everything you never wanted to know

So you client has asked you to implement a row of buttons to like the URL on Facebook, Twitter and Google+. Here are some things you should know about this.

0. Security considerations

Each "like" button is implemented by including a Javascript on your site. This means you are running fucking remote code on your page. You are giving Facebook, Twitter and Google+ full permission to e. g. copy user cookies. Check with your client if she is cool with that. Also note that if you're site is suggesting security by operating under HTTPS ...

IE11: Trigger native mouse events with Javascript

The attached Coffeescript helper will let you create mouse events:

$element = $('div')
Trigger.mouseover($element)
Trigger.mouseenter($element)
Trigger.mousedown($element)
Trigger.mouseup($element)
Trigger.mouseout($element)
Trigger.mouseleave($element)
Trigger.click($element)

The dispatched events are real DOM events, which will trigger both native and jQuery handlers.
jQuery's .trigger is simpler, but will only trigger event handlers that were bound by jQuery's .on.

Real user actions t...

Capturing signatures on a touch device

If you need to capture signatures on an IPad or similar device, you can use Thomas J Bradley's excellent Signature Pad plugin for jQuery.

To implement, just follow the steps on the Github page.

The form

If you have a model Signature with name: string, signature: text, you can use it with regular rails form like this:

- form_for @signature, :html => { :class => 'signature_form' } do |form|
  %dl
    %dt
      = form...

How to make select2 use a Bootstrap 4 theme

select2 is a great jQuery library to make (large) <select> fields more usable.

For Bootstrap 3 there is select2-bootstrap-theme.
It won't work for Bootstrap 4, but rchavik's fork does (at least with Bootstrap 4 Alpha 6, current version at time of writing this).

It is based on a solution by angel-vladov and adds a few fixes.

Use it by addi...

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...

pickadate.js

The mobile-friendly, responsive, and lightweight jQuery date & time input picker.

Does not depend on jQuery UI, but currently does not allow typing in the associated input field.

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.

How to click hidden submit buttons with Selenium

In your Cucumber features you can't really click hidden elements when using Selenium (it does work for a plain Webrat scenario, though).

Unfortunately you need to hack around it, like this:

When /^I press the hidden "([^\"]+)" submit button$/ do |label|
  page.evaluate_script <<-JS
    $('input[type=submit][value="#{label}"]').show().click();
  JS
end

If your button is nested into a container that is hidden this will not do the trick. You need a more complex method to also show surrounding containers:

When /^I pre...

How to preview an image before uploading it

When building a form with a file select field, you may want to offer your users a live preview before they upload the file to the server.

HTML5 via jQuery

Luckily, HTML5 has simple support for this. Just create an object URL and set it on an <img> tag's src attribute:

$('img').attr('src', URL.createObjectURL(this.files[0]))

Unpoly Compiler

As an Unpoly compiler, it looks like this:

up.compiler '[image_p...

Javascript equivalent of Ruby's array.collect(&:method)

The most common use case for Ruby's #collect is to call a method on each list element and collect the return values in a new array:

['hello', 'world', 'this', 'is', 'nice'].collect(&:length)
# => [5, 5, 4, 2, 4]

Although there is no equivalent to this idiom in naked Javascript, there is a way to collect object properties (but not method results) if you are using common Javascript libraries.

If you are using jQuery with the Underscore.js utility library, you can use [pluck](htt...