Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Tuesday, 20 July 2010

Quick Tip – Optimizing DOM Traversal » Learning jQuery - Tips, Techniques, Tutorials

The topic of optimization has come up a number of times in the jQuery mailing list. jQuery’s DOM traversal is powerful and easy, but it can sometimes be slow as well. As with any JavaScript library or framework, the helper methods will be slower than the plain old JavaScript (p.o.j) methods. Nevertheless, if we keep in mind the jQuery’s speed hierarchy, the speed difference between jQuery and p.o.j. will often be negligible.

The “speed hierarchy” goes like this, in order of fastest to slowest:

  1. ID : $(‘#some-id’)
  2. Element : $(‘div’)
  3. Class : $(‘.some-class’)

jQuery uses JavaScript’s native getElementById() to find an ID in the document. It’s fast — probably the single fastest way to find something in the DOM — because it’s only looking for a single unique thing, and it’ll stop looking once it has found it. So, if we have <h2 id="title">This is my title</h2>, we would use $('#title'), not $('h2#title') to access it.

To find a bare class name, as in #3 above, jQuery goes through every element in the entire DOM. To find an element, on the other hand, it uses getElementsByTagName(), thereby limiting the number of elements it has to traverse right from the start. Therefore, if we know which element the class is tied to, we can speed up the traversal significantly by referring to it, using, for example, $('div.some-class') rather than $('.some-class').

Likewise, we can help jQuery gather our classes faster if we can limit where jQuery looks to a particular ID: $('#sidebar .menu'), not $('.menu').

I’m sure there other ways to make DOM traversal speedier, so if anyone knows any other tricks, I’d love to see them in the comments. Also, I should probably reiterate that if speed is all you care about, no library/framework is going to beat p.o.j.

Update: Motivated by enej’s comment, I put together a little speed-test page where you can try out a number of different DOM queries and see how fast they are. Since I posted a link to the page on the jQuery mailing list, there has been quite a bit of activity in this area. Aaron Heimlich extended the speed test to work in conjunction with Firebug for some awesome reporting, and rumor has it that Yehuda Katz is working on an entire speed-test suite.

Update

Please be aware that these optimizations are not necessarily helpful as of jQuery 1.3 because of the new “Sizzle” selector engine.

A handy tip for those who are interested in speeding up their jQuery code. It may seem obvious, but I've had a conversation about this in the last couple of days, so thought it would be handy to post!

Posted via email from Mark Kennard's Posterous

Friday, 20 March 2009

Playing with the JavaScript Date Object

I've been working on a couple of projects that require manipulation of the date strings in one way or another, and one of the things I wanted to achieve was to show a posting date in a list built from RSS, but this meant I would need to convert ISO Date format used in the Blogger RSS feed to a prettier format.

After a bit of Googling and tweaking code, I found a solution, which I will post at a later date, but in the meantime, here's a list of a few useful links relating to manipulating dates using JavaScript.
  1. DateJs - Very useful little JavaScript utility for working with dates.
  2. Parsing W3C's ISO 8601 Date/Times in JavaScript - Useful script that uses Regular Expressions to handle ISO Format Dates.
  3. JavaScript Date Object -Estelle Weyl's useful article giving an overview of the JavaScript date object.
  4. JavaScript Toolbox Date Formating - A useful library contains functions to deal with dates in Javascript, parse date strings, format dates to different output strings, and compare dates.
  5. JavaScript Pretty Date - John Resiq's function to convert dates to "web 2.0" style strings, eg Something like "2008-01-28T20:24:17Z" would become "2 hours ago".
  6. JavaScript ISO8601/RFC3339 Date Parser -Another approach to formatting ISO dates.
  7. PHPDate - Jon Combe's jQuery port of PHP's Date function. Very useful!
  8. JavaScript Source Date & Time - A list of scripts that might come in handy for some readers.
  9. JavaScript date string formatting - Svend Tofte's interesting script. again, based on PHP's date function.
  10. JavaScript Date Formatting - An Unorthodox Way -Most date formatting implementations use format strings where format specifiers like “mm”, “mmm”, “HH”, etc. are used for selecting different components of a date. Ates Goral tackles the date object from a different angle.

Wednesday, 11 March 2009

Essential jQuery Controls

I've been doing an awful lot of jQuery coding of late, and at last, jQuery has been elected weapon of choice by other developers on the team too. As a result, it's been interesting seeing what some of the other guys are playing with.

JP sent me these links today. If you need some good jQuery interface controls, start below...

30 Essential Controls
: Theresa Neil gives a good breakdown on 30 essential interface controls including AutoSuggest, Charts & Graphs, Dialogs, Comboxes etc, and which JavaScript libraries support them. Handy.

Essential Controls List : If, like me, you work almost exclusively with jQuery, this page lists the Essential Controls for jQuery, and where you can find them. REALLY handy!

Tuesday, 4 November 2008

John Resig Talks JavaScript and jQuery

I found this video last night, featuring John Resig giving a talk at Northeastern University about JavaScript and jQuery. As the brains behind the fantastic jQuery library, this video is a great opportunity to get the lown-down and some hints and tips "straight from the horse's mouth".




Well worth watching, even if it is little "dry" for non-techies or designers.

Sunday, 2 November 2008

More than one way to skin a cat, continued...

Part 3 Using jQuery.AJAX() to load data and catch loading errors

Well, after a bit of a delay, here's the third part of my tutorial (part 1, part 2) demonstrating different ways of achieving the same result. In this part, I am going to use some more jQuery and CSS to build on what we coded in the last installment, and we are going to use the jQuery.ajax() function to add a bit more sophistication to our word generator.

Step 1 Create your HTML document.

First, we need an HTML document to contain and update our externally loaded content. Our page will contain a display area for the loaded text, and a button which will update the page on demand. It should look something like this...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Random words</title>

</head>

<body>

<div id="displayRandomWords"></div>

<div id="displayUpdateButton"></div>

</body>

</html>
Step 2. Add the jQuery library to your page.

As we will be calling upon the magic of jQuery again, we need to include the library in the head of our HTML so, add the following to the head of your page...

<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
Step 3 Write the code to do the clever stuff...

Now for the interesting bit. We need to create a function to call the random_words.asp, and if it loads successfully, display the output. We also need a nice preloading graphic to let users know that something is happening, and finally a link to reload new random words, so in your favourite editor, create a .js file as follows, and save it as jq_name_gen_part2.js
// Once the browser is loaded and ready to go...
$(document).ready(function(){

//define the getData function, to handle the data process....
function getData(){
// show the preload graphic....
$('#displayRandomWords').html('<img src="ajax-loader.gif" />');
// get rid of content from link button - It's not needed while data is loading...
$('#displayUpdateButton').empty;
// now setup the jQuery.AJAX function
$.ajax({
// type can be GET or POST....
type: "GET",
// file name of data to be loaded...
url: "random_words.asp",
// dataType - Use this to prevent unexpected results with loaded data
dataType: "HTML",
// Define function that fires when data is successfully loaded...
success: function(data){
// Build the Reload link...
$('#displayUpdateButton').html('<a href="#" id="aReloadData">Reload...</a>');
// Display the output from our server-side script...
$('#displayRandomWords').html('<strong>'+ data +'</strong>');
// setup the click event handler for the reload button...
$('#aReloadData').click(function(event){
// fire the getData function on click to reload new words...
getData();
})
},
// a simple bit of error trapping. If there is problem loading the data, show an error message...
error: function(){
$('#displayRandomWords').html('Oops, we seem to have hit an error!');
}
});
};
//Fire the getData function first time out to populate the elements onLoad....
getData();
});
Step 4: Make sure your .js file is included in the head of your HTML document, below your call for jQuery itself.Your HTML should now look like the following piece of code. Notice I have also included a CSS file to make it look a bit nicer too. You can download all the source code for this part of the tutorial from here.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link href="name_generator_demo.css" rel="stylesheet" type="text/css" />

<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>

<script src="jq_name_gen_part2.js" type="text/javascript"></script>

<title>Random words</title>

</head>

<body>

<div id="displayRandomWords"></div>

<div id="displayUpdateButton"></div>

</body>

</html>

If you want to see it all running in your browser, click here...

In the next part, I will show how to use Flash and Actionscript 2 to load and display external data, so check back soon.

Monday, 13 October 2008

jQuery enhanced HTML lists

I was playing around with CSS and ordered lists this evening, trying to make an ordered list with large item numbers and small list item text, and after much messing around discovered that what I was trying to achieve isn't really possible using just CSS and the OL or UL tags, and, after using jQuery for a while now, thought I'd have a go at creating a plugin to solve my problem.

It's nothing very complex, but it does the job. It simply looks at an OL or UL, strips out the HTML content of the child LI elements, and replaces the OL or UL with DIVS. This allows me to use CSS to style the numbers and text separately, using progressive enhancement. You can see a demo here.

Usage

To use it simply include jQuery in the head of your document...

<script src="your_path_to_jquery/jquery.min.js" type="text/javascript"></script>

Below that, include the jquery.enhanceList.js file...

<script src="your_path_to_jquery/jquery_enhanceList.js" type="text/javascript"></script>

Make sure you have the following CSS classes in your stylesheet, feel free to tweak it to your design requirements!...

.olContainer {
width: 450px;
margin: 5px;
border-bottom:1px dotted #cccccc;
padding-top:10px;
}
.olNumber {
font: 700 220% / 1 Georgia, "Times New Roman", Times, serif;
width: 30px;
margin: 0 10px 0px 10px;
text-align: center;
float: left;
position: relative;
padding: 0 10 10 10;
}
.olText {
white-space: normal;
font: 400 100% / 1 Arial, Helvetica, sans-serif;
padding: 0 0 10px 10px;
line-height: 1.5em;
}
.clearFix {
clear: both;
}

In your HTML document, you will need an ordered or unordered list, in my example, I am giving the target list a class called "enhance" to use as a selector...

<ol class="enhance">

<li>This is the first item, Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tatio</li>

<li>This is the second item Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tatio</li>

<li> Third item...Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tatio</li>

<li>Fourth item...Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tatio</li>

<li>Fifth item..Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tatio</li>

<li>Sixth item...Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tatio</li>

</ol>

It is a good idea to use an external javascript file to contain your code, rather than have script in your HTML document, so create a new .js file as follows, and save it as enhance.js in your sites script directory,...

$(document).ready(function(){
$('#activeEnhance').click(function(event){
$('ol.enhance').enhanceList()
})

Then include it in the head of your HTML page...

<script src="your_path_to_jquery/enhance.js" type="text/javascript"></script>

Thats it. All you have to do now is run it! I hope you find it useful. Feel free to let me know your thoughts on this. You can download sample code, and the plugin here

03 Nov 2008 Update: A visitor contacted me to let me know that my posted source code didnt work out "out of the box" - this was due to my source HTML referring to jQuery 1.2.6 which wasnt included in the zip. This has now been fixed. Apologies to you if you downloaded it and had problems due to this oversight!

Powered by ScribeFire.

Useful jQuery Plugins

I use jQuery pretty much every day at work, and in personal projects. I love the way it allows me to add rich functionality and effects to my projects, without much hard-core coding (well, unless I'm trying to be a smart-arse!).

So in true spirit of the Blogosphere, I thought I'd compile the top 10 list of my current favourite useful jQuery plugins...

  1. Dimensions - This is one of the best. It extends jQuery with dimension specific methods. With it, you can get dimensions (height and width) of the window, the document, and individual elements, and find the co-ordinates (offsets) of any element in a web page. VERY useful.
  2. Cookie - I use this one quite a lot, it makes manipulating cookies a breeze. Go get it!
  3. jQuery UI - This is really a collection of plugins rather than one (but you can create your own build so you don't have to include the whole collection), but highlights include a variety of visual effects, including Fold, Slides, Explode, Pulsate, Puff and more, as well as some really slick ui elements such as a rather tasty SplitPane and Drag and Drop behaviours. Nice.
  4. Media - This is a very cool one, it allows for unobrusive embedding of media including Flash, Quicktime and Silverlight into documents. Highly recommended.
  5. labelOver - Another one in my regular jQuery toolkit, this allows you place the label over the input field, using CSS. It is based on a very good article on A List Apart about Making Compact Forms More Accessible
  6. Validation - Anyone involved in the development of web applications needs a good validation script, and this is a great jQuery plugin that does just that. I hate ugly forms and JavaScript alerts, which is why I can't code a form without at least considering using this plugin. In short, don't leave home without it!
  7. tableSorter - Sometimes, you can't avoid using tables, particularly for displaying data, and this plugin allows for all sorts of table tomfoolery, from basic column sorting to appending the table data using Ajax.
  8. Form - This useful plugin lets you enhance forms to submit using AJAX. No special mark-up required, just include the plugin and write your callback. We like it!
  9. Field - If you need to manipulate form fields beyond the standard val() method, this is the plugin for you!
  10. XML to JSON - This is a cool utility if you work with Ajax and XML documents. Does what it says on the tin!
I could have easily made this a top 20 list, as there are so many good plugins out there, but then I would'nt have enough for my next list, but I hope you found at least one useful addition to your jquery library.

Tuesday, 7 October 2008

Here's a cute little bug...

This one drove me mad today. I'm working on a slide/reveal panel mechanism for an project under development at work, using jQuery, and almost straight away, everything worked perfectly in Firefox (once I'd sussed the HTML mark-up needed anyway!).

However, nothing seemed to happening at all when I tested in IE7, and the only clue IE would give me was a somewhat cryptic "Expected identifier, string or number".

Huh? What's that supposed to mean?

Well, a bit of Googling and I found the solution. According to Cow at NeoDragon it's an IE issue (surprise surprise)...

"In Javascript you have lists like:


var list = { opacity: 0.5, height: 0.5} 

Similar syntax is used to group functions:


var MyFuncs = {foo: function() {},bar:function() {},} 

The above code should work fine in real web browsers such as Firefox. IE will give a screwed up error such as "Expected identifier, string or number". Just remove the comma after the last function and the error be gone."

Nice one Cow!! (I couldnt find the authors real name, but please let me know if you do!)



Powered by ScribeFire.

Monday, 6 October 2008

More than one way to skin a cat, continued...

Part 2: Loading external data into a web page using jQuery.

In part 1 we setup our ASP page to spit out random words on demand, so now we can start examining the various methods of getting the random words into our web pages.

Seeing as I am a jQuery nut, I'm going to demonstrate the jQuery way first (well, one of a few). If you've not played with jQuery yet, this might convince you to have a go.

Step 1: Include the jQuery library in the head of your web page
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
Step 2: Create a DIV in your page to contain the generated words
<div id="displayRandomWords"></div>
Step 3: Write the code to do the clever stuff..

Using your preferred text editor, create a new .js file and add the following code, then save it as jq_name_gen.js in the same directory as your html file.

// This is a basic "when everything is ready..."
$(document).ready(function(){

// This line tells jQuery to find an element with the ID 'displayRandomWords' and
// then to load the output from our ASP page into it. In one line of code!
$('#displayRandomWords').load('random_words.asp')
});

Step 4: Include your js in the head of your document

<script src="jq_name_gen.js" type="text/javascript"></script>

You should now have an HTML file that looks something like this...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script src="jq_name_gen.js" type="text/javascript"></script>
<title>Random words</title>
</head>
<body>
<div id="displayRandomWords"></div>
</body>
</html>
When you run the page in your web browser (on the server, as the ASP won't run locally remember!) you should see the random words magically appearing in your DIV. Click here to see it running.

Simple huh? To be honest, I have simplified things here to demonstrate some of the cool stuff without boring you with geeky stuff. Things to bear in mind include the fact that you can only load data from the documents parent domain (if you want to load from a different domain you will need a server-side proxy, check back soon for an example), and there is nothing in place to check to make sure the data has loaded. We'll cover that in a later tutorial, along with handling other types of data, including JSON and XML.

So, thats the first way of skinning our "loading external data" cat, in part 3 of this tutorial I will be using CSS and jQuery to make this widget a little more interesting.


Powered by ScribeFire.

Adding Code Snippets to Blogger posts

In my previous post I wanted to include some sample code, but wanted to have highlighted and include line numbers. Well, after some scooting around, it seems I'm not the only one who wants be able to add "pretty" code snippets to some of my posts. I'm quite surpised that it hasnt been implmented as a piece of standard Blogger functionlality, but it's not, so the next best thing can be found at http://code.google.com/p/syntaxhighlighter/

This cool library allows you to use <pre> tags containing your code and it will add highlighting and line numbers to your snippets, for a variety of different languages, including Visual Basic, Python, CSharp and JavaScript. Nice.

If you want to see how to implement it on Blogger, have a look at Timothy Broder's blog GPowered. Give it a go, its well worth it.