Posts tagged with 'jquery'

JavaScript: handy hint for jQuery document ready handlers

Like 99% of all jQuery users, I write the code I want executed when the document is ready like this:

$(function () {
  // code using $ for the jQuery function
});

Except… What happens if someone calls $.noConflict() and $ is no longer valid? Do I have to resort to using jQuery() all over the place, just to be sure?

Answer: no. It seems – and I only discovered this moments ago – the document ready handler gets passed the jQuery function as the first and only argument. You can write this instead:

jQuery(function ($) {
  // code using $ for the jQuery function
});

Or, if you are really paranoid:

jQuery(function ($, undefined) {
  // code using $ as the jQuery function
  // and undefined means what it says
});

Magic!

Album cover for 18Now playing:
Moby - Extreme Ways
(from 18)


Minor changes to look-and-feel

I’ve been meaning to do a bit of housework on this site to clean up the CSS and to add a bit of interactivity. After all, I write a lot about JavaScript, so I might as well start adding some to my blog.

Bansky street cleaner - Chalk Farmphoto © 2007 Dan Brady | more info (via: Wylio)First things first: if things look a little wacky for you, your browser is probably using the old CSS file. Refresh. That should force the new CSS file to be downloaded and used.

Second: the changes to the CSS are two-fold. The main impetus was to allow for the second rightmost sidebar to be hidden/shown. Originally both sidebars were absolutely positioned and so, to enable this new behavior, I had to float all three columns (content, sidebar 1, sidebar 2). That way, when the third column is hidden, the other two can grow/move correctly (and when it is shown, they can shrink/move back). The other main point of the CSS tweaking was to make the display of comments nicer. Previously the size of a single comment block was the maximum of the height of the metadata/avatar part to the left of the content or the height of the content itself. The first possibility made the gaps between comment blocks uneven and look bad, so I fixed this.

Third: I added some JavaScript and jQuery to allow that second sidebar to be hidden and shown. I’ve added an extra link on the “navigation bar” above that performs this task.

These changes should help those readers who are using a smaller screen (say, 1024 pixels wide) see the main content more easily. I have had a couple of emails complaining about the old layout, so these changes should alleviate the problem.

Now playing:
Heaven 17 - This Is Mine (2006 Digital Remaster)
(from Greatest Hits - Sight And Sound)


JavaScript for C# developers: writing a library (part 1)

From comments I received when I wrote my recent article over on my DevExpress ctodx blog, it seems there’s a need for people to understand how to write reusable code in the form of a library in JavaScript, and not fall into those nicely shaped C# potholes along the way. So I thought, let’s have a go. (Update: I’ve made a couple of corrections to point out the files this code appears in.)

Library of knowledgephoto © 2009 Shironeko Euro | more info (via: Wylio)Some ground rules first. The first is that I’m going to use jQuery. Although jQuery is perhaps best known as being a DOM manipulator library, I think it’s now almost de rigueur amongst people who use the Microsoft ASP.NET stack for writing web applications. My initial code won’t be doing much DOM manipulation, but I shall use jQuery nevertheless. The second is that I’m going to be using modern JavaScript best practices (no globals, use of closures, getting the code to pass JSLint on its default settings, thinking about performance, etc). The third is that, at the start, it will seem that I’m going overboard with single JS files, one per object, with all the performance problems that might entail in a “real” web site, but I shall be addressing that later on.

Onwards.

The first problem to solve is that of my global footprint. If you’ve read any of my writing about JavaScript in the past (say from my chapter on JavaScript in Professional DevExpress ASP.NET Controls), I’ve espoused minimizing the number of global variables you create. There are many reasons for this, many standard, many obvious, but this time in writing my library I want to reduce it to zero. Since my library has to be visible, er, globally, how should I do this? Well, I shall piggyback on another global object: the jQuery function. Yes, this is cheating to a certain extent (I’ll be creating a globally available object in a global object, essentially), but it’s accepted practice when you use jQuery.

Here’s the minimal code you need to write to create such an object:

  $.jmbLibrary = {};

