Rey Bango

JavaScript, HTML, CSS & Random Stuff…

How to Easily Inject jQuery into any Web Page

I use jQuery…a lot. It just makes JavaScript development much easier for me. Every so often, I may come across a site where I want to poke around and see what’s going on under the hood. In many cases, jQuery is being used so it’s simple to spark up Firebug and leverage jQuery to work with a document. While jQuery is very pervasive, there are still plenty of sites that don’t use it which forces me to go back to plain ‘ole JavaScript. There’s nothing wrong with that but I’ve gotten used to the nice, terse syntax jQuery provides and I’d like to be able to use it.

Awhile back, I came across an awesome bookmarklet created by my jQuery teammate, Karl Swedberg, which allows me to inject the latest version of jQuery right into my page. This is great when you want to work with a page which doesn’t have jQuery included and you either don’t own the page or don’t feel like adding a script tag to it. The code below shows how the jQuery lib is included.

It’s fairly straightforward in that a script element is created:

var script=document.createElement('script');

and the script tag’s src attribute is set with the following URL:

‘http://code.jquery.com/jquery-latest.min.js’

Then, they grab a reference to the document’s head DOM element:

var head=document.getElementsByTagName('head')[0]...;

and then insert the new script tag into the head of the document.

head.appendChild(script);

That was a very high-level explanation because there’s definitely more going on. In fact, Karl took the extra step of ensuring that jQuery’s .noConflict() method is called should there be another library present that requires the “$” namespace. Very cool. :)

Now, this leverages the latest minified version from the jQuery repo but you should be able to easily include a version of jQuery from the Microsoft or Google CDNs if that’s your preference:

Microsoft: http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js
Google: http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

You can find the full source for the bookmarklet below and if you want to install it now, here’s the link for you to use:

» jQuerify «– Drag this link to your browser toolbar

I created a quick screencast that shows you how to add the bookmarklet to your browser and then use it for playing with a web page:

Nicely formatted bookmarklet code:

(function() {
  var el=document.createElement('div'),
   b=document.getElementsByTagName('body')[0];
   otherlib=false,
   msg='';
  el.style.position='fixed';
  el.style.height='32px';
  el.style.width='220px';
  el.style.marginLeft='-110px';
  el.style.top='0';
  el.style.left='50%';
  el.style.padding='5px 10px';
  el.style.zIndex = 1001;
  el.style.fontSize='12px';
  el.style.color='#222';
  el.style.backgroundColor='#f99';
  if(typeof jQuery!='undefined') {
 msg='This page already using jQuery v'+jQuery.fn.jquery;
 return showMsg();
  } else if (typeof $=='function') {
 otherlib=true;
  }
  // more or less stolen form jquery core and adapted by paul irish
  function getScript(url,success){
 var script=document.createElement('script');
 script.src=url;
 var head=document.getElementsByTagName('head')[0],
  done=false;
 // Attach handlers for all browsers
 script.onload=script.onreadystatechange = function(){
   if ( !done && (!this.readyState
     || this.readyState == 'loaded'
     || this.readyState == 'complete') ) {
  done=true;
  success();
  script.onload = script.onreadystatechange = null;
  head.removeChild(script);
   }
 };
 head.appendChild(script);
  }
  getScript('http://code.jquery.com/jquery-latest.min.js',function() {
 if (typeof jQuery=='undefined') {
   msg='Sorry, but jQuery wasn\'t able to load';
 } else {
   msg='This page is now jQuerified with v' + jQuery.fn.jquery;
   if (otherlib) {msg+=' and noConflict(). Use $jq(), not $().';}
 }
 return showMsg();
  });
  function showMsg() {
 el.innerHTML=msg;
 b.appendChild(el);
 window.setTimeout(function() {
   if (typeof jQuery=='undefined') {
  b.removeChild(el);
   } else {
  jQuery(el).fadeOut('slow',function() {
    jQuery(this).remove();
  });
  if (otherlib) {
    $jq=jQuery.noConflict();
  }
   }
 } ,2500);
  }
})();

One year ago today, my dad passed away

I can’t believe it’s been a year. A whole year since my dad lost his fight with cancer. The pain has definitely subsided over that time, especially knowing that he isn’t suffering anymore. No more shitty chemo. No more convulsions. No more meds. No more being an invalid. And that’s good because my dad hated being dependent on anyone.

Tonight, I’ll join my family in a service to remember my dad. And that’s good because we all need some closure.

We miss you dad.

Choose 3 Developers You’d Spend a Day With

Here’s a question. Given 3 days and allotted 1 day per developer, which 3 developers would you spend it with? Here’s the caveat, the developers MUST BE in the web development community.

Here are my choices in no specific order:

  • Nicole Sullivan – Why? Because she is a freaking CSS guru and the amount of CSS knowledge I could gain from a day of her mentoring would be so incredibly valuable. She’s also a super-cool person.
  • Nicholas Zakas – Why? Well, there are a lot of people who are really awesome JavaScript developers but few, in my opinion, who have the experience in a large-scale environment. Nicholas has that, as the principal front-end engineer for Yahoo! and that’s knowledge worth nabbing. And if you’ve watched his presentations, you know he can teach.
  • Joe Stump – Why? Because Joe is one of the coolest dudes on the planet and apart from that, he has the knowledge to build out BIG sites. Now that he’s focused on geolocation, getting into that would be so cool. Plus, I know Joe loves kids so I could talk to him about babies and stuff. ;)

Now, my list isn’t meant to leave anyone out because there are a ton of people who I’d like to learn from. This is just a group who I feel, at the moment, would offer knowledge that I want right now and they’re just great for providing that. So hopefully, I won’t hurt anyone’s feelings. :)

So who would you pick?

The Case for jQuery’s .delegate() Method for Dynamic Event Binding

Binding events is one of the most common tasks a JavaScript developer has to do. It’s integral to the way our applications handle user interaction and response. Since it’s inception, jQuery has had event handling via various helper methods that helped to abstract cross-browser differences. If you’re a jQuery developer, I’m sure you’re used to syntax like this:

$("#clname").click( function() { alert( "Rey" ) } );

which would bind a click event to a DOM element with an ID of “clname”. Very easy to understanding and simple to use. But when you get past just simple use of JavaScript and start inserting new DOM nodes, this binding becomes less useful because it can’t handle dynamically inserted elements. Let me explain.

Say you have the following HTML markup:

<div id="clcontainer">
<a href="#" class="clients">Click for Rey Information</a>
</div>

and you bind the click event to generate an alert of some type like this:

$(".clients").click( function() { alert( "Here's some information." ) } );

but then you decide that you’re going to add a new DOM element to the page dynamically:

$("#clcontainer" ).append( "<a href='#' class='clients'>Click for Mark Information</a>" )

What do you think will happen? I would venture many developers might expect that the second, dynamically appended DOM element would share the same binding as the first since they share the same class name. That’s not the case. jQuery methods such as click(), dbclick(), and bind() are meant to bind events to a specific set of available DOM elements (i.e: not dynamically appended). (Note: I updated this part to better clarify what I meant based on feedback by Jamie Newman)

Now to get around this limitation, jQuery team member Brandon Aaron initially created a plugin called LiveQuery which would allow you to bind events not only to specific DOM elements but all subsequent DOM elements that were appended to the DOM that matched the selector specified in the initial binding. That plugin eventually became part of the jQuery Core library and renamed simply to live(). The great thing with live() is that you could now bind dynamically added DOM elements like this:

$(".clients").live( "click", function() { alert( "Here's some information." ) } );

and if you did append a new DOM element, like this:

$("#clcontainer" ).append( "<a href='#' class='clients'>Click for Mark Information</a>" )

it would now share the same function binding as initially defined.

The Problem with Live()

Now, live() is an awesome method and people totally loved it. That is, until they wanted to bind events based on a deeper DOM traversal than just a single element, specifically when methods were used that alter the selector expression’s initial results (e.g.: using children()). So, if we had markup like this:

<div id="clcontainer">
	<ul>
		<li>Mary</li>
		<li>Jane</li>
	</ul>
</div>

and tried to use live() to bind all of the list items like this:

$("#clcontainer").children( "ul" ).find( "li" ).live( "click", function() { alert( "Here's some information." ) } );

the binding would fail. Since chaining is so widely used within the jQuery community, this was a bit of a surprise to many and one of the most requested updates to jQuery.

In order to get around this, Brandon introduced in jQuery v 1.4 the new delegate() method. It provides greater control by allowing you to specify the context to which you’d like to bind to. So using the same example as above and making some slight changes to use delegate(), we’re now able to use chaining to determine our selector results and then specify that we’d like all current and future list items to be bound to our declared function:

$("#clcontainer").children( "ul" ).delegate( "li", "click", function() { alert( "Here's some information." ) } );

When to Use live() or delegate()

These two convenience methods are totally awesome and incredibly helpful with more complex apps. The best use case for them is when you know that you will be dynamically adding new DOM elements and they’ll share the same bound function. I mean, essentially that’s the premise of event delegation. You’re trying to limit the number of event handlers needed to handle functionality and increase maintainability be centralizing your logic. Make sense. If you’re not going to be doing anything that involved, though, then jQuery’s event helper methods such as bind(), click() etc. are still excellent choices for those one-off scenarios.

Random Thought: When Was the Last Time You Took a Step Back and Appreciated the Internet?

As I was tweeting back and forth with my online buddies, I kind of had a moment where I just looked at the screen in utter amazement of the fact that I’m able to communicate so easily with so many people all over the world. Setting aside all of the web pages we look at, code we build, videos we see..isn’t it just amazing that a set of cables (obviously a lot of them) allow our thoughts to go from one end of the planet to another at incredible speed?

Seriously, take a step back and consider your IM chat or your Skype call or even a tweet. Think about the fact that every keystroke and every data bit somehow gets to where it needs to go. That’s just damn impressive. I think back 32 years ago when I was 10 years old having to get up to change a channel on a TV or using a paper map to figure out how to get to a vacation spot. Now, our phones can accurately pinpoint our location and find the nearest eatery for a great meal. Amazing!

I know the younger guys & gals may not be able to relate. You guys grew up with much of this stuff so it’s just normal to you. For me, this is some really cool and amazing stuff and I truly hope that every now and then, you take a step back and just appreciate the wonder that is the Internet.

Book Review: A Book Apart’s HTML5 for Web Designers by Jeremy Keith

I just finished A Book Apart’s first book titled HTML5 for Web Designers. The book, written by well-known developer Jeremy Keith, and provides an overview of HTML5. I was pretty hyped up to receive this book and pre-ordered it based on my experience with Jeremy’s previous book.

My Thoughts

If you’re totally new to HTML5, this book will give you a good overview of the new spec. It’s not a highly technical book and is meant to provide the reader with an understanding of the evolution of the spec as well as some of the most important features of HTML5 including Canvas, video and updated form capabilities. The book is very short (only 85 pages) and extremely easy to read, which allowed me to finish it off in about 2-3 days of non-contiguous reading. I also liked Jeremy’s use of humor throughout the book.

With that said, this book is definitely not a deep-dive into HTML5 and if you’re expecting to pick it up and actually learn how to use the new features, I think you’ll be disappointed. While there are some technical nuggets (especially around Canvas), the book is really just an overview with very little technical meat to it. And I believe that’s the way that A Book Apart is trying to promote their books; quick, easy-to-read materials that get you good information fast.

What I would recommend is that if you’re looking to get a 10,000 foot view of HTML5, pick up this book. It’s definitely worthwhile from that perspective. If you’re looking to better understand the implementation of specific features, then this is not the right choice. And I offer this recommendation whether you’re a developer or designer. Better resources for a deeper, technical understanding of HTML5 include:

Dive Into HTML5
HTML5 Demos
HTML5 Doctor

All of these are listed in the Resources section of the book and having read them previously truly are excellent sites for deep-diving into HTML5.

Tell Me the Development Problems that Script Junkie Can Try to Solve via Solutions-based Content

My biggest focus at Microsoft is the Script Junkie website. We use it to publish really great cross-browser, solutions-based content to help developers improve their JavaScript, HTML, & CSS development efforts.

The Script Junkie team is working on our content plan for the next six months and we’re looking to identify developer problem areas that we can provide solutions for. So I’m reaching out to my blog readers in an effort to understand what type of things pain you. Here are some examples of problem areas that we’ve heard of:

  • Designing and implementing for multiple devices like 42″ LCD TVs to 480px Android device
  • Getting users to upgrade their browsers in a friendly way
  • Developing cross-browser compatible websites with minimal hacks
  • How realistic is it to begin using HTML5 & CSS3 today?

It’s important to note that that we’re not looking for answers to the above problem areas at this time. These are examples to demonstrate the type of concerns we’re hearing. We’re looking for more questions that hopefully we can answer via solutions-based articles and code. So if you have thoughts on wide-spread development problems that you’d like to see tackled, please comment below. Remember that Script Junkie focuses on JavaScript, HTML and CSS so please be sure to keep that in mind when listing out your pain points.

We’ll roll-up your comments and then focus on the top 10 things listed by the development community.

Thanks for your help!

The Essential List of JavaScript, jQuery, HTML & CSS Books to Make You a Better Web Developer

Over the years, I’ve read or been recommended a number of books which are essential reading for professional web developers. I’ve compiled the list of books below to help the community find a comprehensive list of good books that can help them be better coders.

JavaScript

Professional JavaScript for Web Developers – My new favorite book. Almost 1,000 pages of VERY detailed JavaScript information. Written by Nicholas Zakas, Yahoo! Principal Front-end Engineer for Yahoo!’s home page and recommended by the YUI team as well. BUY THIS BOOK!

JavaScript: The Definitive Guide – Considered the Bible of JavaScript for its thorough coverage of JavaScript. You need to have this in your library, even as a reference.

DOM Scripting: Web Design with JavaScript and the Document Object Model – This is a good book to get you familiar with the DOM.

AdvancED DOM Scripting: Dynamic Web Design Techniques

Beginning JavaScript with DOM Scripting and Ajax: From Novice to Professional – The book by Christian Heilmann that really got me past the initial hump of plain ‘ole JavaScript. His writing style is awesome.

Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications and libraries – JUST BUY THIS BOOK! Stoyan did a great job of outlining OOJS principles and it’s been incredibly valuable.

JavaScript: The Good Parts – It’s certainly a good book and I would recommend reading it after one of the more intro books like JS for Web Developer by Nicholas Zakas.

Learning jQuery 1.3 – While covering jQuery v1.3, the techniques discussed are still useful and I still recommend the book highly.

Pro JavaScript Techniques – John Resig’s famous book on advanced JS techniques.

Secrets of the JavaScript Ninja – Still not out but considering that John Resig is that author, it’s sure to be great.

ppk on JavaScript, 1/e – One of the first books I picked up and great overview of the language.

Accelerated DOM Scripting with Ajax, APIs, and Libraries

Ajax Security – Billy Hoffman is the man when it comes to Ajax security and this books shows why.

jQuery Cookbook: Solutions & Examples for jQuery Developers (Animal Guide) – Tips & techniques from the jQuery team rolled up in a cookbook style. You can’t go wrong.

jQuery in Action, Second Edition – This is now updated for jQuery v1.4.x as well as jQuery UI 1.8.x. Definitely a must-have for jQuery developers

jQuery Enlightenment – Cody Lindley did an amazing job in outlining the best jQuery techniques in this self-published book. Totally worth the price.

Test-Driven JavaScript Development

jQuery: Novice to Ninja

HTML & CSS

Web Standards Solutions: The Markup and Style Handbook, Special Edition

Bulletproof Web Design: Improving flexibility and protecting against worst-case scenarios with XHTML and CSS (2nd Edition)

The Art & Science Of CSS – This is one of Sitepoint’s best CSS books. Loved it.

HTML Utopia: Designing Without Tables Using CSS, 2nd Edition – Not being a designer, I thought this book was a tremendous help in understanding how to better design sites.

Head First HTML with CSS & XHTML – This has been my goto book for some time. The Head First books are just so great at breaking down topics in easy to understand ways and this book is no exception.

Introducing HTML5 (Voices That Matter) – Going to get this soon mainly because it’s written by Remy Sharp and Bruce Lawson whom I respect tremendously, especially for their HTML5 & CSS3 savvy.

HTML5 For Web Designers – Just got this on 7/19/10. Need to read it by it’s by Jeremy Keith and he rocks.

CSS Cookbook, 3rd Edition (Animal Guide) – Just picked this up on a recommendation.

CSS: The Missing Manual – I keep hearing rave reviews about this book all over the place.

Site Performance & Enhancement

High Performance Web Sites: Essential Knowledge for Front-End Engineers – Steve Souders is the performance guru and if you want your apps to perform better, get this book and the one right below this one.

Even Faster Web Sites: Performance Best Practices for Web Developers

High Performance JavaScript (Build Faster Web Application Interfaces) – Again, another great book by Nicholas Zakas which outlines very important performance techniques for JavaScript applications.

Designing with Progressive Enhancement: Building the Web that Works for Everyone – Great book on progressive enhancement by the superstars at the Filament Group.

This is certainly not all inclusive and I’m sure there are other books out there that have been great. If you feel very passionate about a specific title, let me know via the comments and I’ll check it out.

jQuery JavaScript Templates Tutorial: Inline Expressions and Code Blocks

So far in my series on jQuery JavaScript Templating, I’ve showed how to create a basic jQuery JavaScript template and then nest templates for increased layout flexibility and maintainability. If you haven’t read those two posts, I highly recommend you do so you can understand the concepts below.

Now, let’s dive into two other techniques available in the Microsoft jQuery Templates plugin; inline expressions and code blocks.

Inline Expressions

Being able to use a template to create a succinct layout is very powerful but without the ability to manipulate the data that’s being rendered, you’d probably find templates a lot less useful. That’s where inline expressions come in. Inline expressions allow you to use common JavaScript expressions to effect a change in the way your data is rendered. Using a slightly modified version of the data from my last tutorial, I can show you what I mean. Here’s the data:

var clientData = [
     { first: "Rey", last: "Bango", age: 42, id: 1, phone: [ "954-600-1234", "954-355-5555" ] },
     { first: "Mark", last: "Goldberg", age: 51, id: 2, phone: ["954-600-1234", "954-355-5555"] },
     { first: "Jen", last: "Statford", age: "25", id: 3, phone: ["954-600-1234", "954-355-5555"] }
 ];

What I did was break out the “name” attribute into “first” and “last” name fields. Now, say I wanted to render the full name in my template. I would use the following inline expression to do so:

<script id="clientTemplate" type="text/html">
    <p><li>${ first + " " + last }</li></p>
</script>

Which gives me the following result:

Notice that I’m using the standard JavaScript “+” operator to concatenate the two data attributes together to form my final output. JavaScript developers should immediately be able to understand the code here and see how flexible this option is.

Code Blocks

Now, while inline expressions are certainly powerful, the ability to affect the data via code blocks is even more important because it allows you to specify conditional statements that can be used to determine what type of and when data will be represented. Let’s say that based on the age of a client, I want to show some text next to their name. I’ll use the following code block:

{{if (age > 30)}}veteran coder!{{else}}rising star!{{/if}}

This code block allows me to specify a conditional statement that allows me to create a nice descriptor based on the person’s age. The key is the “{{if..else}}” custom tag that’s been incorporated into the template plugin that allows you to specify conditional statements.

Here’s what the template would look like:

<script id="clientTemplate" type="text/html">
    <p><li>${ first + " " + last + " is a " }{{if (age > 30)}}veteran coder!{{else}}rising star!{{/if}}</li> </p>
</script>

which generates the following results:

And again, the cool thing is that the syntax for the expressions use standard JavaScript operators so I can do something like this as well:

{{if (age > 20 && age < 30 || age == 42)}}rising star!{{else}}veteran coder!{{/if}}

The thing to stress here is that using inline expressions and code blocks together can give you a tremendous amount of control over how you control you data. You have the flexibility you’d expect by using JavaScript but in a manner that is easily readable and maintainable.

Here’s the final code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="robots" content="noindex" />
  <title>Template Test</title>
  <script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
  <script src="jquery.tmpl.js" type="text/javascript"></script>
  <script type="text/javascript">
  $(document).ready(function() {

var clientData = [
     { first: "Rey", last: "Bango", age: 42, id: 1, phone: [ "954-600-1234", "954-355-5555" ] },
     { first: "Mark", last: "Goldberg", age: 51, id: 2, phone: ["954-600-1234", "954-355-5555"] },
     { first: "Jen", last: "Statford", age: "25", id: 3, phone: ["954-600-1234", "954-355-5555"] }
 ];

        $("#clientTemplate").tmpl(clientData).appendTo("div");

});
  </script>

<script id="clientTemplate" type="text/html">
    <p><li>${ first + " " + last + " is a " }{{if (age > 20 && age < 30 || age == 42)}}rising star!{{else}}veteran coder!{{/if}}</li> </p>
</script>

</head>

<body>

<div></div>

</body>
</html>

The Source Code for my Twitter Demo from the Think Vitamin jQuery Online Conference Templating Presentation

I just finished my presentation at Think Vitamin’s jQuery Online Conference and it was such a great experience. This is the first BIG virtual conference I’ve presented at and it ran smooth as silk. I really have to hand it to the Carsonified team; they have their act together. :)

The big takeaways:

  • Online conferences rock! No travel == less expenses.
  • The technology is good enough to be able to do this and WebEx is awesome.
  • Carsonified’s got this down. While some tech problems are expected, they’ve really got the process working well.

The only downside, from a speaker perspective, is that you really can’t see how your audience is reacting. That’s tough because sometimes, you’re able to adjust according to your audience’s feedback. If there’s dead silence, you know you need to bring them back. If they’re engaged, you know you’re on track. In a virtual conference, you can’t gauge that so it’s tough.

Lots of folks have asked for the code for the Twitter demo that I did. You can now download that below:

Download the Twitter Demo Source

I want to thank everyone for attending and for the kind words. I really appreciate it. I also want to thank Carsonified for giving me the opportunity to speak at a great event.

THE BIG LIST!

My BIG LIST of JavaScript, CSS & HTML Development Tools, Libraries, Projects, and Books.

Constantly updated with the latest and greatest tools. Check it out!

Contact Me

AIM: iamreybango
GTalk: reybango at gmail dot com
GMail: reybango at gmail dot com
Twitter: @reybango


Twitter

Rey Bango is Digg proof thanks to caching by WP Super Cache