Tag Archives: javascript

Developing using jQuery, Firefox and Firebug

10Its becoming more important to know jQuery. If you haven’t heard of jQuery, its one of the most commonly used javascript libraries used on the web. We use it for the corporate site, Hi, and GO. If your not a frequent developer in javaScript it can be an ordeal either re-learning what you’ve forgotten (I’m at that age) or having to learn something new for the first time.

As Douglas Adams would have said..

There are some really nice tools to get you started. If you don’t already, using Firefox as your development browser means that you can take advantage of a whole bunch of development tools, so if you haven’t already fire up this post in Firefox. One of the most famous developer tools for Firefox is Firebug. If you develop, you should use Firebug, get it and install it.

You don’t even need a site with jQuery already installed. BBC famously uses its own javaScript library (Glow), not jQuery, so go to the BBC homepage and fire up FireBug (F12) if you haven’t already done so.

If you’re new to FireBug, you may want a few minutes to explore and play (you’ll feel a little bit like the Scorcerer’s Apprentice). When you’ve finished playing; On the menu bar of Firebug you should see “Console”. Click “Console” to open it. In the bottom left hand corner enter :jQuery at the >>> prompt. As the BBC doesn’t use jQuery you should get an error telling you that jQuery isn’t defined.

John Reisig, the man behind jQuery, has created a bookmarklet called jQuerify. The bookmarklet loads jQuery to sites that don’t have jQuery (but only for your browser session). To use it just drag the jQuerify link into your browser toolbar and whilst on the BBC homepage, click it.

Now when you type jQuery at the Console, you should have access to the jQuery library. Now you can start to play with the jQuery library. For example, at the console type: jQuery(‘h2’) which gets all h2 elements on the page. Clicking the returned Object item takes you into the Document Object Model, giving access to all sorts of information about those page elements.

OK, lets do something freaky. Lets get rid of all the BBC’s h2 elements. Make sure you’re on the BBC home page, jQuerify has been clicked and go back to the console in Firebug and enter: jQuery(‘h2’).hide(2000)

This will hide all of the h2 elements on the page, but will be animated over 2 seconds so you can see them slide away. Don’t panic (you only did it in your browser)! You can re-display the elements by submitting: jQuery(‘h2’).show() You could also just refresh the browser, but you would have to re-click your jQuerify bookmarklet to continue experimenting with jQuery.

Now you can experiment with the entire jQuery library to learn many of the methods, documented on the site, just by entering code in the firebug console.

Flickr’s photo page Ajax trick

Flickr recently started previewing their new photo pages. They’re quite nice but it does something that’s been driving me mad and I can’t work out how it’s doing it. It only happens in Google Chrome 5 and I’ve only seen it in a few places.

Take a look at this screen capture of Flickr’s new lightbox view. Note how the URL updates each time I click through to a new view. Nothing surprising there until you realise it’s not doing a full refresh of the page and is actually an Ajax call back to the server. (You may want to hit the full screen button, bottom right.)

Contrast that with what happens in Firefox – it’s still doing Ajax calls to make flicking between photos quick but the URL changes after the fragment

This technique is pretty common – Facebook have been using it for a couple of years and we even use it to give tabbed pages history on our site. It’s necessary because JavaScript isn’t allowed to set the full page URL without a page refresh, or at least that’s what I thought!

Google Maps has been doing the same as Flickr for a couple of months but I’ve still no idea how! Anyone care to read the Chromium source code or dig around Flickr’s JavaScript to see if there’s something different?

Update: also works in Safari, thanks Ross.

That 3D thing

James Cameron's AvatarLast week my brother who is the last person in the world I’d expect to hear give a film recommendation, phoned me to wish me a happy birthday and then went on to tell me that I just had to go and see Avatar, coming from him, it had to be good.

So on Saturday I took the family. The effects were astounding and you really feel that you were watching an event, the future of how all visually rich films will have to be produced to come anywhere close to this. That said, the plot was typically Hollywood but you couldn’t fail to give it 9/10 for entertainment (I never give 10).

A couple of weeks ago the first 3D TV was trialled in pubs in Manchester, using an Arsenal v Manchester United match.

So with all this 3D about I wondered if there was any 3D web development going on. Seems like there’s quite a bit. Here’s a sample of 3 flash sites using 3D (some take a little while to load):

  1. http://ecodazoo.com/
  2. http://www.whitevoid.com/portfolio.html
  3. http://www.cleoag.ru/labs/flex/parkseasons/

These are all of course Flash sites and more and more we’re seeing opposition to building sites in flash, with some people controversially venting their spleen.

There are few alternatives in javaScript or SVG. So for now I think that Flash will continue to lead the way in this experimental media.

Video, Silverlight and jQuery

During our 25 days of blogging last year, Sam talked about some of the new websites designs that we’ve been working on.  The 125 website was the first to go live last month and today we have released the website accompanying the exhibition for a new sports development.

