Posts Tagged ‘jQuery’

jQuery plugin to show and hide vertical menus

Tuesday, July 20th, 2010

It’s very common for us to show and hide vertical menus when developing sites. This idiom is particularly common on sites with a lot of submenus, such as e-commerce shopping carts.

Since it’s a technique we use so frequently, we decided to write a little jQuery plugin to make life easier for ourselves. This plugin takes nested unordered lists and turns them into expandable and contractable menus.

The plugin has the following features:

  • Dual licenced under GPL / MIT licences – do what you want with this code (as long as you leave the licence intact!)
  • Lightweight (~2Kb packed)
  • Keyboard accessible, basic WAI-ARIA support. Usable with JavaScript switched off.
  • Easy to use and deploy
  • Configurable through CSS, callback functions and numerous options

Please note that this plugin optionally uses of Klaus Hartl‘s excellent jquery.cookie.js plugin.

You can download the plugin here, and view the docs, and an example here.

jQuery 1.4 Reference Guide review

Tuesday, March 16th, 2010

In the interests of full disclosure, Packt Publishing sent me a copy of this book for me to review. There was no other compensation received for this review. I am reviewing this book for the benefit of the blog readers.

The recent release of jQuery 1.4 brought a plethora of new features and major performance improvements across the board. At the same time, the new jQuery API site was launched in an effort to improve the documentation and community spirit. Make no mistake, 1.4 is a milestone release for jQuery.

To mark this, Karl Swedberg and Jonathan Chaffer have released the jQuery 1.4 Reference Guide, an exhaustive tour of the functionality that jQuery 1.4 offers. There are eleven chapters, covering selectors, DOM traversal and manipulation, events, effects, AJAX, plug-ins, and more. In addition, there’s an alphabetical API reference guide and a couple of really useful appendixes providing lots of handy information.

As I mentioned above, each chapter groups together jQuery methods with a common theme. There are helpful code samples for each method, and they are explained thoroughly in the accompanying text. Occasionally, performance tips are mentioned, but as the book stresses early on, you shouldn’t worry too much about micro-optimizing code – your time as a developer is more valuable than that!

So who is this book aimed at? Well, as the name suggests, this is a reference guide. A familiarity with jQuery syntax is essential, and in some areas, a decent knowledge of vanilla JavaScript will be beneficial too. Although there are hints and tips peppered throughout the book, this is no tutorial book. If you’re not familiar with jQuery, you should pick up Learning jQuery instead, by the same authors.

As such, I would recommend this to the intermediate to advanced jQuery user. You will almost certainly learn something from the book, and a reference guide always comes in handy! Some of the major points I picked up were:

  • Many jQuery methods accept anonymous functions as parameters now – this is a really clean, practical way of writing code
  • There are more ways to measure elements than I realised – I knew about .height() and .width(), but not .innerHeight(), .outerHeight() etc. This has caused me problems in the past!
  • The Sizzle selector engine is really, really powerful and I’m not using it to its full potential.

The downside of a book like this is that it dates relatively quickly. For example, jQuery 1.4.2 introduced two methods – .delegate() and .undelegate() – which are not covered in the book. There’s no getting around this when the library itself is under heavy development, but it’s something that you should be aware of if you’re considering purchasing.

I also spotted one error  that I reported at the publisher’s website, so if you do purchase this book, you should keep an eye on the errata there.

However, if you’re looking for a jQuery reference guide, this is the book to own. The publishers will donate to the jQuery project for every copy of the book sold and you will learn something from this book, so it’s a win-win situation! The jQuery Reference Guide is on sale now, with a cover price of £24.99.

jQuery UI 1.7 – The User Interface library for jQuery – reviewed

Thursday, February 25th, 2010

jQuery UI 1.7 by Dan Wellman

jQuery UI 1.7 by Dan Wellman

jQuery UI is the official interface library for jQuery, the leading JavaScript framework. Dan Wellman‘s book, jQuery UI 1.7 – The User Interface library for jQuery, is intended to be the ‘missing manual’ – fleshing out the online documentation with examples, tutorials, and an in-depth look at the API. The book is supported by many great code samples, which are available at Packt’s support site.

There are thirteen chapters in total, covering the high-level widgets (such as the accordion) and low-level widgets (such as the draggable and droppable interaction helpers.) In addition, the CSS and effects frameworks are covered too.

No knowledge of jQuery UI is assumed, although it is expected that the reader will have a decent grasp of HTML, CSS, and jQuery. The book is pitched at the beginner to intermediate level jQuery UI user, although I would think that even advanced users will find that it contains valuable information.

The structure of each chapter is similar. Starting with the most basic example to get you up and running, more options are gradually introduced to give you a greater level of control, with plenty of code samples to help you along. Most chapters finish with a more advanced scenario, showing some really imaginative uses in which jQuery UI shines. For example, the drag and drop chapter walks the reader through creating a simple game.

The book also takes the time to describe some of the rare occasions where cross-browser issues might rear their heads, along with the fixes. It would have been easy for the author to skip past those parts, but I appreciated this honest approach. It may not be the sexiest subject matter, but it’s something that we as web developers deal with on a day-to-day basis, so it was great to see it tackled in the book.

