HowTo: Revert local changes in Git

Found this answer on Stack Overflow very useful, so thought I'd share it here:

If you want to revert changes made to your working copy, do this:

git checkout .

If you want to revert changes made to the index (i.e., that you have added), do this:

git reset

If you want to revert a change that you have committed, do this:

git revert ...

Source: How to revert all local changes in a GIT managed project to previous state ?

How to get Fancybox 1.3.1 to stay put!

I recently had a need to use a Fixed position overlay and found that Fancybox breaks if I set #fancybox-wrap to position:fixed. I believe the centerOnScroll option was supposed to solve this problem by recalculating the absolute position of #fancybox-wrap upon scrolling. The problem with this approach is that the overlay 'shudders' or 'feels jumpy' when you scroll in Firefox, Opera and IE7+.

Luckily the fix is actually pretty simple with the following steps:

1. Get a copy of the source code - jquery.fancybox-1.3.1.zip

2. Do a in-code-search

Open jquery.fancybox-1.3.1.js and look for the fancybox_get_viewport function (should be around line 56), the function should look like this:

fancybox_get_viewport = function() {
  return [ $(window).width(), $(window).height(), $(document).scrollLeft(), $(document).scrollTop() ];
},

3. Change it to look like this:

fancybox_get_viewport = function() {
  var isFixed = wrap.css('position') === 'fixed'; // add support for fixed positioning
  return [ $(window).width(), $(window).height(), isFixed ? 0 : $(document).scrollLeft(), isFixed ? 0 : $(document).scrollTop() ];
},

4. Add some CSS

Add the following clauses to your CSS files (ensure these clauses load after the jquery.fancybox-1.3.1.css file):

#fancybox-wrap {
  position: fixed;
}
* html #fancybox-wrap {	/* IE6 */
  position: absolute;
}

That's it!

Basically what the fix does is detect whether the wrapper is a fixed position element, if so it would return 0 for the scrollLeft and scrollTop values of the viewport. So even if you're not using a fixed position element you can add this fix in as it's non-destructive.

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?!?

Happy Birthday Google Chrome!

Wow, it's been a year already? Time certainly flies when you're having fun! It seems the Google Chrome team have been hard at work! They've finally made a version of Google Chrome for Mac and Linux which you could download from the Dev channel.

Had a quick test and found Print and Application shortcuts haven't been implemented yet. Chrome also died on me a few times unexpectedly (doesn't seem to cope too well with our QUnit test pages). Overall I like the minimal interface and speedier JavaScript response times. It could only get better!

Zend Server CE and Snow Leopard Problem

There's a compatibility issue with the Java Bridge in Zend Server CE which results in failure of the ZendServer admin interface. A temporary fix could be found at http://forums.zend.com/viewtopic.php?f=44&t=1115

I found this out the hard way - reinstalled and digged the internals before realizing it was a compatibility issue. I hope the Zend guys fix this soon!

Oh, I'm on Zend Server CE 4.0.5

Labs: UI inlineEdit

After my last tutorial on building a simple inlineEdit plugin I converted the concepts into a UI widget. It's now sitting in labs for you to use, pick apart and devour:

http://jquery-ui.googlecode.com/svn/branches/labs/inlineedit/demo.html

If you inspect the source code you will notice the structure is quite different. It's actually pretty much the same functionality wise but I have separated each piece into smaller chunks. This makes it easier to extend in future (I plan to write more on ways to extend UI widgets in another post).

Here's a quick peek at the features:

  • Basic inline editing - click, edit, save
  • Ability to save on pressing ENTER key
  • Cancel by un-focussing the input or clicking cancel
  • ThemeRoller ready
  • Customisable empty placeholder
  • Save and Cancel callbacks
  • Cancelable Save callback (so you could script a cancel action)

As usual please feedback and help improve this widget either by commenting here or on the InlineEdit design & planning page

Enjoy!