For both sites we’ve developed some new ways of displaying information as well as improving the designs. Bot the homepage designs use jQuery to create visual effects on the page. 125 has multiple “slides” of information. Each slide transitions to the next after a short period of time or when you click the link on the right.

New Sport also uses some jQuery transitions, this time to change the background image and headline when you hover over links to each section.

There’s a few more new additions to the sport site. We were provided with a DVD containing lots of aerial photos of the campus to feature in a gallery. We’ve done the usual thumbnail gallery but we’ve also got a fancier way of showing off photos.

Microsoft Photosynth is a tool from their Live Labs project. It works by taking a set of photos, working out how they fit together and creating a 3D model in which you can navigate around them. Our set of photos is 71% “synthy” – a measure of how we matched they are – pretty good I’d say! The one negative thing is that viewing the resulting photosynth requires Silverlight on the browser.

Photosynth of Edge Hill

Another new development that’s being released for the first time on this site is a video browser. The observant may have noticed last week video pages on the Edge Hill site changed slightly, doubling the size of the video and moving around some elements on the page. This was to allow us to highlight related videos right along side.

Video player

One final little thing we’ve incorporated into this site is embedding the PDF of exhibition boards – normally a sizable download – into the page using Scribd. Using third party hosted services has risks associated with it but here it clearly benefits the user to be able to quickly scan through pages without the need to download a large file and open in Acrobat.

Aptana Outline Auto-Expansion Monkeyed!

You may have seen my last post Monkeying with my outline! where I apparently managed to get Aptana automatically expanding my outline whenever I viewed a new file in the editor. Well… it didn’t quite go to plan. Long story short, the script only executed properly when it was loaded after editing in the script editor, not when Aptana loaded up at the start. Details here in the Aptana scripting forum. I was rescued by Kevin Lindsey. Above and beyond the run of the mill support, he even emailed me to let me know he’d snuck the fix into 1.2. It’s working brilliantly! So now here’s my code with the updated bits from Kevin, I’ve commented out all the println’s cause I like a clean console.

/*
 *
 * Menu: EHU > HandlerService (Auto expand outline)
 * Kudos: Ingo Muschenetz & Kevin Lindsey & Steve Daniels
 * License: EPL 1.0
 * Listener: getPartService().addPartListener(this);
 * DOM: http://localhost/com.aptana.ide.scripting
 * DOM: http://download.eclipse.org/technology/dash/update/org.eclipse.eclipsemonkey.lang.javascript
 *
 *
*/
 
function getPartService()
{
    var workbench = Packages.org.eclipse.ui.PlatformUI.getWorkbench();
    var result = null;
 
    if (workbench)
    {
        var window = null;
 
        runOnUIThread(function() {
            window = workbench.getActiveWorkbenchWindow();
 
            if (window != null)
            {
                result = window.getPartService();
                //out.println("result set to " + result);
            }
            else
            {
                //out.println("window is not defined");
            }
        });
    }
    else
    {
        //out.println("workbench is not defined");
    }
 
    //out.println("getPartService() is returning " + result);
 
    return result;
}
 
function partBroughtToTop(part)
{
  //out.println("part*()\n");
}  
 
function partClosed(part)
{
  //out.println("part*()\n");
}
 
function partDeactivated(part)
{
  //out.println("part*()\n");
}  
 
function partOpened(part)
{
  //out.println("part*()\n");
}
 
function partActivated(part)
{
  if (part.getEditorInput)
  {
    expandOutline();
  }
}
 
function partVisible(part)
{
  //out.println("part*()\n");
}
 
function partHidden(part)
{
  //out.println("part*()\n");
}
 
function expandOutline()
{
  //out.println("expandOutline()\n");
  try
  {
    //out.println("try\n");
    var editor = editors.activeEditor.textEditor;
 
    editor.getOutlinePage().getTreeViewer().expandAll();
  }
  catch (e)
  {
    //out.println("catch\n");
  }
}

Enjoy 🙂

Steve Daniels

Rose tinted json

Lately, we have been looking at providing a little automation to parts of the site which are less dynamic, by using some of the data serialisations that we create, with a sprinkling of javaScript magic.  Specifically we’ve looked at pulling Edge Hill event data, tagged with “rose theatre” into the Rose Theatre site.

This week I will be mostly using jsonCurrently events are added to the events Edge Hill events data, which can be duplicated. Our data serialisations come in four flavours, XML, JSON, PHP and YAML.

This week I have been mostly using JSON.

JSON is javaScript, and doesn’t need a server.  It runs on the site visitor’s browser (if enabled) and provides a way for us to access dynamic data and publish it on static web pages.

The first stage was to create the JSON feed.  Since Edge Hill already has data serialisations for Events and News, all I needed to do was to tweak it a bit and add a new function to the database to return events tagged with “rose theatre” and add a new URL to access the results which look something like this:

[{
	"title":"Alternative Stand Up",
	"slug":"alternative-stand-up",
	"summary":"Comedy at the Rose Theatre.",
	"content":"<p>Tickets \u00a35.50 \/ \u00a33.50 concessions<p><strong>Jamie Sutherland<p>One of the freshest and most natural talents to emerge in the last few years, Jamie has truly established himself on the comedy circuit, and is now very much in demand all over the UK.\u00a0 Liverpool born Jamie will keep you amused with gags, tall tales, and true stories garnered from everyday observational topics.<p><strong>Danny McLoughlin<p>Danny is a complete natural and destined for the top.\u00a0 Think Peter Kay for the confidence factor.<p><strong>Rosie Wilby<p>Rosie Wilby has been performing as a singer songwriter for many years and turned to comedy in 2004, storming through to the semi finals of So You Think You're Funny, on only her second ever stand up gig.\u00a0 In August 2006, Rosie unveiled her debut full length show \u2018Olympic Swingball Champion 2012' at Edinburgh Fringe.<p>Compere.....<p><strong>Ste Porter<p>A top class act who will be a regular comedy circuit favourite before long.\u00a0 See him in Ormskirk first!<p>For further information or to book, call 01695 584480 or email <a>rose@edgehill.ac.uk.",
	"start_date":"2008-10-07",
	"start_time":"20:00:00",
	"end_date":"2008-10-07",
	"end_time":"22:00:00",
	"location":7,
	"created_at":"2008-08-13 14:04:28",
	"updated_at":"2008-08-14 13:46:40",
	"building":"",
	"url":"http:\/\/www.edgehill.ac.uk\/events\/2008\/10\/07\/alternative-stand-up\/json",
	"tags":{
		"Stand Up":"Stand Up",
		"comedy":"comedy",
		"rose theatre":"rose theatre"
	}
}]

Next, add the following code to the html document into which you want to add the data feed:

<div id="rtevents">
  <h3>Next up</h3>
  <p>
    The Rose Theatre's <a href="/events/tag/rose theatre" title="List of events for the rose Theate">upcoming events</a>
  </p>
</div>

The div with the id of “rtevents” acts as a placeholder for the code which will be inserted. At this point, a level 3 heading has been applied with a link to the events page. This gives visitors without javascript capabilities a way of viewing the events (in this case a link to events for the rose theatre page).