One of the major strengths of jQuery UI is its online documentation; there are several examples for each widget, and options and methods are well documented. I was initially a little concerned about what the book could add to this, but my concerns were unfounded. Every chapter revealed methods and options that I had missed, along with examples that used the library in ways I would never have thought of.

One of the biggest revelations to me was the chapter relating to the CSS framework. Although I’d used Themeroller before, I’d never appreciated the full extent to which it can be used, creating a consistent look and feel throughout your site and containing many valuable helper classes.

One area where I would have liked to see some information is that of extending jQuery UI. I would have liked to have read about writing your own widgets, inheriting from $.widget, but I appreciate that this would probably be out of scope for this type of book.

Although jQuery UI 1.8 is just round the corner, I would have no hesitation in recommending this book. There is a wealth of information here, and it is presented in such a way that the reader is given a real understanding of the library, meaning that you won’t have any problems when the next version rolls along. In fact, if you read this book now, you’ll be well prepared for all the goodies that 1.8 contains!

So if you’re looking for a jQuery UI book, you should definitely check this one out!

Accessible AJAX forms with jQuery

Monday, June 22nd, 2009

Unless you’ve buried your head in the sand for the last few years, you must have noticed the increased use of Javascript on the web.

One of the most common criticisms levelled against the increased use of Javascript is that it makes accessible web design difficult, or even impossible. This doesn’t have to be the case though – let’s take a look at how progressive enhancement techniques can improve usability without sacrificing accessibility.

The concept is straightforward – make sure that everything works without Javascript, then use Javascript to add the ‘icing on the cake’.

Basically, all the content and functionality on your site should be accessible to your users, regardless of whether Javascript is switched on or off. This not only has benefits for accessibility, but for SEO too.

In this example, I’m going to take a very plain, simple form and add a little bit of magic!

The HTML

<div id="form">
    <form action="" method="post" name="contact-form">
        <label for="name">Your name:</label>
        <input type="text" name="name" id="name" />

        <label for="email">Your email address:</label>
        <input type="text" name="email" id="email" />
        <input type="submit" name="submit" value="submit" />
    </form>
</div>

<div id="results"></div>

The jQuery

$(document).ready(function(){
    $('form[name="contact-form"]').submit(function(event){
        event.preventDefault();

        var myName    = $('input#name').val();
        var myEmail   = $('input#email').val(); 

        $.post('process.php', {name: myName, email: myEmail},
            function(data){
                $('div#results').html(data).fadeOut().fadeIn();
            }
        )
    })
})

Hopefully there’s nothing too scary in the HTML; a couple of input fields and an empty div that will hold our results.

In the javascript, the important parts are lines two and three. Notice that we’re intercepting the form submission, and passing the event as an argument to the following function.

Next, we call event.preventDefault(). This stops events from bubbling up the DOM, in this case, preventing the form from being submitted.

Next, we fire off an AJAX request to process the form. In this case, we’re just echoing out the values that have been entered by the user, but this could be a contact form, a login form, an ‘add to cart’ button – the possibilities are endless!

You can view the demo here.

Note that the form works with or without javascript. Test it yourself by turning javascript off!

I hope this explains the basics of progressive enhancement. For further reading, check out wikipedia’s entry on the subject.

PeriodicalUpdater for jQuery

Monday, March 9th, 2009

Here at 360innovate we’ve benefitted greatly from free and open source software.

Whether it’s the web server our sites run on or the operating system that runs the web server, free and open source software plays a huge part in the industry we work in.

And so, we present this jQuery plugin in an effort to give a little something back!

The Prototype javascript library features a very useful PeriodicalUpdater() function. This loads content at specified intervals, but if the content being pulled in doesn’t change, the interval gradually increases.

There are several benefits to this approach – it saves bandwidth, and can reduce the CPU usage on the client’s machine.

Unfortunately, there’s been no way to replicate this using jQuery…until now!

Let’s take a look at how it works.

Step 1 – Include the latest version of jQuery and the plugin.

<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="jquery.periodicalupdater.js" type="text/javascript"></script>

Step 2 – call the function with the necessary options and a callback function

$(document).ready(function(){
   $.PeriodicalUpdater({
      url : 'random.php'
   },
   function(data){
      var myHtml = 'The data returned from the server was: ' + data + '';
      $('#results').append(myHtml);
   });
})

Here’s a list of all the options you can set:

url
URL for the ajax request. (Required!)

method
Can be either get or post. (Or GET or POST!)

sendData
Array of values to be passed to the page – e.g. {name: “John”, greeting: “hello”}

minTimeout
Starting value for the timeout in milliseconds.

maxTimeout
Maximum length of time between requests.

multiplier
Sets the amount of decay between ajax requests. If this is set to 2, the length of time between each request will double while the response doesn’t change.

type
Response type – can be text, xml, json etc – as with jquery.get or jquery.post.

Step 3 – Stop the requests!

Finally, you might want to stop ajax requests from PeriodicalUpdater – you can do so like this (assuming you had a link with id stop):

$('a#stop').click(function(e){
   e.preventDefault();
   clearTimeout(PeriodicalTimer);
})

We hope you find this plugin useful. It’s dual licensed under the GPL and MIT licences (just like jQuery), so please read them before you use this plugin.

View the demonstration

Download the plugin