Actionscript code generator on the fly

I was wondering if that could be done.. Now i found this amazing japanese site, via pixelhero, where you can code & compile online in Actionscript 3.

Wonderfl: build flash online

and this is my first attempt to code online. ;-)

Let’s try!

Creating a Carousel using jQuery

A Carousel is a component used to preview images, a little inline slideshow of thumbnails. There are quite a lot premade carousels ready to be copied and pasted if you don’t mind about, but i think that this is a nice example to start working with jQuery.

Step zero: planning

For the structural aspects of the carousel we will use a unordered list, masked by a fixed – width div. The list doesn’t have a maximum number of elements, we will count the and count their width with the Javascript; obiously the list should now be a traditional vertical list: we’ll handle this with css.

There’ll be also two clickable elements, outside the mask, to gently move the list left or right.

The HTML

The html is really simple: is just a list wrapped by a div. The div acts like a mask, hiding the images.

<div id="carousel">
        <ul>
                <li> <img src="..." width="200" height="150" /> </li>
                <li> <img src="..." width="200" height="150" /> </li>
                ...
        </ul>

<span id="left">left</span> | <span id="right">right</span>

We also have the left and right elements. They can be pretty much anything, a good graphic should do the work.

It is important to specify the image width attribute, because the Javascript code will need it to calculate the carousel width.

The CSS

The css is in charge of horizontalizing the list, and masking with the div.

#carousel {
        overflow: hidden;
        position:relative;
        width: 500px;
        height: 150px;
        list-style: none;
    }

Note that we specify the height and width of the component here; we also specify position:relative, which should have really no sense, but is here only to cover a bug in IE7, just like is explained here (in italian)

    #carousel ul {
        padding: 0px;
        margin: 0px;
        position:relative;
    }
    #carousel li {
        display: inline;
    }

    #carousel img {
        border: 0px;
    }

This should explain by himself. The ul position is relative because we want to move it.

So now you should have a non - moving carousel. Funny. Ah.

So now you should have a non moving carousel. Funny. Ah.

And finally.. Javascript!

Here’s where the magic happens..

Fist thing: importing the right files: jquery.js and the easing plugin (we want a sexy movement, not a linear one!). Remember to do this in the <head> tag

<script type="text/javascript" src="js/jquery-1.3.1.min.js"></script>
<script type="text/javascript" src="js/jquery.easing.1.2.js"></script>

Next, we will add some code (in a script tag, obiously):

var shift = 250;

    $(document).ready(function() {
        var ulWidth = 0;
        $("#carousel ul img").each(function(i) {
            ulWidth += $(this).outerWidth(true) + 4;
        });
        $("#carousel ul").css("width", ulWidth);

What’s happening here?  We have a variable, called shift, which we will use to controll how much we want to slide the list each time; Next we bind a function to the document ready event – when all the page has finisched loading. We use the ulWidth variable to sum all the single thumbnail’s width. We initializa it to 0 and then, for each img tag in the list, we will sum the outerWidth() (and a little padding, to be nice); outherWidth() is a nice jQuery function that report the width of an element, including margins.

        $("#right").click(function() {
            var newPos = $("#carousel ul").position().left - shift;
            if ($("#carousel ul").width() + newPos &lt; $("#carousel").width()) {
                newPos = $("#carousel").width() - $("#carousel ul").width();
            }
            $("#carousel ul").animate({ left:newPos+"px"}, 1000, "easeInExpo");
        });
        $("#left").click(function() {
            var newPos = $("#carousel ul").position().left + shift;
            if (newPos &gt; 0) newPos = 0;
            $("#carousel ul").animate({ left:newPos+"px"}, 100, "easeInExpo");
        });
    });

Here, we setup the onClick handlers over the left and right elements. When you’ll click one of these, the magic should happen..
For each handler we read the position().left property and sum the amount that we want to scroll( the shift variable).

It it important to check that the right edge of the list (the left edge + the width) should stay out (on the right) of the viewport, or else we will see the list background. We don’t want to scroll when there are no more images!
The same thing for the left edge, when we scroll left, or else there be space on the left of the first image.

And… it works! Try the demo, or download the examples

Further readings:

the Carousel Pattern on the Yahoo Design Pattern Library and the really good JQuery documentation
Credits to webdevlonge which has a really nice tutorial on creating a carousel with mootools

Easy recursion: determine if a component is showing

A good and easy example of a recursive function has come to my mind while replying to this question on stackoverflow.

The problem was how to know is a component (mx:UIComponent) was visible or not, just like Component.isShowing() works in Java. You canno’t rely on the visible property of the UIComponent, you have to check every parent to see if it too is visible.

First step in recursion is to block the basic level. If the component reference is null, it is not visible; if the component we are checking is an Application, it should be visible, according to his visible property (it doesn’t have a parent).

All the other cases should check the property, AND the parent’s property. (If a component isn’t on the DisplayList, his parent will be null, and it will not be visible,  and so for all of his children).

public static function isVisible(c : UIComponent) : Boolean {
    if (c == null) return false;
    if (c is Application) return c.visible;
    return c.visible &amp;&amp; isVisible(c.parent);
}

Requesting Webservices in Flex 3

Follows Webservices, simple introduction.

In Flex 3 requesting data is really simple, since you really have to load a well know url which prints out XML (or JSON or whatever).

I assume you have read the introduction, here we are with a url that prints out informations about Cher’s top fans:

http://ws.audioscrobbler.com/2.0/?method=artist.gettopfans&artist=cher&api_key=xxxxxxxxxxxx

What we have to do is load that url with a mx:HTTPService Object and parse the result as XML. Simple, it isn’t?

First: create the HTTPService object:

<mx :HTTPService id="fetchData" url="{apiUrl}"  resultFormat="xml" result="handler(event)" fault="error(event)"/>

and the handlers

private function handler(event:ResultEvent):void {
xmldata = XML(event.result);
}
private function error(event:FaultEvent):void {
Alert.show("Error: " + event.fault.message);
}

And oplà, in the data field you will have the returned xml, ready to be shown in your preferred component!

Webservices, simple introduction.

Website exposes their data to 3rd part application trought webservices and xml. It’s pretty simple: the user calls a url which has some parameters that contains the request, the webserver handles the request, queries the database and prints out the resulting data in XML (or JSON, or other) format. This permits to limit user access to the complete data, exposing only a part of them.

This is the underlying technology that empowers all kinds of mashup: you request data from some sources, combine it and show them up in your application. I want to share some examples of building an app that works with data loaded from external webservices; I’m not gonna show you another flickr example, there are too many out there, so I’d prefer doing something using Last.fm APIs.

First thing is, you have to apply for an API KEY. What does this means? Api calls somethines aren’t free, other times the provider wants to keep track of who calls which api, or keep statistics; So you have register a unique id that will sign all your calls. Usually you pass this key as a parameter of the function.

So to start, let’s choose a simple function to call, artist.getTopFans sounds good and doesn’t require authentication. It prints out informations about the top fans of a given artist. The documentation page tells that it requires 2 parameters: the artist name, and the api key, they explains themselves.

So now we know that we want to know who are the top fans of.. let’s say, Cher. We have to take the root url of the APIs, which is

 

http://ws.audioscrobbler.com/2.0/

 

enqueued by the parameters written as &key=value pairs (It’s a simple HTTP GET request, other services will require HTTP POST requests, but, later).
We now have the url of the call, which should be similar to:

 

http://ws.audioscrobbler.com/2.0/?method=artist.gettopfans&amp;artist=cher&amp;api_key=xxxxxxxxxxxx

You can try substituting your api key and open that url in a web browser.