The $ function (functions are objects, remember, so all I’m doing is adding a property) is a synonym for the jQuery function, and all I’ve done is to create an empty object called jmbLibrary as a property of that function. Seems pretty easy, until you realize that the $ identifier may clash with other libraries and jQuery has a way of disabling that identifier altogether (call jQuery.noConflict(false);). I am no longer writing code for a particular page, I’m writing reusable code that could be used everywhere, even on projects that I have no control over. However, the $ is such a nifty shorthand; surely there’s a way to keep it and not have clashes?

Enter a closure. (Admit it: you knew a closure was going to come up sooner or later.)

(function ($) {

  $.jmbLibrary = {};

})(jQuery);

Whoa. What’s going on here? In essence, I’m declaring an anonymous function, not assigning it to any variable, and executing it immediately passing in jQuery as its only parameter. But inside the function body that parameter is known as... our old friend $. (Well, OK, a new friend, but with the same name and the the same functionality.) Throughout that function scope, the jQuery function will be known as $, no matter what happens outside that function.

The reason for the function declaration being enclosed in parentheses is to ensure that the interpreter doesn’t try and parse this code as the start of a named function object like this: function foo() {...}.  We use the parentheses to avoid that confusion.

So now I have the very basic code for my library: a globally accessible object that doesn’t appear in the global scope. I’ve added this minimal code to a JavaScript file called jmbLibrary.js. Let’s add some real functionality to my library now.

The first library object I’m going to add to my library is an encapsulation of cookies. (The web versions, not the sugary crumbly things you bake in an oven; pay attention, people.) I’m going to create a cookie library object within my jmbLibrary object and it will have three methods: add, read, and remove (delete is a reserved word in JavaScript so I can’t use that too easily) to encapsulate the three main operations you can perform on a cookie. So I start off with this code in a file called jmbCookie.js:

(function ($) {

  var $j = $.jmbLibrary;
  var $jc = $j.cookie = {};

})(jQuery);

Same kind of code we’ve just become used to: an anonymous function, not saved but immediately executed in order to provide a closure inside which $ refers to jQuery. I’m declaring two local variables within this closure, one called $j, to refer to the library as a whole, and one called $jc to refer to a new empty object called cookie I’m creating in jmbLibrary. Yes, you guessed it, I like these shorthand names.

Note that our HTML file (which I’m not showing yet) will have to have the following script elements in the head element (I’ve created a Scripts folder for all these JavaScript files):

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
  <script src="Scripts/jmbLibrary.js" type="text/javascript"></script>
  <script src="Scripts/jmbCookie.js" type="text/javascript"></script>

Next time, we’ll take a look at the actual cookie code. Stay tuned.

Album cover for The Best of BlondieNow playing:
Blondie - Call Me {Theme from American Gigolo}
(from The Best of Blondie)


Extras

Search

About Me

I'm Julian M Bucknall, the M because it's my middle initial and because I and the other Julian Bucknall (the movie guy) would like to differentiate ourselves.

I'm a programmer by trade, an actor by ambition, and an algorithms guy by osmosis. I write articles for PCPlus in my spare time, not that there's much of that.

Julian M Bucknall Apart from that, an ex-pat Brit, atheist, microbrew enthusiast, Pet Shop Boys fanboy, slide rule and HP calculator collector, amateur photographer, Altoids muncher.

DevExpress

I'm Chief Technology Officer at Developer Express, a software company that writes some great controls and tools for .NET and Delphi. I'm responsible for the technology oversight and vision of the company.

Validation

Validate markup as HTML5 (beta)     Validate CSS

Bottom swirl

Archives

May 2012 (4)
SMTWTFS
« Apr  
12345
6789101112
13141516171819
20212223242526
2728293031

Like this Archive Calendar widget? Download it here.

Social networking

The OUT Campaign

The OUT Campaign

My Tweets

  • Honest Movie Trailer of Phantom Menace http://t.co/sif8y4Ns and then Battleship, er, Transformers http://t.co/sif8y4Ns
  • Damn, Donna Summer and Chuck Brown both gone in the last 24 hours. Different types of music, sure, but enjoyed them both. :(
  • Just saw a company page showing a list of tweets with "Join the conversation" linked to their Twitter a/c. The tweets are 6 months old #fail
Bottom swirl