Monday, November 26, 2012

flip this

There are many jQuery libraries out there for generating a "Flip" transition effect, as if a card was flipping over.  Flip!'s page is polished, but the effect is marred by the content disappearing during the flip. (Also I didn't like how it encourages the back content to be generated programatically, rather than living with the rest of the content.) QuickFlip 2 does a better job keeping the content present, but the visual effect is rather lackluster. However I have found an excellent, easy to use library that has a high "hey, wow!" factor and only a few things to watch out for: Zachstronaut's rotate3Di. Here it is an action:

This is a trivial example, but the content inside can be any html, including images.

It took me a bit to wrap my head around how it works: it's some CSS transform magic with skewY() and scale() being animated in sync for the nifty 3D illusion. The front of the card/back of the card bit is really interesting: if you want different content for the front and back, you make a function for the sideChange parameter. This function is called halfway through the flip with a boolean argument that indicates if the front is showing. Your function is then responsible for show()ing the appropriate side and hide()ing the other (which makes sense: with a flat object, only one side is visible at a time... Amusingly, the defaults without this function are to show the content reversed.)

So for this example, I had this HTML:

<div class="flippable" id="flipExample">
    <div class="front">Click To Flip</div>
    <div class="back">The Back</div>
</div>

decorated with this CSS (some parts omitted for brevity, feel free to view source.)

.flippable {
    height:150px;
    width:150px;
    padding:1px;
}
.flippable .front {
    background-color:#ffcccc;
}
.flippable .back {
    display:none;
    background-color:#ccccff;
}

The code then was pretty easy...
$('#flipExample').click(
    function(){
        $(this).rotate3Di('toggle', 1000,
            {
                sideChange:function(isFront){
                    if(isFront) {$(this).find(".front").show();$(this).find(".back").hide();}
                    else  {$(this).find(".front").hide();$(this).find(".back").show();}
                }
            });
    }
);

So like I mentioned, the things to watch out for were pretty minor: one was that the container (which is what is actually being rotated, but maybe shouldn't have content of its own outside of what's in your front and back side content) needed 1 pixel of padding, otherwise some odd lines showed up during the animation in chrome. And also, you need to include 2 js files, not just 1: jquery-css-transform.js and rotate3Di.js. The Transform one is needed for IE9 tweaking, which brings us to IE in general: it doesn't work for IE8 or earlier, but it degrades gracefully into an untransitioned swap of the front with the back.

So, a nice effect, and easy to put into place.

Tuesday, November 20, 2012

trunKit: how to deal with too much text...

As a UI developer, I'm sometimes given a visual spec to implement that doesn't really stretch: designs with elements that are fixed sized, regardless of the content meant to be lincluded inside (such as a long title or description.)

One solution for this is to show an abbreviated version of the title, possibly ending with a "...", and then let "hover" (in an increasingly touchscreen world, hover is often deprecated, though iOS tends to let a quick tap act as a hover) show the full title.  While refactoring our "activity tiles" at Alleyoop, I decided to wrap our solution to this issue as a jQuery plugin, So I introduce to you:
 trunKit.alienbill.com
I've posted an example of it in action below, but more information is there on the project site or its github repository.

Wrapping the functionality as a jQuery was easy: I'd recommend jMar's simple guide. The short of it is using a tiny bit of boilerplate, you're implementing an "each()" function (so your code can be daisy-chained) and then there's a nice method to allow for a hash of configuration options, but with sensible defaults.

Here it is in action:
 
This is the first example that I am placing here
My second example is not much different from the first
but by placing three examples, we will experiment with different colors.
But this is short.
There's likely dozens of similar plugins already out there, but this is mine, and I learned a bit from making it and packaging it as a plugin...

Thursday, November 1, 2012

wiki-dy wiki-dy wack

I like wikis, but tend to dislike wiki markup. As a note to my future self, {code}...{code} can be used to mark off some coding type stuff especially if said code has ${template stuff} like that in it.

Wednesday, October 17, 2012

safety second - encoding URLs


Just a note to my future self: you need to be not so blasé about building and then encoding URLs. And you can't just use javascript's encodeURI()on the whole thing, things like & will all be escaped inside of it. Instead, use encodeURIComponent() on the separate bits of it.

Again, kind of no-brainer but I got a slightly singed by it this week.

Friday, October 12, 2012

safety first with "global" javascript variables

This might be a "well duh!" for some of my audience, and I admit my need for this indicates some underengineering in my company's javascript component structure, but sometimes it's useful to pass information into one of our embedded components from the enclosing page via a global variable. ("Gasp!")

For a long time we were making this harder than it needed to be, because if you plan to have the page set something like

var global_hideFooter = true;

and then later do something in a component function like

if(global_hideFooter) { //do something 
}

it will break badly if called from another page that didn't set global_hideFooter one way or the other-- all the code in that block after the call to the non-existent variable will not be run.

However, if we realize that when you set a global in a browser (either by something like "var foo=" outside of any scope, or just start setting "foo =" anywhere) it gets implicitly included as a key/value on the "window" object. That means we can safely do

if(window.global_hideFooter) { //do something 
}

and it won't break if a page doesn't set it (and handily, in this case an unset value would act like false in a boolean context... defaults to false is a pretty natural coding paradigm.)

Tuesday, October 9, 2012

jquery data

