Flexible overflow handling with CSS and JavaScript

You can use text-overflow to truncate a text using CSS but it does not fit fancy requirements.

Here is a hack for the special case where you want to truncate one of two strings in one line that can both vary in length, while fully keeping one of them. See this example screenshot where we never want to show an ellipsis for the distance:

![Flexible overflow with optional ellipsis](https://makandracards.com/makandra/5885-a-flexible-overflow-ellipsis/at...

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'

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

Single step and slow motion for cucumber scenarios using @javascript selenium

Single step and slow motion for Cucumber scenarios can come in handy, especially in @javascript scenarios.

# features/support/examiners.rb
AfterStep('@slow_motion') do
  sleep 2
end

AfterStep('@single_step') do
  print "Single Stepping. Hit enter to continue"
  STDIN.getc
end

If you're using spreewald, these tags are available as @slow-motion and @single-step (with dashes instead of underscores).

Note: You can also [prevent the selenium webbrowser wind...

Hoptoad and Javascript, Sitting in a Tree, S-E-N-D-I-N-G - GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS

We didn’t want to leave front-end developers in the dark when their Javascript throws errors, so we’ve added a Hoptoad notifier for Javascript!

Merging two JavaScript objects

Let's say you want to merge the properties of two JavaScript objects:

let a = { foo: 1, bar: 2 }
let b = { bar: 3, baz: 4 }

let merged = merge(a, b) // => { foo: 1, bar: 3, baz: 4 }

Depending on your build, there are several ways to implement merge().

When you have ES6

When you have an ES6 transpiler or don't support IE11, you may use the spread operator (...) to expand both objects into a new object literal:

let merg...

JavaScript Coordinates

To move elements around we should be familiar with coordinates. Most JavaScript methods deal with one of two coordinate systems:

  • Relative to the window(or another viewport) top/left.
  • Relative to the document top/left.
    It’s important to understand the difference and which type is where.

JavaScript Start-up Performance

As web developers, we know how easy it is to end up with web page bloat. But loading a webpage is much more than shipping bytes down the wire. Once the browser has downloaded our page’s scripts it then has to parse, interpret & run them. In this post, we’ll dive into this phase for JavaScript, why it might be slowing down your app’s start-up & how you can fix it.

The article author also tested 6000+ production sites for load times. Apps became interactive in 8 seconds on desktop (using cable) and 16 seconds on mobile (Moto G4 over 3G).

Represent astral Unicode characters in Javascript, HTML or Ruby

Here is a symbol of an eight note: ♪

Its two-byte hex representation is 0x266A.

This card describes how to create a string with this symbol in various languages.

All languages

Since our tool chain (editors, languages, databases, browsers) is UTF-8 aware (or at least doesn't mangle bytes), you can usually get away with just pasting the symbol verbatim:

note = '♪'

This is great for shapes that are easily recognized by your fellow programmers.
It's not...

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

RaphaelJS: A Javascript vector graphics library

Raphaël is a small JavaScript library that should simplify your work with vector graphics on the web. If you want to create your own specific chart or image crop and rotate widget, for example, you can achieve it simply and easily with this library.

JavaScript: How to check if an object is NaN

JavaScript's NaN ("Not a Number") is hard to compare against. It never equals anything, not even itself:

NaN === NaN;        // false
Number.NaN === NaN; // false

There is the isNaN method, but it is not really what you are looking for:

isNaN(NaN)     // true
isNaN('hello') // true

Option 1: ES6

The Object.is() method determines whether two values are the same value. It even works for NaN:

Object.is(NaN, NaN) // true

Option 2: ES5

The example above shows that simply using isNaN would match other ...

Dealing with "TypeError: Converting circular structure to JSON" on JavaScript

JavaScript structures that include circular references can't be serialized with a"plain" JSON.stringify. Example:

a = { name: 'Groucho' };
b = { name: 'Harpo', sibling: a };
a.sibling = b;

Doing a JSON.stringify(a) will throw an error:

TypeError: Converting circular structure to JSON

There is not much you can do about that except specifying a custom serializer function that detects and cleans up circular references. There are existing solutions so you do not need to think of one yourself, like <https://githu...

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.

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

Howto prompt before accidentally discarding unsaved changes with JavaScript

Ask before leaving an unsaved CKEditor

Vanilla JavaScript way, but removes any other onbeforeunload handlers:

  $(function(){
    document.body.onbeforeunload = function() {
      for(editorName in CKEDITOR.instances) {
        if (CKEDITOR.instances[editorName].checkDirty()) {
          return "Unsaved changes present!"
        }
      }
    }
  }

A robuster implementation example

Note: Don't forget to mark the 'search as you type' forms with the skip_pending_changes_warning class.

var WarnBeforeAccidentallyDiscard...

JavaScript: How to generate a regular expression from a string

Getting a regular expression from a string in JavaScript is quite simple:

new RegExp('Hello Universe');
# => /Hello Universe/

You can also use special characters:

new RegExp('^(\\d+) users')
# => /^(\d+) users/

Our expression above now works only at the beginning of the matched string, looks for a number (\d+ [1]) and also captures that. Sweet.

However, mind that your input will not be magically escaped because of that:

new RegExp('makandra.com')
# => /makandra.com/

The above expression would match "`...

Moment.js - A lightweight javascript date library

A lightweight javascript date library for parsing, manipulating, and formatting dates.

Prevent the selenium webbrowser window from closing after a failed @javascript step

When cucumber encounters a failing step in a @javascript feature, the selenium browser window instantly closes. Sometimes you do not want that, because you need to see what is going on. You can click through the data your feature created, when you add the following file to your features/support directory:

#features/support/examiners.rb

After('@leave_the_window_open') do |scenario|
  if scenario.respond_to?(:status) && scenario.status == :failed
    print "Step Failed. Press return to close browser"
    STDIN.getc
  ...

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.

How to emulate simple classes with plain JavaScript

If you want a class-like construct in JavaScript, you can use the module pattern below. The module pattern gives you basic class concepts like a constructor, private state, public methods.

Since the module pattern only uses basic JavaScript, your code will run in any browser. You don't need CoffeeScript or an ES6 transpiler like Babel.

A cosmetic benefit is that the module pattern works without the use of this or prototypes.

Example

Here is an example for a Ruby class that we want to translate into Javascript using the module patter...