Tip: Obtaining Request Parameters in Zend_View

I found it virtually impossible to obtain GET or POST request parameters in Zend_View without resorting to accessing the $_GET or $_POST variables. Directly accessing these variables within Zend_View is bad practice so it's been suppressed on purpose to keep processing where it should be - within the Controller. However it is possible to get hold of these variables properly and that is to pass them from the Controller.

Example. You have a query string that looks like this ?keyword=test and want to show it in your view, here's what to do:

MyController.php

public function indexAction() {
  $this->view->request = $this->getRequest();
}

my-controller/index.phtml

The keyword is <?= $this->request->keyword ?>

Thanks!

jQuery Inline Edit tutorial

A friend recently asked me to review his edit-in-place code which turned out to be a modification of the one found at http://docs.jquery.com/Tutorials:Edit_in_Place_with_Ajax. Reading the tutorial on that page I asked myself how I would do this differently? Defining a global setClickable() function and then calling $('#editInPlace").click() is totally uncool, essentially limiting yourself to one edit-in-place area per page.

Since the concept of edit-in-place is so simple and the implementation should be likewise I want to try and tackle this as a tutorial by going through concepts and teaching to build from scratch.

The concept

There's a piece of text on a page, e.g. a heading or paragraph, looking plain and un-interesting. When you hover over it however a visual highlight, usually pale yellow, indicates that it's something special - an editable region. You then click on the text and it magically transforms into an editable box with save and cancel buttons tagged at the end. On clicking either save or cancel the editable box transforms back into its original form with text updated if saved.

The build

What we want to do is put these concepts into code whilst building something that's re-usable. A plugin will do the trick! Let's call our plugin inlineEdit.

We are only 3 steps away from achieving our goal! Follow along...

Step 1: Getting the basics right

The basic functionality consists of a static text element (span, div etc...) that can transforms into an input element on click. And on hover the text element will highlight to indicate special interactions.

Here's our first pass: Basic Interaction

Code explanation: Our plugin accepts a CSS class name defined in a stylesheet which is used to toggle the text element's classname - a class defining a background-color typically #ffC is sufficient for this. On clicking we replace the entire contents of the original text element with an input element and pass the original content into the input as its value. For now changes are saved when the input loses focus.

Step 2: Save, Cancel & Callbacks

As you may notice above we saved on blur and there is no way of canceling changes. Let's improve the interaction by adding a save button. This is important as you'd want to do something with the changes or allow a user to manually cancel. Every application does something different at the saving stage so we'll simply define a save callback and let the implementer decide what to do on save, be it Ajax post or what not. The save action is also cancelable by returning false inside the callback.

Here is our second pass: Save, cancel and callbacks

Step 3: Finishing Off

Our plugin is nearly there. Just a few nice finishing touches remaining. We want to give the user ability to change the button label and pass an initial value. Also to make the plugin more re-usable we want to move the core plugin code out to a separate file and reference it instead. To set the stage for further improvements in the future we also split the code into two distinct clauses.

Final result: Live Demo and source code is here

Usage

Now to use this brand spanking new plugin we simply apply it to any DOM element like so:

HTML

<span class="editable">Hello World!</span>

JavaScript - Basic

$(function() {
  $('.editable').inlineEdit();
});

JavaScript - Customised button label with save callback

$(function() {
  $('.editable').inlineEdit({
    buttonText: 'Add',
    save: function(e, data) {
      return confirm('Change name to '+ data.value +'?');
    }
  });
});

Feedback welcome - if you happen to improve upon this code base please share-a-like!

Enjoy!

Update 26-Aug-09: Added placeholder for cases when text is empty; changed label option to buttonText to minimise confusion.

Update 18-Oct-09 Fixed bug in setting initial value via script.

Update 17-Jan-10 Moved code to http://github.com/caphun/jquery.inlineedit. I will continue to improve this plugin from there. Feel free to fork it!