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 ‘JavaScript’ Category

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.

Building JavaScript Widgets

Building JavaScript Widgets

Little pieces of JavaScript you embed onto your website are getting more popular. Every major provider of a service on the web also gives you a little widget that you can put on your blog or webpage to promote what you are doing, for example Twitter, Last FM and Digg all provide widgets which are great for you and great for the service.

I am going to talk you through the development and pitfalls associated with the design and development of widgets.

First and foremost, you need to decide what you want to show with your widget. Knowing this you can make an educated choice about which method you want to use to create a widget, there are basically two methods associated with widget development.

iframe’s

No, iframe’s aren’t dead. They are a major part of widget development. Using a iframe is the easiest way to generate a widget – you host a small file on your web site which contains the information you want to show, like the Digg button for example, and get the JavaScript on the client side to build the URL to it. In the case of Digg the client side JavaScript builds a URL based on the current posts URL.

document.write('');

To install the widget all you have to do is to point the user at your bit of JavaScript:


You can pass any variables you want through to the user at this point by simply making them JavaScript variables, and using the JavaScript to build up the iframe URL based on these variables.



If you want your widget to be able to appear multiple times on the same webpage, you need to remember to set all the variables to null at the end of your JavaScript file.

That’s it! iframe based widgets are very easy to build and to use, however they do come with their downsides. The biggest of these is that the user can’t customise the widget at all – it lives within an iframe and therefore is untouchable by CSS. That’s why certain widgets, like the twitter widget, which are made entirely on the client side in JavaScript.

Client Side

A widget that is built in JavaScript on the client side is definitely the harder option. For this you have to make the JavaScript file create all the HTML, write out a basic style to apply to the HTML and load in the data. When building this try to avoid using frameworks to build the HTML, this only creates more request for your web servers and make the widget slower to load. Instead resort to using the classical JavaScript methods for creating elements.

document.write('
'); var widget = document.getElementById('you_id'); var div = document.createElement('div'); div.innerHTML = 'Hello World'; widget.appendChild(div);

You will have to load your data in from another source, and for this I recommend extending your API to give you a JavaScript variable followed by the JSON encoded data. Here’s an example from tweetmeme.

Pitfalls

There are a lot of difficulties involved in creating widgets and here are just a few of them:

  • AJAX won’t work! You cannot post information between domains.
  • Don’t use a JavaScript framework – for a simple widget it’s is over kill.
  • Try to keep the requests down. These widgets are coming from your servers.
  • Anonymise the JavaScript, you don’t want it conflicting with other JavaScript.
  • Minimize your JavaScript. This will save on bandwidth for you, and make the widget faster to load. 

Questions

If you have any questions, or want to show off any widgets you have made please comment below.

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.

JavaScript in CSS, Ugly But Interesting

There is a very little used and unknown method which allows you to utilise JavaScript within a CSS file. The CSS Expression property allows you to assign a JavaScript expression to a CSS property. For example, this allows you to set the position of an element according to the browser size.

[code="css"]
width:expression(document.body.clientWidth > 950 ? "950px": "100%" );
[/code]

Do not use CSS Expression, they are unreliable, slow and are only supported in IE!

CSS Expression suddenly came to me as a solution for the currently much debated feature (here and here) of variables in CSS3. This could theoretically be currently achieved through the use of CSS Expressions.

[code="css"]
function blue() {
return 'blue';
}

body { background: expression(blue()); }
[/code]

CSS Expressions are horrible and unsupported, so please don’t use them in development. They do, however, highlight a interesting and little known feature of CSS.

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.

Scriptaculous ScrollTo

Example: Click Here!

The script.aculo.us effects library is a fantastic tool. If this really simple tutorial I will show you how to utilize the scroll method and a handy ‘jump to top link’.

Step 1: Add References

Make sure you have the prototype and script.aculo.us
libraries attached to your web page, instructions for how to do this can be found here.

Step 2: Create JavaScript

You can either create a new JavaScript file or append these functions to an already existing one. So first of all we need the function. For that we create a new JavaScript object, we will call this ’scroll’.

var  scroll = { }

Next we want to add the functions. In my case I want a function that will scroll to the top and to the bottom:

var  scroll = {
	top: function(event) {  },
	bottom: function(event) {  }
}

Now we have our framework we can call the ScrollTo function:

new Effect.ScrollTo('top');

The ScrollTo function allows you to define a particular object that you want to scroll into view. In the case of dtsn.co.uk, I have a div on the top of every page with the ID of ‘top’.

Putting that all together we get:

var  scroll = {
	top: function(event) { new Effect.ScrollTo('top'); },
	bottom: function(event) { new Effect.ScrollTo('footer'); }
}

You can then call this function in one of two ways. You can call ’scroll.top()’ and ’scroll.bottom()’, respectively, through the onclick method on any HTML object. Alternative you can use the prototype method of Event.Observe:

// wait for the page to load
Event.observe(document, 'load', function(){
        // give an object an onclick method
	$('go_to_top').observe('click', scroll.top);
});