Categories

Useful jQuery examples

change()

The change() method is an event handler, just like click() or hover(). The change event is for textareas, text inputs, and select boxes, and it will fire when the value of the target element is changed; note that this is different from the focusOut() or blur() event handlers, which fire when the element loses focus, whether its value has changed or not.

The change() event is perfect for client-side validation; it’s much better than blur(), because you won’t be re-validating fields if the user doesn’t change the value.

$(‘input[type=text]’).change(function () {
switch (this.id) {
/ some validation code here /
}
});​​​​​​​​​​

Context

Context is both a parameter and a property in jQuery. When collecting elements, you can pass in a second parameter to the jQuery function. This parameter, the context, will usually be a DOM element, and it limits the elements returned to item matching your selector that are children of the context element. That might sound a bit confusing, so check out this example:

<p class=”hello”>Hello World</p>
<div id=”wrap”>
<p class=”hello”>Hello World</p>
</div>

var hi1 = $(‘.hello’),
hi2 = $(‘.hello’, $(‘#wrap’).get(0));

console.group(‘hi1′);
console.log(“Number of elements in collection:”, hi1.length);
console.log(“Context of the collection:”, hi1.context);
console.groupEnd();
console.group(‘hi2′);
console.log(“Number of elements in collection:”, hi2.length);
console.log(“Context of the collection:”, hi2.context);
console.groupEnd();
So where would this be useful? One place might be inside an event handler function. If you’d like to get an element within the one the event was fired on, you could pass this as the context:

$(‘ul#options li’).click(function () {
$(‘a’, this) . . .
});

data() / removeData()

Have you ever wanted to store some bit of information about an element? You can do that easily with the data() method. To set a value, you can pass in two parameters (a key and a value) or just one (an object).
$(‘#wrap’).data(‘myKey’, ‘myValue’);
$(‘#container’).data({ myOtherKey : ‘myOtherValue’, year : 2010 });
To get your data back, just call the method with the key of value you want.
$(‘#container’).data(‘myOtherKey’); //returns ‘myOtherValue’
$(‘#container’).data(‘year’); //returns 2010
To get all the data that corresponds with an element, call data without any parameters; you’ll get an object with all the keys and values you’ve given to that item.
If you want to delete a key/value pair after you’ve added it to an element, just call removeData(), passing in the correct key.

$(‘#container’).removeData(‘myOtherKey’);

queue() / dequeue()

The queue() and dequeue() functions deal with animations. A queue is list of animations to be executed on an element; be default, an element’s queue is named ‘fx.’

HTML
<ul>
<li id=”start”>Start Animating</li>
<li id=”reset”>Stop Animating</li>
<li id=”add”>Add to Queue</li>
</ul>
<div style=”width:150px; height:150px; background:#ececec;”></div>

JavaScript
$(‘#start’).click(animateBox);

$(‘#reset’).click(function() {
$(‘div’).queue(‘fx’, []);
});

$(‘#add’).click(function() {
$(‘div’).queue( function(){
$(this).animate({ height : ‘-=25′}, 2000);
$(this).dequeue();
});
});

function animateBox() {
$(‘div’).slideUp(2000)
.slideDown(2000)
.hide(2000)
.show(2000, animateBox);
}

delay()

When you’re queuing up a chain of animations, you can use the delay() method to pause the animation for a length of time; pass that time as a parameter in milliseconds.

$(‘div’).hide().delay(2000).show(); // div will stay hidden for 2 seconds before showing.

bind(), unbind(), live(), and die()

Did you know that when you add a click event to an element like this . . .

$(‘#el’).click(function () { /*******/ });
. . . you’re really just using a wrapper for the bind() method? To use the bind() method itself, you can pass the event type as the first parameter and then the function as the second.

If you use a lot of events, you can categorize them with namespacing; just add a period after the event name and add your namespace.

$(‘#el’).bind(‘click’, function () { /*******/ });
$(‘#el’).bind(‘click.toolbarEvents’, function () { /*******/ }); // namespaced
You can also assign the same function to multiple events at the same time, by separating them with spaces. So if you wanted to make a hover effect, you could start this way:
$(‘#el’).bind(‘mouseover mouseout’, function () { /*******/ });

eq()

If you’re looking for a specific element within a set of elements, you can pass the index of the element to the eq() method and get a single jQuery element. Pass in a negative index to count back from the end of the set.

var ps = $(‘p’);
console.log(ps.length); // logs 3;
ps.eq(1).addClass(’emphasis’); // just adds the class to the second item (index in zero-based)
You can also use :eq() in your selectors; so the previous example could have been done like this:

$(‘p:eq(1)’).addClass(’emphasis’);

get()

When getting a collection of element, jQuery returns them as a jQuery object, so you have access to all the methods. If you just want the raw DOM elements, you can use the get() method.

You can specify an index to get only one element.

alert( $(‘p’) ); // [object Object] – the jquery object
alert( $(‘p’).get(1) ); // [object HTMLParagraphElement]

grep()

If you’re not familiar with Unix/Linix shells, you might not have heard the term grep. In a terminal, it’s a text search utility; but here in jQuery, we use it to filter an array of elements. It’s not a method of a jQuery collection; you pass in the array as the first parameter and the filtering function as the second parameter. That filter function takes two parameters itself: an element from the array and its index. That filter function should perform its work and return a true or false value. Be default, all the items that return true will be kept. You can add a third parameter, a boolean, to invert the results and kept the items that return false.

Jeffrey Way did a great quick tip about the $.grep not long ago; check that out to see how to use it!
var nums = ‘1,2,3,4,5,6,7,8,9,10’.split(‘,’);

nums = $.grep(nums, function(num, index) {
// num = the current value for the item in the array
// index = the index of the item in the array
return num > 5; // returns a boolean
});

console.log(nums) // 6,7,8,9,10

Pseudo-Selectors

Sizzle, the CSS Selector engine inside jQuery, offers quite a few pseudo-selectors to make the job of selecting the elements you want easy. Check out these interesting ones:
$(‘:animated’); // returns all elements currently animating
$(‘:contains(me)’); // returns all elements with the text ‘me’
$(‘:empty’); // returns all elements with no child nodes or text
$(‘:parent’); // returns all elements with child nodes or text
$(‘li:even’); // returns all even-index elements (in this case, <li>s)
$(‘li:odd’); // can you guess?
$(‘:header’); // returns all h1 – h6s.
$(‘li:gt(4)’); // returns all elements with an (zero-based) index greater than the given number
$(‘li:lt(4)’); // returns all element with an index less than the given number
$(‘:only-child’); // returns all . . . well, it should be obvious
There are more, of course, but these are the unique ones.

isArray() / isEmptyObject() / isFunction() / isPlainObject()

Sometimes you want to make sure the parameter that was passed to a function was the corrent type; these functions make it easy to do. The first three are pretty self explanatory:

$.isArray([1, 2, 3]); // returns true
$.isEmptyObject({}); // returns true
$.isFunction(function () { /****/ }); // returns true
The next one isn’t as obvious; isPlainObject() will return true if the parameter passed in was created as an object literal, or with new Object().

function Person(name) {
this.name = name
return this;
}
$.isPlainObject({})); // returns true
$.isPlainObject(new Object()); // returns true
$.isPlainObject(new Person()); // returns false

makeArray()

When you create a collection of DOM elements with jQuery, you’re returned a jQuery object; in some situations, you might prefer that this be an array or regular DOM elements; the makeArray() function can do just that.

var ps = $(‘p’);
$.isArray(ps); //returns false;
ps = $.makeArray(ps);
$.isArray(ps); // returns true;

map()

The map() method is remotely similar to grep(). As you might expect, it takes one parameter, a function. That function can have two parameters: the index of the current element and the element itself. Here’s what happens: the function that you pass in will be run once for each item in the collection; whatever value is returned from that function takes the place of the item it was run for in the collection.

$(‘ul#nav li a’).map(function() {
return $(this).attr(‘title’);
}); // now the collection is the link titles
// this could be the beginning of a tooltip plugin.

parseJSON()

If you’re using $.post or $.get—and in other situations that you work with JSON strings—you’ll find the parseJSON function useful. It’s nice that this function uses the browsers built-in JSON parser if it has one (which will obviously be faster).

$.post(‘somePage.php’, function (data) {
/*****/
data = $.parseJSON(data);
/*****/
});

proxy()

If you have a function as a property of an object, and that function uses other properties of the object, you can’t call that function from within other functions and get the right results. I know that was confusing, so let’s look at a quick example:
var person = {
name : “Andrew”,
meet : function () {
alert(‘Hi! My name is ‘ + this.name);
}
};
person.meet();
$(‘#test’).click(person.meet);
By itself, person.meet() will alert correctly; but when it’s called by the event handler, it will alert “Hi! My name is undefined.” This is because the function is not being called in the right context. To fix this, we can use the proxy() function:

$(‘#test’).click($.proxy(person.meet, person));
// we could also do $.proxy(person, “meet”)
The first parameter of the proxy function is the method to run; the second is the context we should run it in. Alternatively, we can pass the context first, and the method name as a string second. Now you’ll find that the function alerts correctly.

replaceAll() / replaceWith()

If you’d like to replace DOM elements with other ones, here’s how to do it. We can call replaceAll() on elements we’ve collected or created, passing in a selector for the elements we’d like to replace. In this example, all elements with the error class will be replaced with the span we’ve created.

$(‘<span class=”fixed”>The error has been corrected</span>’).replaceAll(‘.error’);
The replaceWith() method just reverses the selectors; find the ones you want to replace first:

$(‘.error’).replaceWith(‘<span class=”fixed”>The error has been corrected</span>’);
You can also pass these two methods functions that will return elements or HTML strings.

serialize() / serializeArray()

The serialize() method is what to use for encoding the values in a form into a string.

HTML
<form>
<input type=”text” name=”name” value=”John Doe” />
<input type=”text” name=”url” value=”http://www.example.com” />
</form>
JavaScript

console.log($(‘form’).serialize());​​​ // logs : name=John+Doe&url=http%3A%2F%2Fwww.example.com
You can use serializeArray() to turn the form values into an array of objects instead of a string:

console.log($(‘form’).serializeArray());​​​
// logs : [{ name : ‘name’, value : ‘John Doe’} , { name : ‘url’, value : ‘http://www.example.com’ } ]

siblings()

You can probably guess what the siblings() method does; it will return a collection of the siblings of the whatever items are in your original collections:

<div> . . . </div>
<p> . . . </p>
<span> . . . </span>
$(‘p’).siblings(); // returns <div>, <span>

wrap() / wrapAll() / wrapInner()

These three functions make it easy to wrap elements in other elements. First off, I’ll mention that all three take one parameter: either an element (which is an HTML string, a CSS selctor, a jQuery object, or a DOM element) or a function that returns an element.
The wrap() method wraps each item in the collection with the assigned element:

$(‘p’).wrap(‘<div class=”warning” />’); // all paragraphs are now wrapped in a div.warning
The wrapAll() will wrap one element around all the elements in the collection; this means that the elements in the collection will be moved to a new spot in the DOM; they’ll line up at the place of the first element in the collection and be wrapped there:

FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare

switch example in AngularJS

A simple switch example in AngularJS

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js"></script>
</head>

<body ng-app>
  <label>Type the number you want to show (1 to 3): <input type="text" ng-model="showNumber" /></label><br />
  <div ng-switch="showNumber">
    <div ng-switch-when="1" style="width: 50px; background-color: red; text-align: center;">1</div>
    <div ng-switch-when="2" style="width: 50px; background-color: blue; text-align: center;">2</div>
    <div ng-switch-when="3" style="width: 50px; background-color: green; text-align: center;">3</div>
    <div ng-switch-default style="width: 50px; background-color: lightgray; text-align: center;">None</div>
  </div>
</body>
</html>
FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare

If example in AngularJS

In this example if you check and uncheck a box


<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js"></script>
</head>

<body ng-app>
  <label>Show the square: <input type="checkbox" ng-model="mustShow" /></label><br />
  <div ng-if="mustShow" style="width: 780px; height: 90px; background-color: red;"></div>
  <div ng-if="!mustShow" style="width: 100px; background-color: lightgray; text-align: center;">Not shown</div>
</div>
</body>
</html>
FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare

jQuery Traversing

.add()  Create a new jQuery object with elements added to the set of matched elements.
.addBack()  Add the previous set of elements on the stack to the current set, optionally filtered by a selector.
.andSelf()  Add the previous set of elements on the stack to the current set.
.children()  Get the children of each element in the set of matched elements, optionally filtered by a selector.
.closest()  For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
.contents()  Get the children of each element in the set of matched elements, including text and comment nodes.
.each()  Iterate over a jQuery object, executing a function for each matched element.
.end()  End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
.eq()  Reduce the set of matched elements to the one at the specified index.
.filter()  Reduce the set of matched elements to those that match the selector or pass the function’s test.
.find()  Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
.first()  Reduce the set of matched elements to the first in the set.
.has()  Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.
.is()  Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
.last()  Reduce the set of matched elements to the final one in the set.
.map()  Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
.next()  Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
.nextAll()  Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.
.nextUntil()  Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.
.not()  Remove elements from the set of matched elements.
.offsetParent()  Get the closest ancestor element that is positioned.
.parent()  Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
.parents()  Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.
.parentsUntil()  Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.
.prev()  Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.
.prevAll()  Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.
.prevUntil()  Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.
.siblings()  Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
.slice()  Reduce the set of matched elements to a subset specified by a range of indices.
FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare

Debug output in AngularJS

This example shows how to log debug out from AngularJS, you will need to open a Javascript console window to see this

In Chrome you can do this by holding down Ctrl + Shift + J and the window will appear

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js"></script>
</head>
<body>
  <div ng-app="app">
    <div ng-controller="MainCtrl">
        <h3>Open a javascript console so you can see the output.</h3>
    </div>
</div>
<script type='text/javascript'>
angular.module('app', []).controller('MainCtrl', ['$log', function($log){
    $log.debug('Hello Debug!');
}]);
</script>
</body>
</html>
FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare

Python 2.7 Regular Expressions

\       Escape special char or start a sequence.
.       Match any char except newline, see re.DOTALL
^       Match start of the string, see re.MULTILINE
$       Match end of the string, see re.MULTILINE
[]      Enclose a set of matchable chars
R|S     Match either regex R or regex S.
()      Create capture group, & indicate precedence

After ‘[‘, enclose a set, the only special chars are:

]   End the set, if not the 1st char
-   A range, eg. a-c matches a, b or c
^   Negate the set only if it is the 1st char

Quantifiers (append ‘?‘ for non-greedy):

{m}     Exactly m repetitions
{m,n}   From m (default 0) to n (default infinity)
*       0 or more. Same as {,}
+       1 or more. Same as {1,}
?       0 or 1. Same as {,1}

Special sequences:

\A  Start of string
\b  Match empty string at word (\w+) boundary
\B  Match empty string not at word boundary
\d  Digit
\D  Non-digit
\s  Whitespace [ \t\n\r\f\v], see LOCALE,UNICODE
\S  Non-whitespace
\w  Alphanumeric: [0-9a-zA-Z_], see LOCALE
\W  Non-alphanumeric
\Z  End of string
\g<id>  Match prev named or numbered group,
        '<' & '>' are literal, e.g. \g<0>
        or \g<name> (not \g0 or \gname)

Special character escapes are much like those already escaped in Python string literals. Hence regex ‘\n‘ is same as regex ‘\\n‘:

\a  ASCII Bell (BEL)
\f  ASCII Formfeed
\n  ASCII Linefeed
\r  ASCII Carriage return
\t  ASCII Tab
\v  ASCII Vertical tab
\\  A single backslash
\xHH   Two digit hexadecimal character goes here
\OOO   Three digit octal char (or just use an
       initial zero, e.g. \0, \09)
\DD    Decimal number 1 to 99, match
       previous numbered group

Extensions. Do not cause grouping, except ‘P<name>‘:

(?iLmsux)     Match empty string, sets re.X flags
(?:...)       Non-capturing version of regular parens
(?P<name>...) Create a named capturing group.
(?P=name)     Match whatever matched prev named group
(?#...)       A comment; ignored.
(?=...)       Lookahead assertion, match without consuming
(?!...)       Negative lookahead assertion
(?<=...)      Lookbehind assertion, match if preceded
(?<!...)      Negative lookbehind assertion
(?(id)y|n)    Match 'y' if group 'id' matched, else 'n'

Flags for re.compile(), etc. Combine with '|':

re.I == re.IGNORECASE   Ignore case
re.L == re.LOCALE       Make \w, \b, and \s locale dependent
re.M == re.MULTILINE    Multiline
re.S == re.DOTALL       Dot matches all (including newline)
re.U == re.UNICODE      Make \w, \b, \d, and \s unicode dependent
re.X == re.VERBOSE      Verbose (unescaped whitespace in pattern
                        is ignored, and '#' marks comment lines)

Module level functions:

compile(pattern[, flags]) -> RegexObject
match(pattern, string[, flags]) -> MatchObject
search(pattner, string[, flags]) -> MatchObject
findall(pattern, string[, flags]) -> list of strings
finditer(pattern, string[, flags]) -> iter of MatchObjects
split(pattern, string[, maxsplit, flags]) -> list of strings
sub(pattern, repl, string[, count, flags]) -> string
subn(pattern, repl, string[, count, flags]) -> (string, int)
escape(string) -> string
purge() # the re cache

RegexObjects (returned from compile()):

.match(string[, pos, endpos]) -> MatchObject
.search(string[, pos, endpos]) -> MatchObject
.findall(string[, pos, endpos]) -> list of strings
.finditer(string[, pos, endpos]) -> iter of MatchObjects
.split(string[, maxsplit]) -> list of strings
.sub(repl, string[, count]) -> string
.subn(repl, string[, count]) -> (string, int)
.flags      # int, Passed to compile()
.groups     # int, Number of capturing groups
.groupindex # {}, Maps group names to ints
.pattern    # string, Passed to compile()

MatchObjects (returned from match() and search()):

.expand(template) -> string, Backslash & group expansion
.group([group1...]) -> string or tuple of strings, 1 per arg
.groups([default]) -> tuple of all groups, non-matching=default
.groupdict([default]) -> {}, Named groups, non-matching=default
.start([group]) -> int, Start/end of substring match by group
.end([group]) -> int, Group defaults to 0, the whole match
.span([group]) -> tuple (match.start(group), match.end(group))
.pos       int, Passed to search() or match()
.endpos    int, "
.lastindex int, Index of last matched capturing group
.lastgroup string, Name of last matched capturing group
.re        regex, As passed to search() or match()
.string    string, "
FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare