Sizzle JavaScript Selector Library

A pure-JavaScript CSS selector engine

Handy! RGB to HSL and RGB to HSV color model conversion algorithms in JavaScript - Axon Flux // A Ruby on Rails Blog

Here is a set of additive color model conversion algorithms that I found published on Wikipedia and have implemented in JavaScript.

Solutoire.com › Flotr Javascript Plotting Library

Flotr is a javascript plotting library based on the Prototype Javascript Framework (version 1.6.0.2 at the moment) and inspired by Flot (written by Ole Laursen).

Should You Use JavaScript Library CDNs? « Lickity Split

sing Google’s JavaScript Library CDN comes with a 1/3 of a second tax on missing. (Note that a tax like this applies to opening connections to a any new host: JavaScript Library CDNs, advertisers, analytics and visitor tracking, etc. This is why you should try to reduce the number of different hostnames you serve content from.)

What's wrong with defining JavaScript variables within if blocks? - Stack Overflow

Because javascript has something called "Hoisting" which makes your code do things it doesn't look like it should be doing. Basically, that means a javascript interpreter will move all var declarations, regardless of where they are in the body of a function, to the top of the function body.

Guide to localizing a Rails application

Localizing a non-trivial application can be a huge undertaking. This card will give you an overview over the many components that are affected.

When you are asked to give an estimate for the effort involved, go through the list below and check which points are covered by your requirements. Work with a developer who has done a full-app localization before and assign an hour estimate to each of these points.

Static text

  • Static strings and template text in app must be translated: Screens, mailer templates, PDF templates, helpe...

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.

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

Speed up your websites: Put JavaScripts at bottom

For websites that don't do JavaScript rendering on the client, it's best practice to put script tags at the bottom of the HTML. This way, the page can start to render before scripts have been loaded and run.

The caveat is that you also have to move all other script tags from your views to the bottom of the page. This can be done with helpers.

How to implement

  1. Add the attached javascript_helper to your app.
  2. Move your `javascript_i...

Operators "in" and "of" are very inconsistent between CoffeeScript and JavaScript

CoffeeScript and JavaScript (ECMAScript) both have operators in and of. Each language use them for more than one purpose. There is not a single case where the same operator can be used for the same purpose in both languages.

Check if an object (or its prototype) has a property

CoffeeScript

var hasFoo = 'foo' of object

JavaScript

var hasFoo = 'foo' in object;

Iterate through all properties of an object
================================...

The Plight of Pinocchio: JavaScript's quest to become a real language - opensoul.org

Great presentation about writing Javascript like you write everything else: Well-structured and tested.

JavaScript is no longer a toy language. Many of our applications can’t function without it. If we are going to use JavaScript to do real things, we need to treat it like a real language, adopting the same practices we use with real languages.

This framework agnostic talk takes a serious look at how we develop JavaScript applications. Despite its prototypical nature, good object-oriented programming principles are still relevant. The...

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

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

Reading and writing cookies in JavaScript

You can use JavaScript to get or set cookie values on the client.

Using the vanilla JavaScript API

In JavaScript, document.cookie is an accessor to all cookies on the current site. It looks like a String, but its setter is actually more powerful.

When setting cookies this way, remember to set the path=/ option.

Reading cookies

A result may look like this:

hello=universe; foo=bar

This means that there are 2 cookies: "hello" with value "universe", and "foo" with value "bar...

Compiling Javascript template functions with the asset pipeline

The asset pipeline (which is actually backed by sprockets) has a nice feature where templates ending in .jst are compiled into Javascript template functions. These templates can be rendered by calling JST['path/to/template'](template: 'variables'):

<!-- templates/hello.jst.ejs -->
<div>Hello, <span><%= name %></span>!</div>

// application.js
//= require templates/hello
$("#hello").html(JST["templates/hello"]({ name: "Sam" }));

Whatever is in the <% ... %> is evaluated in Javascript...

JavaScript “Stale Practices” | benmccormick.org

The linked article lists a number of techniques that were best practices with ES5, but have better alternatives in modern JavaScript.

Best practices don’t last forever. This is especially true when a field is changing fast, and JavaScript development has changed a lot over the past 10 years. The old best practices go stale, and new ones take their place. Here are 5 JavaScript best practices that have gone stale recently.

JavaScript bookmarklet to click an element and copy its text contents

Here is some JavaScript code that allows you to click the screen and get the clicked element's text contents (or value, in case of inputs).

The approach is simple: we place an overlay so you don't really click the target element. When you click the overlay, we look up the element underneath it and show its text in a browser dialog. You can then copy it from there.

While moving the mouse, the detected element is highlighted.

Here is the one-liner URL that you can store as a bookmark. Place it in your bookmarks bar and click it to activate....

Enable CSRF protection in Javascript tests

You might not know that Rails disables CSRF protection in tests. This means that if you accidentally forget to send the CSRF token for non-GET requests, your tests will be green even though your application is completely broken (a failed CSRF check usually logs out the user). Rails probably does this because CSRF protection sort of requires Javascript.

You want to enable CSRF protection in Cucumber scenarios that can speak Javascript. To do so, copy the a...

Writing Fast, Memory-Efficient JavaScript

JavaScript engines such as Google’s V8 (Chrome, Node) are specifically designed for the fast execution of large JavaScript applications. As you develop, if you care about memory usage and performance, you should be aware of some of what’s going on in your user’s browser’s JavaScript engine behind the scenes.

JavaScript: Hash/Object with default value

You can easily have a JavaScript hash/object that returns a default value for unset keys/properties -- as long as you need to support only recent browsers.

The key are JavaScript proxies from ECMAScript 6 that allow implementing a custom getter method. They work like this:

var hash = new Proxy({}, {
  get: function(object, property) {
    return object.hasOwnProperty(property) ? object[property] : 'hello';
  }
});

When you set a key,...

How to human-join an array in JavaScript

To simulate Rails' to_sentence in your JavaScript application, you can use these few lines of CoffeeScript code:

joinSentence = (array) ->
  if array.length > 1
    array[0..-2].join(', ') + ', and ' + array[-1..]
  else
    array.join ', '

Examples:

> joinSentence(['cats', 'dogs', 'pandas'])
# => 'cats, dogs, and pandas'

^
> joinSentence(['llamas'])
# => 'llamas'

Here is some plain JavaScript, should you prefer that:

function joinSentence(array) {
  if (array.length > 1) {
    return ar...

Beware: Coffeescript "in" is not the Javascript "in"

The Javascript in operator does what Hash#has_key? does in Ruby: Return whether an object has a property.
However, Coffeescript has its own in operator that checks for array inclusion. To check whether an object has a property, use of:

Javascript

'name' in {name: 'Horst'} # => true

Coffeescript

# wrong
'name' in {name: 'Horst'} # => false

# correct
'name' of {name: 'Horst'} # => true
1 in [1,2,3] # => true

True story.

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

Convert primitive Ruby structures into Javascript

Controller responses often include Javascript code that contains values from Ruby variables. E.g. you want to call a Javascript function foo(...) with the argument stored in the Ruby variable @foo. You can do this by using ERB tags (<%= ruby_expression %>) or, in Haml, interpolation syntax (#{ruby_expression}).

In any case you will take care of proper quoting and escaping of quotes, line feeds, etc. A convenient way to do this is to use Object#json, which is defined for Ruby strings, numb...