Validatious 2.0 - Easy form validation with unobtrusive JavaScript

validate( "email".is("required").andIsAn("email") );

jspdf - Project Hosting on Google Code

jsPDF is an open-source library for generating PDF documents using nothing but Javascript. You can use it in a Firefox extension, in Server Side Javascript and with Data URIs in some browsers.

Underscore.js

Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. It's the tie to go along with jQuery's tux.

Datejs - An open-source JavaScript Date Library

Comprehensive, yet simple, stealthy and fast. Datejs has passed all trials and is ready to strike. Datejs doesn’t just parse strings, it slices them cleanly in two.

jbarnette's johnson at master - GitHub

Johnson wraps JavaScript in a loving Ruby embrace. It embeds the Mozilla SpiderMonkey JavaScript runtime as a C extension.

JavaScript: How to log execution times to your browser console

If you are trying to inspect timings in JavaScript, you can use console.time and console.timeEnd which will write to your browser console.

Example:

console.time('lengthy calculation');
lengthyCalculation();
console.timeEnd('lengthy calculation');

lengthy calculation: 1.337ms

Note that this allows using console.timeEnd in another context which is helpful when you are doing things asynchronously, or just in different places.

Works in all browsers, including recent Internet Explorers. For older IEs, you may activate...

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

Rails 3.1 error message: Could not find a JavaScript runtime

After starting the Rails server in a freshly generated Rails 3.1 project you could see an error message such as

/usr/lib/ruby/gems/1.8/gems/execjs-1.3.0/lib/execjs/runtimes.rb:50:in `autodetect': Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)

Just add a JavaScript runtime to your Gemfile and the error vanishes.

Examples:

gem 'therubyracer'
gem 'extjs'

What `var` actually does in Javascript

TL;DR: Variables not declared using var are stored outside the current scope, most likely in the global scope (which is window in web-browsers).


Declaring a variable in Javascript is done like var x = 5. This creates a new variable in the current scope (e.g. the function you're in). What happens when don't use var?

Javascript needs to be clever when you do an assignment without declaring a variable, e.g. x = 7. To find that variable,

  • it first looks up x in the current scope
  • next, it goes up the scope chain, lookin...

JavaScript dependency management and concatenation: Sprockets

Sprockets is a Ruby library that preprocesses and concatenates JavaScript source files. It takes any number of source files and preprocesses them line-by-line in order to build a single concatenation. Specially formatted lines act as directives to the Sprockets preprocessor, telling it to require the contents of another file or library first or to provide a set of asset files (such as images or stylesheets) to the document root.

TodoMVC - A common learning application for popular JavaScript MV* frameworks

Developers these days are spoiled with choice when it comes to selecting an MV* framework for structuring and organizing JavaScript web apps. Backbone, Spine, Ember (SproutCore 2.0), JavaScriptMVC... the list of new and stable solutions goes on and on, but just how do you decide on which to use in a sea of so many options?

To help solve this problem, we created TodoMVC - a project which offers the same Todo application implemented using MV* concepts in most of the popular JavaScript MV* frameworks of today.

Solutions look and feel the same...

JavaScript Garden

JavaScript Garden is a growing collection of documentation about the most quirky parts of the JavaScript programming language. It gives advice to avoid common mistakes, subtle bugs, as well as performance issues and bad practices that non-expert JavaScript programmers may encounter on their endeavours into the depths of the language.

JavaScript Garden does not aim to teach you JavaScript. Former knowledge of the language is strongly recommended in order to understand the topics covered in this guide

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

simple_format helper for Javascript

The Javascript code below is a rough equivalent to the simple_format helper that ships with Rails:

function simpleFormat(str) {
  str = str.replace(/\r\n?/, "\n");
  str = $.trim(str);
  if (str.length > 0) {
    str = str.replace(/\n\n+/g, '</p><p>');
    str = str.replace(/\n/g, '<br />');
    str = '<p>' + str + '</p>';
  }
  return str;
}

Unlike the Rails helper, this does not preserve whitespace. You probably don't care.

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.

Handling Keyboard Shortcuts in JavaScript

Despite the many JavaScript libraries that are available today, I cannot find one that makes it easy to add keyboard shortcuts(or accelerators) to your javascript app. This is because keyboard shortcuts where only used in JavaScript games - no serious web application used keyboard shortcuts to navigate around its interface. But Google apps like Google Reader and Gmail changed that. So, I have created a function to make adding shortcuts to your application much easier.

Cucumber: Detect if the current Capybara driver supports Javascript

Copy the attached file to features/support. This gets you a convenience method:

Capybara.javascript_test?

Is true for Selenium, capybara-webkit, Poltergeist and a custom driver called :chrome (which we sometimes like to use for Selenium+Chrome).

Similar sounding but completely different card: Detect if a Javascript is running under Selenium WebDriver (with Rails)

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:

Cucumber step to manually trigger javascript events in Selenium scenarios (using jQuery)

When you cannot make Selenium trigger events you rely on (e.g. a "change" event when filling in a form field), trigger it yourself using this step:

When /^I manually trigger a (".*?") event on (".*?")$/ do |event, selector|
  page.execute_script("jQuery(#{selector}).trigger(#{event})")
end

Note that this only triggers events that were registered through jQuery. Events registered through CSS or the native Javascript registry will not trigger.

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

Chosen - makes select boxes better

Chosen is a JavaScript plugin that makes long, unwieldy select boxes much more user-friendly. It is currently available in both jQuery and Prototype flavors.