In addition to the tags, the jQuery library was added. jQuery has a ready-made method for “getting” a JSON feed and the documentation is detailed, yet simple enough to get you started with a working example.  Using that example, I wrote:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  $(document).ready(function(){
    $.getJSON(/events/tag/rose+theatre/json”, function(data){
      $(‘#rtevents’).html(<h3>Next up</h3>);
      $(‘#rtevents’).append(<table id="”eventrow”"></table>);
      $(‘#eventrow’).append(<tr><th>Date</th><th>Event</th><th>Time</th></tr>)
      $.each(data, function(i,data){
        urldate = data.start_date.substr(0, 4)+/+data.start_date.substr(5, 2)+/+data.start_date.substr(8, 2);
        date =<td>+data.start_date.substr(8, 2)+/+data.start_date.substr(5, 2)+</td>;
        time =<td>+data.start_time.substr(0, 5)+</td>;
        time = time ==<td>00:00</td>?<td>TBA</td>: time;
        oddeven = i % 2 == 0 ? ‘even’ : ‘odd’;
        $(“#eventrow”).append(<tr class="”‘+oddeven+‘”">+date+<td><a href="”/events/’+urldate+‘/’+data.slug+‘”">+data.title+</a></td>+time+</tr>);
        if (i == 5) {// sets the maximum number of records returned
          return false;
        }
      });
    });
  });

Let’s try to explain what’s going on here (row by row). The whole thing won’t work unless javascript is enabled in your browser.

  1. Line 1: A jQuery function which runs the javascript that follows it after the html page has loaded.
  2. Line 2: A jQuery call to the JSON feed and a function call to to tell the browser what to do with the data.
  3. Line 3: Find the element with the id “rtevents” and replace it’s contents with our <h3> element.
  4. Line 4-5: Append the table (named; “eventrow”) and table headers to the “rtevents” element (following the h3).
  5. Line 6: For each event returned in the JSON feed, do the following:
  6. Line 7-11: Format JSON data for output.
  7. Line 12: Append the table row to the table (named “eventrow”) with all the formatted data.
  8. Line 13-15: restrict the number of table rows returned if necessary.

Knowing this, you can parse any JSON feeds using jQuery, and there are plenty to choose from these days. A few examples:

Fancy yourself as a javaScript developer? Then add JSON to your bow strings.

Monkeying with my outline!

After having been here about 6 months I have finally succumbed to the pressure from my boss to make a blog post. Normally my ideas for such posts would be large and grand, take too long to type out, and slip into the infinite chasm that is otherwise known as a draft…

I like Aptana, I like the Outline view. What I don’t like is that you always have to expand it. So thus, I never used it, I’m simple and lazy, and not afraid to admit it. Andy Davies reignited my interest in the Outline view earlier today in a round about way. Andy pointed out the lesser noticed Scripts menu in Aptana. Specifically Experimental -> Colorize as HTML. A nice quick and neat tool. Not that I’d use it much mind. But then below its entry I saw “Expand outline”. Bingo!

What followed is my discovery of Monkey Script. I figured getting expand outline on a keyboard shorcut would be good, and perhaps renew my interest in it. But then I noticed the mention of listeners… Queue  a bit of creative Googlin and this post by Ingo on the PartService event handler.

Hacking the existing expand outline script into this proved painless so here we have it:

/*
 *
 * Menu: EHU &gt; HandlerService (Auto expand outline)
 * Kudos: Ingo Muschenetz &amp; Kevin Lindsey &amp; Steve Daniels
 * License: EPL 1.0
 * Listener: getPartService().addPartListener(this);
 * DOM: http://localhost/com.aptana.ide.scripting
 * DOM: http://download.eclipse.org/technology/dash/update/org.eclipse.eclipsemonkey.lang.javascript
 *
*/
 
function getPartService(){
  window = Packages.org.eclipse.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow();
 
  if (window != null) {
    return window.getPartService();
  }
}
 
function partBroughtToTop(part)
{
 
}  
 
function partClosed(part)
{
 
}
 
function partDeactivated(part)
{
 
}  
 
function partOpened(part)
{
 
}
 
function partActivated(part)
{
  if (part.getEditorInput)
  {
    expandOutline();
  }
}
 
function partVisible(part)
{
 
}
 
function partHidden(part)
{
 
}
 
function expandOutline()
{
  try
  {
    var editor = editors.activeEditor.textEditor;
 
    editor.getOutlinePage().getTreeViewer().expandAll();
  }
  catch (e)
  {
    out.println("Failed to expand outline.\n");
  }
}

You’ll notice I hooked the Activated event rather than the Opened one this was because on opening expandOutline executed before the active editor had switched to the new file so the outline was expended on an already opened file. This way has a slight caveat that if you collapse the outline and then go back to the file it’ll expand it again, but that doesn’t bother me at all.

To use the above script simply drop it in a file with a .js suffix and place it in a folder called “scripts” in a project that is currently open on your workspace. I created a new project just for this purpose.

I hope someone found this useful 🙂

Steve Daniels

@media2007: Nate Koechley: High Performance Web Pages

This was a presentation for developers rather than designers so I was expecting a lot of information to go over my head, it did, but enough has stuck to write a short post.

Nate Koechley is a Yahoo! frontend engineer and designer based in San Francisco. The bulk of his presentation was based around a twelve step programme to create quicker web pages.

  1. Make fewer HTTP requests: This refers to combining style sheets and scripts to reduce the amount of communication between your browser and the server. He also recommended using Image Maps, which I thought were considered old hat, but for icon driven navigation I can see how this could work in reducing the need for multiple images.
  2. Use a CDN: this stands for Content Delivery Network, a way of deploying content from multiple “CDN nodes”. This is important for increasing the page load times on sites with a lot of traffic such as MySpace, which uses Akamai.
  3. Add Expires Headers to cached content: This allows control of caching mechanisms in your browser and is important for dynamic content which has to be downloaded repeatedly because it is not cached correctly.
  4. gzip components: gzip is a software application used for file compression with 90% browser support. I use Photoshopto optimize images for the web, gzip can apparently compress them by a further 50%.
  5. CSS at the top of the document: Links to external style sheets should be placed high in the HTML document, and use link rel=”stylesheet” rather than @import for linking.
  6. Move Script Includes to the bottom of the document: Links to external JavaScript files should be put after the closing body tag. This recently adopted practice is a necessity because page downloads are paused until an externally linked script is fully loaded.
  7. Avoid CSS expressions: CSS expressions were introduced in Internet Explorer 5.0 and it allows you to to assign a JavaScript expression to a CSS property. CSS expressions aren’t generally used by designers who enjoy the clarity of basic CSS mark up.
  8. Always link to external CSS and JavaScript files
  9. Reduce DNS lookups: You can reduce Domain Name System (DNS) lookup traffic by using multiple hosts, therefore distributing content via parallel downloads.
  10. Minify Javascript: You can compress external CSS and JavaScript file sizes by eliminating white space. You can use a tool called ShrinkSafe to do this or you can do it safely by hand.
  11. Avoid page redirects
  12. Turn off ETags: ETags prevent pages from caching.