Like I've written about previously, Javascript scoping can be tough to wrap your head around, and in general I try to avoid situations where I have to use CreateDelegate in order to have the context I'd "expect", especially during a click or similar event.

Yesterday I realized I had been forgetting about a very powerful tool in the anti-CreateDelegate, let-DOM-objects-carry-the-context-they-need front: jQuery's ".data()"  function. This little beauty lets a developer put key/value pairs "into" the DOM object for easy retrieval later.

Here's a version of some broken code I made yesterday:

for(var i = 0; i < data.length;i++){
    var jqo = $(".templateWrapper .modelTile").clone(true);
    var foo = data[i].value;
    jqo.click(function(){
        alert.text(foo);

    });
    $("#container").append(jqo);
}

The problem was because of the scoping, the text being alert()d was whatever the last value of foo had been, for all the tile objects.

I knew I could make use CreateDelegate object to carry the context, but that seems slightly less robust. Instead, I went back to use the .data() function:

for(var i = 0; i < data.length;i++){
    var jqo = $(".templateWrapper .modelTile").clone(true);
    jqo.data("val", data[i].value);
    jqo.click(function(){
        alert.text(
$(this).data("val"););
    });
    $("#container").append(jqo);
}

That worked and felt great! I'm not sure why I've been shy about using the .data() function; it's easier than CreateDelegate and less hacky than hidden form elements or rereading the content of visible DOM objects.

Friday, September 28, 2012

fullscreen iOS html5 apps and pretty clouds

Recently I remade an old art project of mine, "Virtual Sisyphus", as an html5 canvas work using Processing.js:


The viewer plays the role of Sisyphus, condemned to drag a rock up a mountain for eternity. Every time you try and fail to do so, the rock scores a point. (It's an existentialist joke, and like the PHB in the Dilbert cartoon series said, it has a certain sense of playfulness, if you look at it from the rock's point of view.)

I exhibited this as a work at my company's employee art show by using an iPad as a kind of virtual frame, you can see it on the left here:


I programmed the piece to have adjustable width and height, so it could fill its container, and scale itself to make good use of the space. Then, to make it as a nice fullscreen app (and make sure all the finger moving got interpreted as clicks and mouse drags in the Sisyphus world, rather than as scaling or resize) I did the following:

In the processing.js code setup, I started with:
size(document.documentElement.clientWidth, document.documentElement.clientHeight);

Then in the html file I had the following meta tags:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name = "format-detection" content = "telephone=no"/>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width;" />
<meta name="apple-mobile-web-app-capable" content="yes" />

Just to be sure, I set padding and margin to 0px for both the body and the canvas tag processing.js uses.

(The apple-specific tag is kind of neat, adding that meant I could send the webpage to the homescreen from Safari, and then when I launch it from the home screen, it just has a minimal black bar at top, and skips the usual Safari address bar and what not.)

BONUS: HOW TO MAKE CLOUDS
I ended up being pleased with how nicely my cloud algorithm came out, using stretched ovals to get  a nicely organic/cartoony feel. Here was my Cloud class:

class Cloud {
  float x,y;
 ArrayList<Fluff> fluffs; 
  Cloud(){
      y = random(0,height * 3 / 8);
      fluffs = new ArrayList();
      int count = round(random(2,8));
      for(int i = 0; i < count; i++){
      fluffs.add(new Fluff());
      }
      x = width - getLeftmost();
      
 } 
   void move(){
      x -= random(.1,.5);
   }   
   float getLeftmost(){
       float lowest = 9999;
     for(Fluff f : fluffs){
       float side = f.getLeftmost();
       if(side < lowest) lowest = side;
     }
     return lowest;
   } 
   
   float getRightmost(){
       float highest = -9999;
     for(Fluff f : fluffs){
       float side = f.getRightmost();
       if(side > highest) highest = side;
     }
     return highest;
   } 
   
   void draw(){
     stroke(0);
     noStroke();
     fill(200);
     pushMatrix();
     translate(x,y);
   for(Fluff f : fluffs){
      f.draw(); 
   }
   popMatrix();
   }
  
}


class Fluff{
  float w,h,x,y;   
  Fluff(){
          w = random(width/9,width /3);
     h = random(height/24, height / 8);  
     x = random(-w/3,w/3);
     y = random(-h/3,h/3);
    
   }
   
   float getLeftmost(){
     return x-w/2;
   }  
   float getRightmost(){
     return x+w/2;
   }  
   
  void draw(){
   ellipse(x,y,w,h);
   w += random(-.1,.1);  
   h += random(-.1,.1);  
   x += random(-.1,.1);  
   y += random(-.1,.1);  
} 
}

(Much  of the code was just getting the maximum left and right extents, so I would know when it was safe to remove a cloud from the world, and making sure it appeared off the right side of the screen.)

My main cloud generating loop was:

Cloud cloudToKill = null;

  for(Cloud c : clouds){
     c.move();
    c.draw(); 
    if(c.x + c.getRightmost() < 0){
     cloudToKill = c; //only one but it doesn't matter
    }
  }
  if(cloudToKill != null) clouds.remove(cloudToKill);
  
  if(clouds.size() < 5){
     if(random(250) < 1){
        clouds.add(new Cloud());
     } 
  }
  
It could only remove one cloud per frame, but that wasn't such a problem. And it maxed out at 5 clouds at a time.

So, that was it! Let me know if you ever manage to drag that rock to the top!