Tag Archives: jQuery

inlineEdit and AngularJS

Recently I used the inlineEdit plugin with a project that uses AngularJS. As the inlineEdit plugin only handles switching between non-editable and editable views and exposes the save/cancel actions it was pretty easy to integrate. What I ended up doing was wrap the inlineEdit plugin with a Directive that implements the ngModelController API.

Take a look at the demo

First steps to using jQuery with CoffeeScript

A colleague recently asked me how you typically write the jQuery DomReady and closure syntaxes with CoffeeScript. It’s actually quite simple but did require a bit of fiddling around to find the right recipe. So I thought I’d share this with you all just in case you’re wondering too!

DomReady:

# CoffeeScript
jQuery ($) ->
  # your code here!

// JavaScript
jQuery(function($) {
  // your code here!
});

DomReady v2:

# CoffeeScript
$(document).ready ->
  # your code here!

// JavaScript
$(document).ready(function() {
  // your code here!
});

Passing jQuery into a closure:

# CoffeeScript
(($) ->
  # your code here!
) jQuery

// JavaScript
(function($) {
  // your code here!
})(jQuery);

Bonus: Ternary statements

# CoffeeScript
a = if found then b else c

// JavaScript
a = found ? b : c;

Do you have a recipe for this too? What is it?

HTML5 Placeholders

HTML5 adds a new attribute to most form elements called a placeholder. Its purpose is to add a short hint inside data entry points that disappear on focus. This type of interaction isn’t new but is new to HTML as of version 5. For this reason not all browsers have implemented this feature. Try it to see which of your browsers support the following bit of code!

HTML

<input type="text" placeholder="click me!">

So now we have a problem. Some browsers support it and others don’t!? Foresee client issues? Not to worry, here’s a workaround using the latest jQuery 1.4 features!

JavaScript

jQuery(document).ready(function($) {

  // first check if placeholder attribute is supported
  if ($('<input/>')
        .attr('placeholder','')[0]
        .placeholder === undefined) {

    // text input placeholder
    $('input[placeholder]')
      .each(function() { 
        this.value === ''
          ? this.value = $(this).attr('placeholder')
          : false; 
      })
      .live('focusin focusout', function(event) {
        event.type == 'focusout' && this.value === '' 
          ? this.value = $(this).attr('placeholder')
          : this.value === $(this).attr('placeholder')
            ? this.value = '' 
            : false;
      });

  }

});

This is not a complete solution as there are other things to consider such as visual style and what happens when you submit the form. But I’ll let you mull over those. :)

Demo and code sample: http://jsbin.com/ujosa/edit

jQuery: Textarea maxlength

Being able to restrict the maximum length of user input from the interface directly is very convenient and practical in use. We do this a lot with input elements. Unfortunately textarea elements do not natively support the maxlength attribute. This attribute was finally added in HTML5 but at the time of writing Chrome is the only browser supporting it.

Naturally many have used JavaScript to rectify this problem and I’d be doing the same here. The difference is we won’t be putting anything special in the markup but will simply use the maxlength attribute within our textarea as if it’s native — like so:

HTML

<textarea cols="30" rows="5" maxlength="10"></textarea>

This is looking good for HTML5 compatibility. And here’s the magic:

jQuery

jQuery(function($) {

  // ignore these keys
  var ignore = [8,9,13,33,34,35,36,37,38,39,40,46];

  // use keypress instead of keydown as that's the only 
  // place keystrokes could be canceled in Opera
  var eventName = 'keypress';

  // handle textareas with maxlength attribute
  $('textarea[maxlength]')

    // this is where the magic happens
    .live(eventName, function(event) {
      var self = $(this),
          maxlength = self.attr('maxlength'),
          code = $.data(this, 'keycode');

      // check if maxlength has a value.
      // The value must be greater than 0
      if (maxlength && maxlength > 0) {

        // continue with this keystroke if maxlength
        // not reached or one of the ignored keys were pressed.
        return ( self.val().length < maxlength
                 || $.inArray(code, ignore) !== -1 );

      }
    })

    // store keyCode from keydown event for later use
    .live('keydown', function(event) {
      $.data(this, 'keycode', event.keyCode || event.which);
    });

});

See live example.

This code could probably be enhanced further by triggering custom events when the maximum length is reached or include a character counter of some sort within the keypress handler. Your imagination is the limit!

Tip: getting values from an options list

So, if you’ve ever converted an options list into a single array of values you might have intuitively done this:

var select = $('#mySelectElement')[0];
var values = new Array();
for (var i=0; i < select.length; i++) {
  values.push(select.options[i].value);
}

Pretty boring aye?

There is a snazzier (is that a word?) alternative, which is to use jQuery.map:

var select = $('#mySelectElement')[0];
var values = $.map(select.options, function(n) { 
    return n.value; 
});

OK, only one line saving but doesn’t that feel good?!?