Posts Tagged ‘javascript’

Toggle non-consecutive checkboxes with jQuery UI

Posted on:Tuesday, December 27th, 2011 by Ashish Datta

You’re all probably familiar with the UI convention of allowing users to select ALL or NONE for a list of checkboxes (like in Gmail). Recently I was working on a project that had a large table full of checkboxes (imagine a 10×10 grid) where the user would need to toggle some but not all of the checkboxes in a given row. And to make matters more complex, they would need to toggle groups of non-consecutive checkboxes (say 15, skip 10, 5, etc.). I threw on the thinking cap but couldn’t think of any similar interactions I’d seen and couldn’t think of a particularly good way to achieve this.

Enter jQuery UI. I happened to stumble across the jQuery UI Selectable documentation and realized it would provide a good UI experience to toggle some but not all of the checkboxes. The code to implement this is surprisingly simple:

Note: You don’t actually need the div container – that was just for JSFiddle.

<div id="checkboxes">

<table id="checkboxTable">
     <tr>
         <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
     </tr>
     <tr>
         <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
     </tr>
     <tr>
         <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
     </tr>
     <tr>
         <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
     </tr>
     <tr>
         <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
          <td><input type="checkbox" /></td>
     </tr>
</table>
</div>

And then the Javascript (jQuery + jQuery UI):

$("#checkboxes").selectable( {filter: "input:checkbox",
            stop: function(event, ui) {

                $(".ui-selected").each( function(){

                    $(this).each( function(){
                        var val = $(this).attr("checked") ? null : "checked";
                        $(this).attr("checked", val);
                    });

                });
}});

You can check out a live demo at http://jsfiddle.net/whMyQ/3/

As always, questions and comments are welcome!

Upload directly to S3 with SWFUpload

Posted on:Thursday, April 21st, 2011 by Ashish Datta

I was working on an application earlier today that required allowing a user to upload a large file (several hundred MB) which would eventually be stored on Amazon S3. After reviewing the requirements, I realized it made sense to just upload the file directly to S3 instead of having to first stage the file on a server and then use PHP to push the file to S3.

Amazon has a nice walk through of using a plain HTML form to upload a file directly to S3 here.

I had all ready been using SWFUpload to upload files to the server so I decided to look into using it to uploading directly to S3. After some head banging, I finally got it to work – here’s the quick n dirty.

  1. Download SWFUpload 2.5
  2. Get SWFUpload ready to use in your project. Copy the SWF file somewhere accessible and include their swfupload.js Javascript file. More info here
  3. Setup an S3 bucket. You’ll need to set the policy to allow uploads from your own user (its the default).
  4. Place a crossdomain.xml file in the root of your S3 bucket. This file “authorizes” flash player to upload files into this host. The content of the file is below.
  5. Initialize the SWFUpload object (example below).
  6. Before beginning the upload, you need to set the appropriate postParams in the SWFUpload object. This is really the “magic” of this process. Example is below.
  7. Start the upload with startUpload()

Thats it! It’s pretty straight forward once you have things going. As an FYI, you can put SWFUpload into “debug” mode by adding debug: true as a property to the initialization object. You can also debug the responses from Amazon by using a packet sniffer like Wireshark.

crossdomain.xml

You probably want to make this file a little less permissive. More details here. Also note, there are differences in the implementation of the file between various versions of Flash player.




  

Initialize SWFUpload

        var swfu = new SWFUpload(
                       {  flash_url: "/assets/swfupload.swf",
                          flash9_url: "/assets/swfupload_fp9.swf",
                          file_size_limit: "1000 MB",
                          file_types: "*.*",
                          debug: false,
                          upload_url: "http://your-bucket.s3.amazonaws.com",
                          button_placeholder_id : "SWFUploadButton",
                          button_image_url : "/assets/select_filesbtn.png",
                          button_width: '112',
                          button_height: '33',
                          button_cursor : SWFUpload.CURSOR.HAND,
                          http_success : [201, 303, 200], /* Amazon returns a 303 on success */
                          file_post_name: "file", /* Amazon expects the file data to be in a input named "file"

                          file_queued_handler: function(f){

                            // track the filenames so you can upload them later
                            cachedUploadFiles[ f.index ] = f.name;
                          },
                          upload_complete_handler: function(e){ uploadSWFFile( ); },
                          upload_start_handler: function(e){
                                  // reset the progress bar
                        	  $("#progressBar").progressbar( 'value', 0 );
                          },
                          upload_error_handler: function(e){

                          },
                          upload_progress_handler: function(f, c, t){
                             // update the progress bar as the process continues
                             $("#progressBar").progressbar( 'value', Math.ceil( ( c/t ) * 100 ) );
                          }
        });

Set SWFUpload postParams

The HMAC signature MUST be calculated on the server because it uses your S3 secret. You MUST keep that value secret in order to maintain the security of your S3 buckets. I’m using Don Schonknecht’s S3 PHP library to calculate the HMAC signatures but you could just as easily do it in straight PHP.


/* In PHP */
$encodedPolicy = json_encode( array(
              "expiration" => "2011-4-22T13:54:23.000Z",
              "conditions" => array(
                  0 => array( "acl" => "public-read" ),
                  1 => array( "bucket" => "your-bucket" ),
                  2 => array( "x-amz-meta-sig" => 'some meta signature to ensure authentic requests'),
                  3 => array( "redirect" => $'URL to redirect a success request (its doesnt matter)' ),
                  4 => array( "key" => "the S3 key for the file (the S3 filename)" ),
                  5 => array( "Filename" => "The original filename of the file. THIS IS IMPORTANT." )
              ),
            )
);

$encodedPolicy = base64_encode( $encodedPolicy );
$s3 = new S3( sfConfig::get("app_amazon_s3_id"), sfConfig::get("app_amazon_s3_secret") );
list($dist, $hmacSignature) = explode(":", $s3->__getSignature( $encodedPolicy ));

/* END PHP */

            var swfConfig = {
                    'AWSAccessKeyId': 'your amazon ID',
                    'acl': 'public-read',
                    'key': 'the S3 key for the file (the S3 filename)',
                    'policy': '<?php echo $encodedPolicy?>',
                    'signature': '<?php echo $signature'?>,
                    'redirect': 'URL to redirect a success request (its doesnt matter)',
                    'x-amz-meta-sig': 'some meta signature to ensure authentic requests',
            };

            // this line sets the post params so that SWFUpload will send the additional fields when it uploads the file.
            $.swfu.setPostParams( swfConfig );

iPhone style checkboxes for Symfony

Posted on:Wednesday, October 13th, 2010 by Ashish Datta

No one worry, I did in fact survive my birthday and subsequent party!

Anyway, I was poking around for some cool UI elements for checkboxes and stumbled across this neat jQuery plugin – http://github.com/tdreyno/iphone-style-checkboxes Basically, what it does is converts checkboxes into iPhone style toggles.

Check out a demo at http://tdreyno.github.com/iphone-style-checkboxes/

This is for a symfony project (shocker!), so I figured I’d roll it into a widget and share.

You’ll need to download and include the JS+CSS+images for the plugin yourself and then copy the following code into your project:


class sfWidgetFormInputiPhoneCheckbox extends sfWidgetFormInputCheckbox {

	public function __construct($options = array(), $attributes = array())
	{

		$this->addOption('checked_label');
        $this->addOption('un_checked_label');

		parent::__construct($options, $attributes);
	}

	public function render($name, $value = null, $attributes = array(), $errors = array())
	{
		$str = parent::render( $name, $value, $attributes, $errors );

		$checkedLabel = $this->getOption("checked_label");
        $uncheckedLabel = $this->getOption("un_checked_label");
        $id = $this->generateId($name);

		$str .= <<

		  $(document).ready( function(){

                $('#$id').iphoneStyle({
                    checkedLabel: '$checkedLabel',
                    uncheckedLabel: '$uncheckedLabel'
                });

		  });
		
EOF;

		return $str;
	}

}

Using it is straightforward:

    $this->setWidgets(array(
      'show-upcoming-events-nav' => new sfWidgetFormInputiPhoneCheckbox( array("checked_label" => "on", "un_checked_label" => "off") ),
    ));

Streaming Foursquare checkins with Google Maps

Posted on:Monday, September 13th, 2010 by Ashish Datta

This Saturday was the second annual Redline Challenge which is a bar crawl from Downtown Crossing to Davis Square that loosely tracks the MBTA Redline.

This year, we decided to use Foursquare to allow the website to track the position of several of the participants on the challenge. Foursquare natively allows you to track your checkin history with private URLs. Currently, they support a handful of formats with KML being the most interesting for our purposes. You can find your private URLs by navigating to http://foursquare.com/feeds/

We used the Google Maps API along with the KML stream from Foursquare to dynamically place markers on the map as different users checked in to different venues.

Here is the PHP we used to pull back the KML feed, transform it to JSON, and spit it back to our jQuery on the client side:

$xml = simplexml_load_file( "http://feeds.foursquare.com/history/myurl.kml" );
$arr["a"] = $xml->Folder;
$xml = simplexml_load_file( "http://feeds.foursquare.com/history/ackleysurl.kml" );
$arr["m"] = $xml->Folder;

echo json_encode( $arr );

Pretty straight forward. Here is the jQuery code on the client side to add markers to the map:

       $.getJSON( "location.php", {}, function(data){

    	   data.a.Placemark = data.a.Placemark.reverse();

         var hasStarted = false;
         var barIndex = 1;

         $.each( data.a.Placemark, function(i, val){

               if( val.published.indexOf("Sat, 11") == -1 ){
                    return true;
               }

               if( !hasStarted && val.name == "Setfive Consulting" ){
                  hasStarted = true;
               }else if( !hasStarted ){
                  return true;
               }

               var latLng = val.Point["coordinates"].split(",");

               var point = new GLatLng( latLng[1], latLng[0] );

               var marker = new GMarker(point);

               marker.bindInfoWindowHtml( "
" + barIndex + ". " + val.name + "
" ); map.addOverlay(marker); latLngList.push( point ); if( i == data.a.Placemark.length-1 ){ map.setCenter(point, 14); $(marker).click(); marker.openInfoWindowHtml( "
We are at " + barIndex + ". " + val.name + "
" ); } barIndex++; }); var polyline = new GPolyline( latLngList, "#ff0000", 5 ); map.addOverlay(polyline); latLngList = []; data.m.Placemark = data.m.Placemark.reverse(); var blueIcon = new GIcon(G_DEFAULT_ICON); blueIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png"; markerOptions = { icon:blueIcon }; barIndex = 1; $.each( data.m.Placemark, function(i, val){ if( val.published.indexOf("Sat, 11") == -1 ){ return true; } var latLng = val.Point["coordinates"].split(","); var point = new GLatLng( latLng[1], latLng[0] ); var marker = new GMarker(point, markerOptions); marker.bindInfoWindowHtml( "
" + barIndex + ". " + val.name + "
" ); map.addOverlay(marker); barIndex++; latLngList.push( point ); }); var polyline = new GPolyline( latLngList, "#001299", 5 ); map.addOverlay(polyline); })

That’s about it.

UPDATED: New Facebook Phonebook Script

Posted on:Monday, July 19th, 2010 by Ashish Datta

I realized this morning that Anonymous Coward’s Facebook Phonebook Greasemonkey script broke awhile back so I decided to rewrite it from scratch.

The original instructions for how to install the script are available here.

I updated the original Userscripts page with the new script so you can download it here.

Once again, this probably breaks your Facebook TOS so I can’t vouch for the safety of your account if you do decide to do this.

QR Bookmarklet

Posted on:Sunday, June 13th, 2010 by Ashish Datta

I got tired of having to find the same website (mostly recipes) on my phone after looking at them on my workstation or laptop so I decided to whip together a bookmarklet to throw a Google powered QR code on any page.

The bookmarklet will just slap a QR code image with the current page’s URL (window.location) so that you can open the page on your phone. ps. Barcode Scanner for Android will automatically open the URL in a browser.

Without further ado, QR Code Bookmarklet

jQuery.trigger weirdness

Posted on:Thursday, June 10th, 2010 by Ashish Datta

Earlier today, I was trying to use jQuery to trigger the submission of a form after a radio button was clicked. The form tag looked something like:

...form..

So for a regular submit button:


Everything works fine, you’ll see the alert() and the form won’t submit because of the return false.

I ran into issues when I tried to trigger() the submit event with jQuery. I was trying to trigger the submit() event on the form via jQuery. The problem I ran into, was that the saysomething() function was getting called, but the “return false” seemed to have no effect.

The final form looked something like:

For some reason, if you submit the form via a jQuery trigger the form submits even though saysomething() gets called. I’m not sure if this is the expected behavior but it was certainly something of a shock. Anyway, a live version of the form is running here.

jQuery blank() modified for password fields

Posted on:Wednesday, April 28th, 2010 by Ashish Datta

We’ve been using Jeff Hui’s very awesome jquery.blank plugin for sometime over at Setfive HQ. What blank() is allow you to basically move the labels for text inputs into the input themselves (to save space). We use this technique frequently for login boxes in headers since it’s easier not to have to stick in labels next to text boxes.

The problem is, you can’t use blank() on a password field since a password field won’t display clear text (obviously). To get around this, I’ve always manually stuck in a “shadow” text box next to the password field and toggled the text box or password box in order to make blank() work correctly.

Anyway, I finally got tired of doing this so I decided to patch the plugin to do this automatically. Jeff incorporated the code back into blank() and it’s available on GitHub here.

Happy coding.

javascript – $(document).ready getting called twice? Here’s why.

Posted on:Monday, February 22nd, 2010 by Matt Daum

Recently we found ourselves having a really weird problem on a project: Every time a page was loaded it seemed a bunch of different Javascript functions were being called multiple times and making many widgets on the page break and we couldn’t figure it out. Some of the functions were our own code, some part of the package we were using. After a while we narrowed it down to that all the functions in the

$(document).ready(...);

we’re being called twice. We had never seen this. After about an hour of removing javascript files and just headbanging, and many thanks to Ashish, we found the root cause. We had written in a quick hack for a late proof of concept to string replace on the entire HTML of a page a specific string. We did it this way:

$('body').html($('body').html().replace(/{REPLACETEXT}/i, "More important text"));

Basically we used a regex to parse the entire HTML tree and then replace it with the updated text. Unknowingly this caused the document ready event to be triggered again(though now it makes sense), causing many widgets to get extra HTML.

Let this save you some headbanging.

jQuery UI $.dialog – on the fly HTML

Posted on:Friday, November 13th, 2009 by Ashish Datta

Wow its been awhile!

We’ve been insanely busy over the last month or so. We launched Setfive Ventures and are anxiously anticipating the launch of both WeGov and OmniStrat in the immediate future. There are also a handful of internal project that should be rolling out before Christmas. Get Excited.

Anyway, the jQuery UI Dialog class is pretty sweet. Basically, it provides a class to display a modal dialog box from a regular old DOM element (a div, span, or whatever.)

One of the thing that isn’t explained well (or at all?) in the documentation is that you can create a dialog with on the fly HTML! I found this out after posting on the Google Group asking why this feature didn’t exist (it does. Ashish fail.)

So if you want to create a dialog with on the fly HTML all you need to do is:

$("<p>Hello World!</p>").dialog();

Pretty sweet.