Skip to content

Instantly share code, notes, and snippets.

@stuarthallows
Last active December 20, 2015 22:29
Show Gist options
  • Save stuarthallows/6205754 to your computer and use it in GitHub Desktop.
Save stuarthallows/6205754 to your computer and use it in GitHub Desktop.
Notes from the Pluralsight course 'jQuery Tips and Tricks'.
// MODULE 1
// visit jsperf.com to write and run performance tests.
// use a CDN with a fallback, see html5 boilerplate.
// working with selectors
// consider prefixing variable names with $ when holding jQuery objects.
// caching
// consider caching objects whenever accessing via jQuery selector more than once.
var $display = $(".display");
function f() {
$display.addClass("processed").fadeIn(5000); // chaining
}
// Use $(this) in callbacks to access the target element.
$("#btn").click(function (){
$(this).addClass("highlight");
});
// defining a selector context #1
$(".panel", $("#context"));
// defining a selector context #2, may be considered clearer.
$("#context").find($(".panel"));
// custom pseudo-class selector
$.extend($.expr[":"], {
hasArialFont: function (element) {
return $(element).css("font-family") === "Arial";
}
});
$("div:hasArialFont").click(function () {
alert("Element has Arial font");
});
// limit DOM interactions.
var divs = [];
for (var i = 0 - 1; i < total; i++) {
divs.push("<div>" + i + "</div>");
}
$("#emaillist").html(divs.join(""));
// check if an element exists, make use of fact that selector returns a wrapped set.
$("#item").length > 0;
// or add custom function
jQuery.fn.exists = function () { return this.length > 0;}
// find() vs filter()
// find used for searching for descendents
// filter used to filter existing collection.
// use the end() function with chaining.
var cust = getCustomer(id);
$("<div class='cust'><span/></div>")
.find("span").attr("title", cust.name).end()
.appendTo("#divContainer");
// Using an object with setter methods.
// less maintainable
$("a.main").attr("href", "http://pluralsight.com").attr("title", "Pluralsight Courses");
// more maintainable
$("a.main").attr({
"href": "http://pluralsight.com",
"title": "Pluralsight Courses"});
// Use classes over styles.
// MODULE 2
// Events tips and tricks
// Use on() instead of bind(). blur, change, click, focus methods etc are wrappers around the 2 parameter on() method.
// on applies to items added to the DOM after on is called, bind would need to be called again after an object is added.
// In Chrome $0 is a shortcut to the selected item.
// delegate() attached handlers to a delegate object, use when adding objects dynalically, e.g. li to a ul, in whuch
// case the ul woud be the delegate to which handlers could be attached.
// The live() method uses the documenta as the delegate.
// e.preventDefault() - prevent default behaviour
// e.stopPropagation() - don't tell your parents
// e.stopImmediatePropagation() - don't tell your siblings, prevent other handlers at the same level being called.
// Returning false is equivalent to calling both e.preventDefault() and e.stopPropagation()
// Namespace an events by appending period and unique term, useful particularly when removing events.
$("input").on("focus.fo", function() {});
$("input").off("focus.fo");
$("input").off(".fo"); // Remove all handlers in namespace.
// Register events before DOM ready.
// No need to wait for the document to be loaded before attaching this handler, so this code could be moved to the file
// html head for earlier registration.
$(document).on("click", "#members ul li", function() {});
// No need to do this;
$(document).ready(function() {
$("#members ul li").on("click", function() {});
});
// Reusing existing methods as event handlers.
// Pass to proxy() method the object to take the this identity in the 'clicked' method.
var person = new Person("Stuart Hallows");
$(".person").on("click", $.proxy(person.clicked, person));
// Creating custom events. Consider using the documents as a mediator to implement pub sub.
// register for custom event
$("input").on("clear", function(){
this.val("");
});
// call custom event.
$("button").on("click", function (e) {
$("input").trigger("clear");
});
// Determining user input.
// see e.Which, e.pageX etc.
// Determine if event triggred by user or programatically
// e.originalEvent if set indicates a user event
// Just-in-tim Initialization
// only initialise control when necessary, e.g. on focus, when scrolled into view.
$(document).on("focus", "input.date:not(.hasDatepicker)", function (e){
// initialise the input.date to a datepicker.
$(this).datepicker();
});
// MODULE 3
// Ajax and Data tips and tricks
// .then and passing two callbacks is alternative to calling .done and .fail.
// Consider breaking down ajax calls into methods that return promises, separate the call implementation from the handlers.
// Consolidate the ajax calls for reusability.
// Resolve multiple calls woth $.when()
// Adding headers to an ajax request.
$.ajax({
url: "...",
type: "POST",
beforeSend : function (request) {
request.setRequestHeader("AuthToken", authToken);
}
});
// Retrieving headers in a response
authenticate(authToken)
.success(function(data, statusText, jqXHR){
$("#authToken").html(jqXHR.getResonseHeader("AuthToken"));
})
.fail(function(jqXHR, statusText, err){
});
// Custom ajax converters.
// e.g. if data was returned in one format and needed to be converted into another format.
// Can be defined globally and apply to all calls.
$.ajaxSetup({
converters : {
"json jsond": function(data){
return data && data.hasOwnProperty("d") ? data.d : data;
}
}
});
// then in call...
.ajax({
url: "...",
dataType: "jsond",
success: // etc
});
// Storing data with the data() function.
$("selector").data("theKey", "data to store");
var value = $("selector").data("theKey");
// or store multiple objects
var customer = $("selector").data();
customer.orders = orders;
customer.shipping = address;
// html5 data-* attriburs
<div id="pet" data-type="dog" data-name="baron" data-object='{type: "dog"}'>Baron the dog</div>
// read data values
var name = $("#pet").attr("data-name"); // always returns string
var name = $("#pet").data("name"); // will try to cast retuen type to number or object etc
// MODULE 4
// Utility methods.
// $.map method allows array items to be masaged, like Select in .NET
// call like $.map(array, fn) or $("selector").map(fn).get();
// $.grep is a search utility for arrays. Alternative is underscore filter.
people = $.grep(people, function(person) {
return person.age > 18;
});
// $.type
// typeof new Date() returns object as does calling typeof with many other arguments.
// $.type (new Date()) returns date.
// feature detect not $.browser detect.
// $.callbacks used internally to implement deferred.
// Synonymous to multitask delegates in .NET.
var callbacks = $.Callbacks();
callbacks.add(calculator.add);
callbacks.add(calculator.multiply);
callbacks.fire(3, 3);
// $.extend() can be used to merge methods from two objects.
jquery.fn.valentines = function (options) {
var settings = $.extend(
{},
{ color: "red", font-size: "16px" },
options
);
return this.css(settings);
}
$("a").valentines({ color: "A00000 "});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment