[QuickTip] Prepend jQuery object references with $

Old school textbooks used to have you prepend variable names with special identifiers. For example, “strName”, “intYear”, “bolFemale” would hold things like a string, integer, and boolean.

One trick I like to use when working with jQuery is to prepend jQuery objects with a dollar sign. This not only helps keep your code self-documented, but makes a chain of commands easier to read.

Here’s a bit of code I use on my site:

function toggleCard($card){
    $card.toggleClass('expanded')
    $card.find('.card')
        .toggleClass('c4')
    $card.find('.content')
        .first()
        .toggleClass('hidden')

    var scrollTarget = $card.hasClass('expanded') ? $card.find('.content').offset().top - 30 : $card.offset().top

    $html.stop(true).animate({
        scrollTop: scrollTarget - $nav.outerHeight()
    })
}

compared to:

function toggleCard(card){
    card.toggleClass('expanded')
    card.find('.card')
        .toggleClass('c4')
    card.find('.content')
        .first()
        .toggleClass('hidden')

    var scrollTarget = card.hasClass('expanded') ? card.find('.content').offset().top - 30 : card.offset().top

    html.stop(true).animate({
        scrollTop: scrollTarget - nav.outerHeight()
    })
}

If you knew my convention, you could tell that both $card and $nav are jQuery selected objects. And $nav isn’t even defined here. Also notice how the jQuery objects are syntax highlighted differently!

Are there any other conventions you use?

I use $this for self-referencing in classes, ie:

var $this = this;

I don’t use jQuery, but if I did, I could totally see the value of establishing your kind of convention. Makes sense.

In fact that one is so common I have it macro’d to “vthis”

Not sure if it’s a convention, but something I use quite a lot are predicate methods.
I find they make your code easier to read, plus I’m a fan of small, concise methods.

E.g.

divisibleByThree = function(n){ return n%3 === 0 };
[1, 3, 14, 21, 25, 27].filter(divisibleByThree); // [3, 21, 27]

I also work with Ruby on occasion.
In Ruby you can end your predicate method with a question mark and there are many of them built into the language.

E.g.

[].empty? #true
"SitePoint".include? "oint" #true
1.respond_to?("+") #true

And Ruby’s syntax lets you write things like:

send_reminder unless @invoice.paid?
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.