dtsn · I build cool stuff for the web. Hi I'm Daniel and I blog about design, JavaScript and CSS. Find out more about me and subscribe to my feed.

Archive for the ‘Prototype’ Category

Bouncing JavaScript Tutorial

Original Source: http://giancarlo.dimassa.net

There have been many examples of bouncing effects in scriptaculous but this one has to be one of the most realistic. It uses the equations developed by Robert Penner to accurately represent a bounce, and it does look cool.

What you need

As with most of my tutorials this is based on scriptaculous and prototype, but the equations could easily be porter to other animation frameworks.

The code

This is really simple, basically what we are going to be doing is to add a new transitional effect to scriptaculous. To do this we just extend the Effect class.

Add this to your own JavaScript file instead of scriptaculous, so you don’t loose it when you update.

/*Based on Easing Equations v2.0
(c) 2003 Robert Penner, all rights reserved.
This work is subject to the terms in http://www.robertpenner.com/easing_terms_of_use.html

Adapted for Scriptaculous by Ken Snyder (kendsnyder ~at~ gmail ~dot~ com) June 2006
*/

Effect.Transitions.Bounce = function (pos) {
    if (pos < 0.36363636363636365) {
        return 7.5625 * pos * pos;
    } else if (pos < 0.7272727272727273) {
        return 7.5625 * (pos -= 0.5454545454545454) * pos + 0.75;
    } else if (pos < 0.9090909090909091) {
        return 7.5625 * (pos -= 0.8181818181818182) * pos + 0.9375;
    } else {
        return 7.5625 * (pos -= 0.9545454545454546) * pos + 0.984375;
    }
}

Use it

You can use this effect as a transition type with lots of effects.

new Effect.BlindDown(div, {
    duration: 0.5,
    transition: Effect.Transitions.Bounce
});

Check out Ken Snyder’s blog for more transitional effects.

JavaScript Check/Uncheck Checkboxes

This tutorial is a really simple one and is only a one liner in prototype (slight more in regular JavaScript). It will check all the checkboxes on a page, and a function to uncheck all checkboxes quite handy really especially if you are dealing with long lists.

Check All

$$('input[type="checkbox"]').invoke('writeAttribute', 'checked', 'checked');

What we are doing here is selecting all the inputs of type checkbox and enumerating over them writing a check attribute to each one.

Uncheck All

$$('input[type="checkbox"]').invoke('removeAttribute', 'checked');

As you can guess this just the opposite way round.

JavaScript

You can do the same basic principle without a framework:

// check all
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
	if (inputs[i].type == 'checkbox') {
		inputs[i].checked = true;
	}
}

// uncheck all
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
	if (inputs[i].type == 'checkbox') {
		inputs[i].checked = false
	}
}

That’s it there isn’t really much to it, but I thought it was worth sharing.

JavaScript Weather

Here’s a crazy idea, what would you do if you wanted to change the background picture of your website so it matches the weather. Luckily Its really easy, and I figured out all the hard bits for you.

UPDATE – Chris Heilmann over at the Yahoo! Developer Network Blog has made this even simpler through the use of YQL.

The Data

First of all we need a data source which will provide the weather for a particular location, we can grab this from the Yahoo Weather API. Using the code UKXX0117 which is for Reading, UK I can create the an RSS feed which you can see here http://weather.yahooapis.com/forecastrss?p=UKXX0117&u=c. Great but how can we process this RSS feed? That’s where Yahoo Pipes comes in, we can take in the RSS feed extract the data we need (item.yweather.condition) and export it as JSON.

image

Now we can access the JSON data for the weather in Reading here.

JavaScript

The JavaScript cannot directly call the JSON script via AJAX due to cross site scripting limitations imposed by the browser. This is where JSONP comes in, JSONP is a way to retrieve data from external domains through wrapping the JSON in a function, you can read more on JSONP at from__future__import. Yahoo Pipes fully supports the JSONP format using the parameter callback, therefore in our webpage we load up the following.

<script type="text/javascript" src="http://pipes.yahoo.com/pipes/pipe.run?_id=b13966505cb6b00dd1d18ec4aafc14b4&_render=json&_callback=weather"></script>

This will call the function weather passing through a weather status code as the parameter.

That is really it, you can do whatever you want with the data, here’s a quick example of how I would use it.

function weather(data) {
        var code = data.value.items[0].content;
	switch(code) {
		case '32': $(document.body).addClassName('sunny');
		break;
	}
}

Example

TweetTabs, A Story

For everyone who follows me on twitter or knows me personally would know that yesterday I launched something that i have been working on for a very long time. TweetTabs is a way of tracking real-time twitter trends and searches, and has been my little project since i first started on it back in Easter. The idea came from the lack on online real-time ways to interface with twitter, the premise is simple, i wanted an easy way to search for things in twitter which constantly updated, so TweetTabs was born.

The initial application was written in about 2 hours entirely in JavaScript, it later went through a number of huge revisions especially over the Easter weekend. It gained quite a lot of features, and then lost them. I wrote an entire OAuth module in JavaScript, then realised that you can’t authenticate headers. The project was basically done apart from one of the most complicated features. Then my life changed, I broke up with my long term girlfriend, of 5 years, and had to move back home with my parents. Even though this didn’t dent my enthusiasm for the project it definitely affected the timescales.

How it works

image

TweetTabs is a very simple idea, but it takes a very long time to solve the problems it presents. The entire application is written in JavaScript, this gets around the notion of having a API limit for your twitter searches, you are now only limited by your I.P. address, which has a much higher (not declared) limit. For every tab TweetTab hits twitter to fetch the data, this is controlled by our adaptive pollrate. Put simply this means that each tab can work out the optimum time to fetch more data from twitter. We try and limit the number of times TweetTabs hits twitter in the hour, mostly so that you don’t reach your API limit (it is possible, and I did it a lot in testing), and we don’t overload twitter.

TweetTabs Screencast from Daniel Saxil-Nielsen on Vimeo.

Coverage

So now TweetTabs has been launched and has had loads of positive feedback and has been covered on loads of huge sites:

Dedications

I don’t know whether this is normally done for releasing products, but I feel it is appropriate, I would like to mention everyone who helped with the process along the way. Starting firstly with @nickhalstead, who supported me the whole way (and sorry it took so long). @nicktelford who was there to bounce ideas of and to find lots of bugs just before we were about the launch. @alexforrow for writing a really good deployment script, which merges all the files and obfuscates them. All the great people that tested it along the way: @chris_alexander, @craigyd, @amykate and @girlygeekdom (who is probably the one who answers @tweettabs questions online).

TweetTabs is built using Prototype and the JavaScript framework, and is powered by TweetMeme, and Twitter.

JavaScript Halloween Effects

Halloween is just around the corner and what better to jazz your blog up than with some Halloween related JavaScript. This tutorial will focus on making images appear and disappear on the background of your blog.

For this example I will be using a ghost which will appear every two seconds in a random location and disappear again. You can preview what this will look like by clicking the button below (only viewable in a web browser).

You can download the source files for this tutorial below as well as the ghost AI file.

Source Files

For this tutorial we are going to be using Script.aculo.us effects library with the Prototype core framework.

var Ghost = Class.create({
	initialize: function() {
	}
});

First of all we need to create our Class, which is called Ghost. Inside the class Ghost we have added our initialize function. The initialize function will be called when we create a new instance of the class. Therefore we need to put in all our setup code:

 // create the element
this.ghost = new Element('div', {'class' : 'ghost'});
// hide the element
this.ghost.hide();
// add the element to the body
$(document.body).insert({top: this.ghost});
// get the size of the document
this.size = document.viewport.getDimensions();
// set up the timer
new PeriodicalExecuter(this.show.bindAsEventListener(this), 2);

In this segment we create our hidden ghost element. We then store the size of the document, and load up our periodical executer to call this.show. The second parameter in the Periodical Executer is the time between calls, we are calling the show function once every 2 seconds.

show: function() {
	// randomly set where the ghost is going
	var x = Math.floor(Math.random()*(this.size['width']-200));
	var y = Math.floor(Math.random()*(this.size['height']-200));
	// set the style
	this.ghost.setStyle({
		'left': x + 'px',
		'top': y + 'px'
	});

	// show the object
	this.ghost.appear({
		afterFinish: function() {
			this.ghost.fade();
		}.bind(this)
	});
}

The show function needs to be added to the Ghost class. The show function first calculates where we want our ghost to appear, so we work out random x and y co-ordinates using the document sizes we gathered in our initialize function. We then position the element and call the Script.aculo.us appear effect which will slowly fade in the image. After the appear effect has finish we want to hide the ghost so we call fade.

Ok, now we have all the code complete we need to call the class. We can do this in a number of ways, you could bind the event to a button:

BOO

Or you can bind it into your document load function, which means it will start when the page loads:

document.observe("dom:loaded", function() {
	new Ghost();
});

CSS

The CSS is a really simple one line.

.ghost { width: 100px; height: 100px; position: absolute; background: url('yourimage.png') no-repeat; }

This tutorial is just a brief outline with what you can do with JavaScript this Halloween. If you have any other ideas you would like me to implement, please tell me in the comments below.

Prototype Element.Insert

Prototype has a very useful function which is not well documented, Element.inset. Element.insert is a very powerful prototype function which lets you insert a element in one of 4 positions, before, after, top, bottom of an element.

If we wanted to insert an element after a element we would use this code:

[code="javascript"]
Element.insert(first-element, {top: content});
[/code]

Expanding this further:

[code="javascript"]
// lets create our element
var dummy = new Element('div').update('Hello World');
// add the element
Element.insert($('hook'), {after: dummy});
[/code]
Where hook is the element we want before our created element

This code will add our Hello World text after the div with the id of hook.