Build an Advanced jQuery Plugin

Premium Tutorial – Build an Advanced “Poll” jQuery Plugin, and a GIVEAWAY!

I’m proud to launch our first ever Premium tutorial, exclusive to members. For this flagship tut, veteran developer/writer Dan Wellman – author of the recently released jQuery UI 1.6, from Packt publishing – will teach you how to build an advanced “poll” jQuery plugin. Not only will you have a lengthy tutorial to study, but we’ll also provide a companion video tutorial to assist.

To celebrate our first Premium tutorial, I also have some free books to give away, courtesy of Packt!.

A Wonderful, and In Depth Tutorial That Will Take You From A-Z

In this tutorial we’re going to be creating a jQuery plugin from start to finish; this plugin will allow us (or other developers) to easily add a simple poll widget to a web page or blog. By poll widget, I mean an area in which a question is posed which visitors are encouraged to answer. Once they have answered the question the results of the poll will then be displayed.

screencast
jQuery Plugin

Sign up for a PLUS membership now!

Free Books!

To help celebrate the launch of our new plus program, I have some books, courtesy of the folks over at Packt publishing, that we’ll be giving away!!

Whatcha Got?

I have a few copies of Dan’s new “jQuery UI 1.6″ book, as well as “The Jquery Reference Guide”. All you have to do is leave a comment with a quick jQuery tip. We’ll then randomly choose several winners! I’ll go first.

If, within a function, you find yourself repeatedly calling “$(this)”, consider caching it.

$(this).click(dosomething);
.....
$(this).somethingElse();
......
$(this).evenMoreSomething();

can become…

var $this = $(this);
$this.click();
.....
$this.somethingElse();
.....
$this.evenMoreSomething();

Join Tuts Premium

For those unfamiliar, the family of TUTS sites runs a premium membership service called “Premium”. For $19 per month, you gain access to exclusive premium tutorials, screencasts, and freebies at NETTUTS, PSDTUTS, and VECTORTUTS! For the price of a pizza, you’ll learn from some of the best minds in the business. Join today!

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://2fade.net Jamie

    Damn, wish i had a plus account this looks cool

  • Misael Arroyo

    Great screencast, following it right now.

    [First Comment..... I hope]

  • http://another-perfect-world.org/ Vasili

    If you’re planning on showing something when you click on something with jQuery, hide that element with jQuery so non-JavaScript users can still see that content.

    $(‘#element’).hide(); instead or #element { display: none; }

  • http://www.designworks.lt/ Alexander

    jQuery Tip:

    To fix the fadeIn() and fadeOut() ClearType glitch in IE, just remove the “filter” attribute:
    $(‘#someDiv’).fadeOut(‘slow’, function() {
    this.style.removeAttribute(‘filter’);
    });

  • http://www.danharper.me Dan Harper

    This looks great! Unfortunately, the screencast doesn’t ‘fit’ into my browser window (1440×900, Mac – even with the dock hidden). I’ve had to zoom out using Firefox to fit the whole player in.
    Any chance of another way to watch the screencast?

  • http://www.drawmyattention.co.uk Amo

    It’d be nice if you had a link to the demo of the project so those of us who don’t have a plus subscription can see exactly what’s being produced in these exclusive tutorials.

    That’d help us decide better if we want to part with our hard earned cash anyway :)

  • Devin Rajaram

    There is a problem with the player and chrome, that needs to be fixed, its not showing the whole video player.

  • http://mil-an.co.uk Milan

    Use google.load() for many javascript libraries.

  • http://diggerdesignlabs.com Steve Robillard

    unless developing for a local intranet load jquery from Google’s CDN. It may not always be faster but for most users it will either be already in their cache or load from one of Google’s data centers and the average load time will be better across all users.

  • Devin Rajaram

    Here is my little tip on jQuery.

    Use this tip to specify Internet Explorer and insert you code within the curly braces.

    if ($.browser.msie) {
    // This is just for IE
    }

  • http://another-perfect-world.org/ Vasili

    @Amo: I was thinking the same thing. But people could still see some of the coding, in this case, the jQuery. ;)

    @Devin: The site exists.

  • http://synarchydesign.com Kevin Martin

    Oh, nice, I have done something like this in the past. It was a very interesting build.

    ** jQuery Tip**
    To know if you have an IE user on your site, you can easily do something like:

    if ($.browser.msie)
    {
    // I would add 5,000 loops of alert messages :D
    }

  • Gustavo Caetano

    To style differently an external link just do this

    $(“a”).not(“[href^=/]“).not(“[href^=#]“).append(“?”);

    They will me marked with a EXTERNAL class.

  • Derek

    Shorthand for ready event: instead of
    $(document).ready(function() {});

    try
    $(function() {} );

  • http://evan.evanriley.net Evan Riley

    Awesome first PLUS tut. Great Job Dan. and the Envato team for a smooth release of the new plus.

  • Devin Rajaram

    here is another quick tip really simple and nice

    location.reload(true);

    use that to make a page reload

  • http://www.vileworks.com Stefan

    Where possible give your selectors a context.
    Ex: $(‘#content .class’) is faster than $(‘.class’)

    And another one: when possible try to put your JavaScript at the bottom, right before the closing body element.

    Hey… you didn’t say they had to be original :D Just from the top of my head.

  • http://juarezpaf.com Juarez P. A. Filho

    Increase the speed of your script, just give a context to your selectors.
    So today you do that
    $(‘#showList’).hide;

    Try
    $(‘#showList’, $(‘#content’) ).hide;

    Nice first tutorial. I’ll see it soon.
    I hope learn more about jQuery UI.

  • http://zachlebar.com Zach LeBar

    Whenever you have a question about what a jQuery element can do…consult the Wiki. It’s in depth with simple explanations, source code, and demos.

  • http://www.suankual.com/ codeAries

    I wish i could have both the books :)

  • Peter C.

    Hmm quick tips… as Derek mentioned you can create a ready handler very easily, but use jQuery not the dollar:
    jQuery(function($){ /* $ now always references jQuery scope */ });

    If you want to stop “dancing” animations, add a call to stop (docs) before the animation call.

  • Tom Malone

    Insert your jQuery scripts (and all Javascript files) at the bottom of the page. That way your content will not be delayed downloading to the user’s browser while waiting on a script file to load.

  • http://jasonseney.com Jason

    Need to REALLY stop animations from going out of control? Have a grid of items that fade in/out on hover and they go crazy when you hover all over the place?

    Fix it with this:

    $(item).hover(function () {
    $(this).find(‘.overlay’).queue(“fx”, []); //Stop any previous queued animation
    $(this).find(‘.overlay’).fadeTo(‘slow’, 1.00);
    }, function() {
    $(this).find(‘.overlay’).queue(“fx”, []); //Stop any previous queued animation
    $(this).find(‘.overlay’).fadeTo(‘slow’,0);
    });

    Just make sure the opacity on overlay is initialized to 0, do not use display:none or hide().

  • http://www.pixelsandcode.net Bob Sawyer

    I always put my jquery ready() events in an external file and load it after all the other jquery files. Keeps things nice and tidy.

  • http://jarrydcrawford.com/ Jarryd

    I know this is on the docs, but still useful to post here :). If you are using another javascript library ( usually by force ) there are ways you can get jQuery to not conflict with it:

    var $j = jQuery.noConflict();

    $j(document).ready(function(){
    $j("div").hide();
    });

  • http://disturbyte.mp Zachary Voase

    I have a jQuery tip (well, a code snippet).

    At the bottom of this comment is a bookmarklet I whipped up a while back which I call the ‘jQuery Shell’.

    What it does is inserts two scripts into the current page’s ‘head’ element: jQuery, and Billy Reisinger’s JavaScript Shell (Jash). This launches the shell, allowing you to dynamically interact with objects on the page using jQuery. It’s really handy for debugging, and it makes a nice companion to Firebug or the Web Inspector, because you can enter JS snippets (with tab completion), execute them and see the results in real-time. It works on any page, whether it’s your own or someone elses, meaning you can have all sorts of fun.

    To install it, simply select and copy the code below, right-click on the bookmark toolbar in your browser and add it as the URL of a new bookmark called ‘jQuery Shell’ (or whatever else tickles your fancy).

    Here’s the bookmarklet:

    javascript:(function()%20{head%20=%20document.getElementsByTagName(%27head%27)[0];jash_script%20=%20document.createElement(%27script%27);jash_script.src%20=%20%27http://tr.im/gy0v%27;jash_script.type%20=%20%27text/javascript%27;jquery_script%20=%20document.createElement(%27script%27);jquery_script.src%20=%20%27http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.js%27;jquery_script.type%20=%20%27text/javascript%27;head.appendChild(jquery_script);head.appendChild(jash_script);})();

  • morozgrafix

    I often use this bookmarklet to jQuerify any web page on the fly:

    javascript:var%20s=document.createElement(‘script’);s.setAttribute(‘src’,%20′http://jquery.com/src/jquery-latest.js’);document.body.appendChild(s);s.onload=function(){/*Your Code Here*/};void(s);

    More info here:http://ejohn.org/blog/hacking-digg-with-firebug-and-jquery/

    and here:

    http://www.learningjquery.com/2008/06/updated-jquery-bookmarklet

  • http://www.thomasbritton.co.uk Tom

    Good tip ive started to use more often is to link to offsite js, such as google code.

    // Load jQuery
    google.load(“jquery”, “1.3.1″);

    google.setOnLoadCallback(function() {
    // Your code goes here.
    });

  • http://www.scottgm.co.uk Scott MacDonald

    Css-tricks.com has some great videos, some of them that include jQuery, great for beginners

  • http://www.DanMesa.com Dan

    Very cool. I was just looking for a quality tut for something like this. I swear to god that’s like the 3rd time that’s happened. Blows my mind.

    Overall, I’m really loving the new setup.

  • Jeremy Halvorsen

    I don’t have a good tip…THAT’S WHY I NEED THE BOOK! :P

  • Jonathan

    When using the hover() method, leave off the second function if you only want an effect on mouse in.

    $(‘#hover-demo p’).hover(function() {
    $(this).addClass(‘mouse-in’);
    });

  • Yash

    Awesome!! I have a Plus subscription so I’m going to view this now, I’m excited :) . Of course I’m a real JavaScript and JQuery newb, but still.

    And my tip – use google to load the JQuery framework so that your website will not have as much load on it, like this –

  • Satkrit

    If want to break away from the usual circle and square bullets and want to use an EM dash or even an image. There are two steps to this:

    $(“ul”).addClass(“Replaced”);
    $(“ul > li”).prepend(“‒ “);

  • Satkrit

    By the way looks like this tutorial will be very helpful. Too bad I can’t pay for it. :(

  • http://www.bradenkeith.com Braden Keith

    My Jquery Tip:

    Use a cheat sheet! It helps speed up the process when you have a quick reference, I recommend: http://www.gscottolson.com/weblog/2008/01/11/jquery-cheat-sheet/

  • http://yoosuf.awardspace.com M.A.Yoosuf

    :S, i gotta pay now

  • http://stas.nerd.ro/ Stas

    jQuery is as cool as:
    var me = comment.getUserByName(‘Stas’);
    $(‘winer’).book(‘The Jquery Reference Guide’).belongsTo(me);

    :)

  • Devin Rajaram

    I don’t mind paying :)

  • http://www.subprint.com Joseph McCann

    $(document).ready(function(){ /* All Code Goes Here */})

    is the same as

    $().ready(function(){ /* All Code Goes Here */})

    which is also the same as

    $(function(){ /* All Code Goes Here */});

    The first is the traditional way, passing document to the ready method. The second passes nothing, which is fine because the ready method essentially says if it is empty, then the element is the document. The third way is simply passing a function, which jQuery checks for in the ready method and executes it the same as the prior 2 techniques.

  • http://www.stolenbit.com KiT

    This is… TOO GREAT!!!
    Thanks a bunch, TUTS+ :)

  • http://www.4colorsdesign.com saran

    I want this book

  • Backer

    My jquery tip is to deal with slideUP, slideDown, show, hide etc

    To call the slideDown only when it is hidden
    if ($(“#discountDisplay”).is(“:hidden”)){
    $(“#discountDisplay”).slideDown(“slow”);
    }

    To call the slideUp only when it is shown
    if (!$(“#discountDisplay”).is(“:hidden”)){
    $(“#discountDisplay”).slideDown(“slow”);
    }

  • Ian

    This is a bit of an obscure tip but it may be helpful nonetheless. If you’re developing inside an environment that has compatibility issues with jQuery (i.e. an existing JavaScript framework that you can’t control). You’ll need to make sure you load jQuery *first* and relinquish control of the $. If you find yourself in a .NET / C# world – here is a handy method:

    public static void AddJQueryReference(Page page)
    {
    const string JavaScriptReferenceFormat = @”";
    const string JQueryRegistrationKey = “jQuery Registration key”;
    if (!page.ClientScript.IsClientScriptBlockRegistered(typeof(Utility), JQueryRegistrationKey))
    {
    string jQueryReference = string.Format(CultureInfo.InvariantCulture, JavaScriptReferenceFormat, page.ClientScript.GetWebResourceUrl(typeof(YourClassName), “YourCompany.Namespace.JavaScript.jquery-1.2.6.min.js”));
    page.Header.Controls.Add(new LiteralControl(jQueryReference));
    page.ClientScript.RegisterClientScriptBlock(typeof(YourClassName), JQueryRegistrationKey, “jQuery(function($){$.noConflict();});”, false);
    }
    }

  • Backer

    Small change in my previous comment

    To call the slideDown only when it is hidden
    if ($(”#discountDisplay”).is(”:hidden”)){
    $(”#discountDisplay”).slideDown(”slow”);
    }

    To call the slideUp only when it is shown
    if (!$(”#discountDisplay”).is(”:hidden”)){
    $(”#discountDisplay”).slideUp(”slow”);
    }

  • http://www.brenelz.com/blog Brenelz

    Wow… I just signed up for plus and its GREAT!!!!!

    jQuery Tip:

    If you are having trouble binding events to dynamically created elements – check out the live query plugin! http://plugins.jquery.com/project/livequery

  • Jeffrey

    Using the jquery library you can use several xpath selectors. For instance to add a class to all pdf files you are linking to you can use this jquery snippet…

    $(‘a[@href$=".pdf"]‘).addClass(‘PDF’);

  • http://blog.insicdesigns.com insic

    wow! really cool! how i wish i could have a plus account!

  • RandomWebGuy

    Great work as always guys.

    Here’s my JQuery Tip:

    Use: $(window).bind(“load”,function(){ });

    instead of:

    $(document).ready(function(){});

    When you want to execute jquery commands after the page and all its assets (images, etc) have loaded first.

  • Snookerman

    jQuery tip:

    If you put your code at the end of the page (which you should to allow your page to load faster) you don’t need to use $(document).ready(function() {}); or $(function() {}); since the page has already loaded.

    Good luck!