Compare commits

..

No commits in common. "master" and "1.5.2" have entirely different histories.

56 changed files with 3007 additions and 5794 deletions

View file

@ -111,7 +111,7 @@ update_submodules:
# update the submodules to the latest at the most logical branch # update the submodules to the latest at the most logical branch
pull_submodules: pull_submodules:
@@git submodule foreach "git pull \$$(git config remote.origin.url)" @@git submodule foreach "git pull origin \$$(git branch --no-color --contains \$$(git rev-parse HEAD) | grep -v \( | head -1)"
@@git submodule summary @@git submodule summary
pull: pull_submodules pull: pull_submodules

View file

@ -1,4 +1,4 @@
[jQuery](http://jquery.com/) - New Wave JavaScript [jQuery](http://jquery.com/) - New Wave Javascript
================================================== ==================================================
What you need to build your own jQuery What you need to build your own jQuery
@ -56,89 +56,6 @@ Sometimes, the various git repositories get into an inconsistent state where bui
(usually this results in the jquery.js or jquery.min.js being 0 bytes). If this happens, run `make clean`, then (usually this results in the jquery.js or jquery.min.js being 0 bytes). If this happens, run `make clean`, then
run `make` again. run `make` again.
Git for dummies
---------------
As the source code is handled by the version control system Git, it's useful to know some features used.
### Submodules ###
The repository uses submodules, which normally are handled directly by the Makefile, but sometimes you want to
be able to work with them manually.
Following are the steps to manually get the submodules:
1. `git clone https://github.com/jquery/jquery.git`
2. `git submodule init`
3. `git submodule update`
Or:
1. `git clone https://github.com/jquery/jquery.git`
2. `git submodule update --init`
Or:
1. `git clone --recursive https://github.com/jquery/jquery.git`
If you want to work inside a submodule, it is possible, but first you need to checkout a branch:
1. `cd src/sizzle`
2. `git checkout master`
After you've committed your changes to the submodule, you'll update the jquery project to point to the new commit,
but remember to push the submodule changes before pushing the new jquery commit:
1. `cd src/sizzle`
2. `git push origin master`
3. `cd ..`
4. `git add src/sizzle`
5. `git commit`
The makefile has some targets to simplify submodule handling:
#### `make update_submodules` ####
checks out the commit pointed to by jquery, but merges your local changes, if any. This target is executed
when you are doing a normal `make`.
#### `make pull_submodules` ####
updates the content of the submodules to what is probably the latest upstream code.
#### `make pull` ####
make a `make pull_submodules` and after that a `git pull`. if you have no remote tracking in your master branch, you can
execute this command as `make pull REMOTE=origin BRANCH=master` instead.
### cleaning ###
If you want to purge your working directory back to the status of upstream, following commands can be used (remember everything you've worked on is gone after these):
1. `git reset --hard upstream/master`
2. `git clean -fdx`
### rebasing ###
For feature/topic branches, you should always used the `--rebase` flag to `git pull`, or if you are usually handling many temporary "to be in a github pull request" branches, run following to automate this:
* `git config branch.autosetuprebase local` (see `man git-config` for more information)
### handling merge conflicts ###
If you're getting merge conflicts when merging, instead of editing the conflicted files manually, you can use the feature
`git mergetool`. Even though the default tool `xxdiff` looks awful/old, it's rather useful.
Following are some commands that can be used there:
* `Ctrl + Alt + M` - automerge as much as possible
* `b` - jump to next merge conflict
* `s` - change the order of the conflicted lines
* `u` - undo an merge
* `left mouse button` - mark a block to be the winner
* `middle mouse button` - mark a line to be the winner
* `Ctrl + S` - save
* `Ctrl + Q` - quit
Questions? Questions?
---------- ----------

View file

@ -182,6 +182,8 @@ var OPERATORS = array_to_hash([
">>=", ">>=",
"<<=", "<<=",
">>>=", ">>>=",
"~=",
"%=",
"|=", "|=",
"^=", "^=",
"&=", "&=",
@ -189,7 +191,7 @@ var OPERATORS = array_to_hash([
"||" "||"
]); ]);
var WHITESPACE_CHARS = array_to_hash(characters(" \n\r\t\u200b")); var WHITESPACE_CHARS = array_to_hash(characters(" \n\r\t"));
var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{}(,.;:")); var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{}(,.;:"));
@ -199,47 +201,20 @@ var REGEXP_MODIFIERS = array_to_hash(characters("gmsiy"));
/* -----[ Tokenizer ]----- */ /* -----[ Tokenizer ]----- */
// regexps adapted from http://xregexp.com/plugins/#unicode function is_alphanumeric_char(ch) {
var UNICODE = { ch = ch.charCodeAt(0);
letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0523\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0621-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971\\u0972\\u097B-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D28\\u0D2A-\\u0D39\\u0D3D\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC\\u0EDD\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8B\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10D0-\\u10FA\\u10FC\\u1100-\\u1159\\u115F-\\u11A2\\u11A8-\\u11F9\\u1200-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u1676\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19A9\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u2094\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2C6F\\u2C71-\\u2C7D\\u2C80-\\u2CE4\\u2D00-\\u2D25\\u2D30-\\u2D65\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31B7\\u31F0-\\u31FF\\u3400\\u4DB5\\u4E00\\u9FC3\\uA000-\\uA48C\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA65F\\uA662-\\uA66E\\uA67F-\\uA697\\uA717-\\uA71F\\uA722-\\uA788\\uA78B\\uA78C\\uA7FB-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA90A-\\uA925\\uA930-\\uA946\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAC00\\uD7A3\\uF900-\\uFA2D\\uFA30-\\uFA6A\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"), return (ch >= 48 && ch <= 57) ||
non_spacing_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"), (ch >= 65 && ch <= 90) ||
space_combining_mark: new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"), (ch >= 97 && ch <= 122);
connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]")
}; };
function is_letter(ch) { function is_identifier_char(ch) {
return UNICODE.letter.test(ch); return is_alphanumeric_char(ch) || ch == "$" || ch == "_";
}; };
function is_digit(ch) { function is_digit(ch) {
ch = ch.charCodeAt(0); ch = ch.charCodeAt(0);
return ch >= 48 && ch <= 57; //XXX: find out if "UnicodeDigit" means something else than 0..9 return ch >= 48 && ch <= 57;
};
function is_alphanumeric_char(ch) {
return is_digit(ch) || is_letter(ch);
};
function is_unicode_combining_mark(ch) {
return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch);
};
function is_unicode_connector_punctuation(ch) {
return UNICODE.connector_punctuation.test(ch);
};
function is_identifier_start(ch) {
return ch == "$" || ch == "_" || is_letter(ch);
};
function is_identifier_char(ch) {
return is_identifier_start(ch)
|| is_unicode_combining_mark(ch)
|| is_digit(ch)
|| is_unicode_connector_punctuation(ch)
|| ch == "\u200c" // zero-width non-joiner <ZWNJ>
|| ch == "\u200d" // zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
;
}; };
function parse_js_number(num) { function parse_js_number(num) {
@ -278,7 +253,7 @@ function is_token(token, type, val) {
var EX_EOF = {}; var EX_EOF = {};
function tokenizer($TEXT) { function tokenizer($TEXT, skip_comments) {
var S = { var S = {
text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''), text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''),
@ -289,8 +264,7 @@ function tokenizer($TEXT) {
col : 0, col : 0,
tokcol : 0, tokcol : 0,
newline_before : false, newline_before : false,
regex_allowed : false, regex_allowed : false
comments_before : []
}; };
function peek() { return S.text.charAt(S.pos); }; function peek() { return S.text.charAt(S.pos); };
@ -325,7 +299,7 @@ function tokenizer($TEXT) {
S.tokpos = S.pos; S.tokpos = S.pos;
}; };
function token(type, value, is_comment) { function token(type, value) {
S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) || S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) ||
(type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) || (type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) ||
(type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value))); (type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value)));
@ -337,10 +311,6 @@ function tokenizer($TEXT) {
pos : S.tokpos, pos : S.tokpos,
nlb : S.newline_before nlb : S.newline_before
}; };
if (!is_comment) {
ret.comments_before = S.comments_before;
S.comments_before = [];
}
S.newline_before = false; S.newline_before = false;
return ret; return ret;
}; };
@ -381,7 +351,7 @@ function tokenizer($TEXT) {
if (ch == "+") return after_e; if (ch == "+") return after_e;
after_e = false; after_e = false;
if (ch == ".") { if (ch == ".") {
if (!has_dot && !has_x) if (!has_dot)
return has_dot = true; return has_dot = true;
return false; return false;
} }
@ -447,7 +417,7 @@ function tokenizer($TEXT) {
ret = S.text.substring(S.pos, i); ret = S.text.substring(S.pos, i);
S.pos = i; S.pos = i;
} }
return token("comment1", ret, true); return token("comment1", ret);
}; };
function read_multiline_comment() { function read_multiline_comment() {
@ -455,41 +425,14 @@ function tokenizer($TEXT) {
return with_eof_error("Unterminated multiline comment", function(){ return with_eof_error("Unterminated multiline comment", function(){
var i = find("*/", true), var i = find("*/", true),
text = S.text.substring(S.pos, i), text = S.text.substring(S.pos, i),
tok = token("comment2", text, true); tok = token("comment2", text);
S.pos = i + 2; S.pos = i + 2;
S.line += text.split("\n").length - 1; S.line += text.split("\n").length - 1;
S.newline_before = text.indexOf("\n") >= 0; S.newline_before = text.indexOf("\n") >= 0;
// https://github.com/mishoo/UglifyJS/issues/#issue/100
if (/^@cc_on/i.test(text)) {
warn("WARNING: at line " + S.line);
warn("*** Found \"conditional comment\": " + text);
warn("*** UglifyJS DISCARDS ALL COMMENTS. This means your code might no longer work properly in Internet Explorer.");
}
return tok; return tok;
}); });
}; };
function read_name() {
var backslash = false, name = "", ch;
while ((ch = peek()) != null) {
if (!backslash) {
if (ch == "\\") backslash = true, next();
else if (is_identifier_char(ch)) name += next();
else break;
}
else {
if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
ch = read_escaped_char();
if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
name += ch;
backslash = false;
}
}
return name;
};
function read_regexp() { function read_regexp() {
return with_eof_error("Unterminated regular expression", function(){ return with_eof_error("Unterminated regular expression", function(){
var prev_backslash = false, regexp = "", ch, in_class = false; var prev_backslash = false, regexp = "", ch, in_class = false;
@ -509,14 +452,15 @@ function tokenizer($TEXT) {
} else { } else {
regexp += ch; regexp += ch;
} }
var mods = read_name(); var mods = read_while(function(ch){
return HOP(REGEXP_MODIFIERS, ch);
});
return token("regexp", [ regexp, mods ]); return token("regexp", [ regexp, mods ]);
}); });
}; };
function read_operator(prefix) { function read_operator(prefix) {
function grow(op) { function grow(op) {
if (!peek()) return op;
var bigger = op + peek(); var bigger = op + peek();
if (HOP(OPERATORS, bigger)) { if (HOP(OPERATORS, bigger)) {
next(); next();
@ -528,18 +472,19 @@ function tokenizer($TEXT) {
return token("operator", grow(prefix || next())); return token("operator", grow(prefix || next()));
}; };
function handle_slash() { var handle_slash = skip_comments ? function() {
next(); next();
var regex_allowed = S.regex_allowed; var regex_allowed = S.regex_allowed;
switch (peek()) { switch (peek()) {
case "/": case "/": read_line_comment(); S.regex_allowed = regex_allowed; return next_token();
S.comments_before.push(read_line_comment()); case "*": read_multiline_comment(); S.regex_allowed = regex_allowed; return next_token();
S.regex_allowed = regex_allowed; }
return next_token(); return S.regex_allowed ? read_regexp() : read_operator("/");
case "*": } : function() {
S.comments_before.push(read_multiline_comment()); next();
S.regex_allowed = regex_allowed; switch (peek()) {
return next_token(); case "/": return read_line_comment();
case "*": return read_multiline_comment();
} }
return S.regex_allowed ? read_regexp() : read_operator("/"); return S.regex_allowed ? read_regexp() : read_operator("/");
}; };
@ -552,7 +497,7 @@ function tokenizer($TEXT) {
}; };
function read_word() { function read_word() {
var word = read_name(); var word = read_while(is_identifier_char);
return !HOP(KEYWORDS, word) return !HOP(KEYWORDS, word)
? token("name", word) ? token("name", word)
: HOP(OPERATORS, word) : HOP(OPERATORS, word)
@ -584,7 +529,7 @@ function tokenizer($TEXT) {
if (ch == ".") return handle_dot(); if (ch == ".") return handle_dot();
if (ch == "/") return handle_slash(); if (ch == "/") return handle_slash();
if (HOP(OPERATOR_CHARS, ch)) return read_operator(); if (HOP(OPERATOR_CHARS, ch)) return read_operator();
if (ch == "\\" || is_identifier_start(ch)) return read_word(); if (is_identifier_char(ch)) return read_word();
parse_error("Unexpected character '" + ch + "'"); parse_error("Unexpected character '" + ch + "'");
}; };
@ -620,7 +565,7 @@ var ASSIGNMENT = (function(a, ret, i){
} }
return ret; return ret;
})( })(
["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&="], ["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "~=", "%=", "|=", "^=", "&="],
{ "=": true }, { "=": true },
0 0
); );
@ -663,16 +608,16 @@ function NodeWithToken(str, start, end) {
NodeWithToken.prototype.toString = function() { return this.name; }; NodeWithToken.prototype.toString = function() { return this.name; };
function parse($TEXT, exigent_mode, embed_tokens) { function parse($TEXT, strict_mode, embed_tokens) {
var S = { var S = {
input : typeof $TEXT == "string" ? tokenizer($TEXT, true) : $TEXT, input: tokenizer($TEXT, true),
token : null, token: null,
prev : null, prev: null,
peeked : null, peeked: null,
in_function : 0, in_function: 0,
in_loop : 0, in_loop: 0,
labels : [] labels: []
}; };
S.token = next(); S.token = next();
@ -726,7 +671,7 @@ function parse($TEXT, exigent_mode, embed_tokens) {
function expect(punc) { return expect_token("punc", punc); }; function expect(punc) { return expect_token("punc", punc); };
function can_insert_semicolon() { function can_insert_semicolon() {
return !exigent_mode && ( return !strict_mode && (
S.token.nlb || is("eof") || is("punc", "}") S.token.nlb || is("eof") || is("punc", "}")
); );
}; };
@ -748,20 +693,17 @@ function parse($TEXT, exigent_mode, embed_tokens) {
}; };
function add_tokens(str, start, end) { function add_tokens(str, start, end) {
return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end); return new NodeWithToken(str, start, end);
}; };
function maybe_embed_tokens(parser) { var statement = embed_tokens ? function() {
if (embed_tokens) return function() {
var start = S.token; var start = S.token;
var ast = parser.apply(this, arguments); var stmt = $statement();
ast[0] = add_tokens(ast[0], start, prev()); stmt[0] = add_tokens(stmt[0], start, prev());
return ast; return stmt;
}; } : $statement;
else return parser;
};
var statement = maybe_embed_tokens(function() { function $statement() {
if (is("operator", "/")) { if (is("operator", "/")) {
S.peeked = null; S.peeked = null;
S.token = S.input(true); // force regexp S.token = S.input(true); // force regexp
@ -855,12 +797,12 @@ function parse($TEXT, exigent_mode, embed_tokens) {
unexpected(); unexpected();
} }
} }
}); };
function labeled_statement(label) { function labeled_statement(label) {
S.labels.push(label); S.labels.push(label);
var start = S.token, stat = statement(); var start = S.token, stat = statement();
if (exigent_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0])) if (strict_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0]))
unexpected(start); unexpected(start);
S.labels.pop(); S.labels.pop();
return as("label", label, stat); return as("label", label, stat);
@ -885,35 +827,29 @@ function parse($TEXT, exigent_mode, embed_tokens) {
function for_() { function for_() {
expect("("); expect("(");
var init = null; var has_var = is("keyword", "var");
if (!is("punc", ";")) { if (has_var)
init = is("keyword", "var") next();
? (next(), var_(true)) if (is("name") && is_token(peek(), "operator", "in")) {
: expression(true, true); // for (i in foo)
if (is("operator", "in")) var name = S.token.value;
return for_in(init); next(); next();
} var obj = expression();
return regular_for(init); expect(")");
}; return as("for-in", has_var, name, obj, in_loop(statement));
} else {
function regular_for(init) { // classic for
var init = is("punc", ";") ? null : has_var ? var_() : expression();
expect(";"); expect(";");
var test = is("punc", ";") ? null : expression(); var test = is("punc", ";") ? null : expression();
expect(";"); expect(";");
var step = is("punc", ")") ? null : expression(); var step = is("punc", ")") ? null : expression();
expect(")"); expect(")");
return as("for", init, test, step, in_loop(statement)); return as("for", init, test, step, in_loop(statement));
}
}; };
function for_in(init) { function function_(in_statement) {
var lhs = init[0] == "var" ? as("name", init[1][0]) : init;
next();
var obj = expression();
expect(")");
return as("for-in", init, lhs, obj, in_loop(statement));
};
var function_ = maybe_embed_tokens(function(in_statement) {
var name = is("name") ? prog1(S.token.value, next) : null; var name = is("name") ? prog1(S.token.value, next) : null;
if (in_statement && !name) if (in_statement && !name)
unexpected(); unexpected();
@ -941,7 +877,7 @@ function parse($TEXT, exigent_mode, embed_tokens) {
S.in_loop = loop; S.in_loop = loop;
return a; return a;
})()); })());
}); };
function if_() { function if_() {
var cond = parenthesised(), body = statement(), belse; var cond = parenthesised(), body = statement(), belse;
@ -1010,7 +946,7 @@ function parse($TEXT, exigent_mode, embed_tokens) {
return as("try", body, bcatch, bfinally); return as("try", body, bcatch, bfinally);
}; };
function vardefs(no_in) { function vardefs() {
var a = []; var a = [];
for (;;) { for (;;) {
if (!is("name")) if (!is("name"))
@ -1019,7 +955,7 @@ function parse($TEXT, exigent_mode, embed_tokens) {
next(); next();
if (is("operator", "=")) { if (is("operator", "=")) {
next(); next();
a.push([ name, expression(false, no_in) ]); a.push([ name, expression(false) ]);
} else { } else {
a.push([ name ]); a.push([ name ]);
} }
@ -1030,8 +966,8 @@ function parse($TEXT, exigent_mode, embed_tokens) {
return a; return a;
}; };
function var_(no_in) { function var_() {
return as("var", vardefs(no_in)); return as("var", vardefs());
}; };
function const_() { function const_() {
@ -1049,7 +985,7 @@ function parse($TEXT, exigent_mode, embed_tokens) {
return subscripts(as("new", newexp, args), true); return subscripts(as("new", newexp, args), true);
}; };
var expr_atom = maybe_embed_tokens(function(allow_calls) { function expr_atom(allow_calls) {
if (is("operator", "new")) { if (is("operator", "new")) {
next(); next();
return new_(); return new_();
@ -1084,32 +1020,29 @@ function parse($TEXT, exigent_mode, embed_tokens) {
return subscripts(prog1(atom, next), allow_calls); return subscripts(prog1(atom, next), allow_calls);
} }
unexpected(); unexpected();
}); };
function expr_list(closing, allow_trailing_comma, allow_empty) { function expr_list(closing, allow_trailing_comma) {
var first = true, a = []; var first = true, a = [];
while (!is("punc", closing)) { while (!is("punc", closing)) {
if (first) first = false; else expect(","); if (first) first = false; else expect(",");
if (allow_trailing_comma && is("punc", closing)) break; if (allow_trailing_comma && is("punc", closing))
if (is("punc", ",") && allow_empty) { break;
a.push([ "atom", "undefined" ]);
} else {
a.push(expression(false)); a.push(expression(false));
} }
}
next(); next();
return a; return a;
}; };
function array_() { function array_() {
return as("array", expr_list("]", !exigent_mode, true)); return as("array", expr_list("]", !strict_mode));
}; };
function object_() { function object_() {
var first = true, a = []; var first = true, a = [];
while (!is("punc", "}")) { while (!is("punc", "}")) {
if (first) first = false; else expect(","); if (first) first = false; else expect(",");
if (!exigent_mode && is("punc", "}")) if (!strict_mode && is("punc", "}"))
// allow trailing comma // allow trailing comma
break; break;
var type = S.token.type; var type = S.token.type;
@ -1172,68 +1105,64 @@ function parse($TEXT, exigent_mode, embed_tokens) {
return as(tag, op, expr); return as(tag, op, expr);
}; };
function expr_op(left, min_prec, no_in) { function expr_op(left, min_prec) {
var op = is("operator") ? S.token.value : null; var op = is("operator") ? S.token.value : null;
if (op && op == "in" && no_in) op = null;
var prec = op != null ? PRECEDENCE[op] : null; var prec = op != null ? PRECEDENCE[op] : null;
if (prec != null && prec > min_prec) { if (prec != null && prec > min_prec) {
next(); next();
var right = expr_op(expr_atom(true), prec, no_in); var right = expr_op(expr_atom(true), prec);
return expr_op(as("binary", op, left, right), min_prec, no_in); return expr_op(as("binary", op, left, right), min_prec);
} }
return left; return left;
}; };
function expr_ops(no_in) { function expr_ops() {
return expr_op(expr_atom(true), 0, no_in); return expr_op(expr_atom(true), 0);
}; };
function maybe_conditional(no_in) { function maybe_conditional() {
var expr = expr_ops(no_in); var expr = expr_ops();
if (is("operator", "?")) { if (is("operator", "?")) {
next(); next();
var yes = expression(false); var yes = expression(false);
expect(":"); expect(":");
return as("conditional", expr, yes, expression(false, no_in)); return as("conditional", expr, yes, expression(false));
} }
return expr; return expr;
}; };
function is_assignable(expr) { function is_assignable(expr) {
if (!exigent_mode) return true;
switch (expr[0]) { switch (expr[0]) {
case "dot": case "dot":
case "sub": case "sub":
case "new":
case "call":
return true; return true;
case "name": case "name":
return expr[1] != "this"; return expr[1] != "this";
} }
}; };
function maybe_assign(no_in) { function maybe_assign() {
var left = maybe_conditional(no_in), val = S.token.value; var left = maybe_conditional(), val = S.token.value;
if (is("operator") && HOP(ASSIGNMENT, val)) { if (is("operator") && HOP(ASSIGNMENT, val)) {
if (is_assignable(left)) { if (is_assignable(left)) {
next(); next();
return as("assign", ASSIGNMENT[val], left, maybe_assign(no_in)); return as("assign", ASSIGNMENT[val], left, maybe_assign());
} }
croak("Invalid assignment"); croak("Invalid assignment");
} }
return left; return left;
}; };
var expression = maybe_embed_tokens(function(commas, no_in) { function expression(commas) {
if (arguments.length == 0) if (arguments.length == 0)
commas = true; commas = true;
var expr = maybe_assign(no_in); var expr = maybe_assign();
if (commas && is("punc", ",")) { if (commas && is("punc", ",")) {
next(); next();
return as("seq", expr, expression(true, no_in)); return as("seq", expr, expression());
} }
return expr; return expr;
}); };
function in_loop(cont) { function in_loop(cont) {
try { try {
@ -1293,8 +1222,6 @@ function HOP(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop); return Object.prototype.hasOwnProperty.call(obj, prop);
}; };
var warn = function() {};
/* -----[ Exports ]----- */ /* -----[ Exports ]----- */
exports.tokenizer = tokenizer; exports.tokenizer = tokenizer;
@ -1310,6 +1237,3 @@ exports.KEYWORDS = KEYWORDS;
exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN; exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN;
exports.OPERATORS = OPERATORS; exports.OPERATORS = OPERATORS;
exports.is_alphanumeric_char = is_alphanumeric_char; exports.is_alphanumeric_char = is_alphanumeric_char;
exports.set_logger = function(logger) {
warn = logger;
};

File diff suppressed because it is too large Load diff

View file

@ -4,4 +4,4 @@ var print = require("sys").print,
src = require("fs").readFileSync(process.argv[2], "utf8"); src = require("fs").readFileSync(process.argv[2], "utf8");
// Previously done in sed but reimplemented here due to portability issues // Previously done in sed but reimplemented here due to portability issues
print( src.replace( /^(\s*\*\/)(.+)/m, "$1\n$2" ) + ";" ); print(src.replace(/^(\s*\*\/)(.+)/m, "$1\n$2;"));

View file

@ -1,54 +0,0 @@
#!/usr/bin/env node
/*
* jQuery Release Note Generator
*/
var fs = require("fs"),
http = require("http"),
tmpl = require("mustache"),
extract = /<a href="\/ticket\/(\d+)" title="View ticket">(.*?)<[^"]+"component">\s*(\S+)/g;
var opts = {
version: "1.6.2 RC 1",
short_version: "1.6.2rc1",
final_version: "1.6.2",
categories: []
};
http.request({
host: "bugs.jquery.com",
port: 80,
method: "GET",
path: "/query?status=closed&resolution=fixed&component=!web&order=component&milestone=" + opts.final_version
}, function (res) {
var data = [];
res.on( "data", function( chunk ) {
data.push( chunk );
});
res.on( "end", function() {
var match,
file = data.join(""),
cur;
while ( (match = extract.exec( file )) ) {
if ( "#" + match[1] !== match[2] ) {
var cat = match[3];
if ( !cur || cur.name !== cat ) {
cur = { name: match[3], niceName: match[3].replace(/^./, function(a){ return a.toUpperCase(); }), bugs: [] };
opts.categories.push( cur );
}
cur.bugs.push({ ticket: match[1], title: match[2] });
}
}
buildNotes();
});
}).end();
function buildNotes() {
console.log( tmpl.to_html( fs.readFileSync("release-notes.txt", "utf8"), opts ) );
}

View file

@ -1,27 +0,0 @@
<h2>jQuery {{version}} Released</h2>
<p>This is a preview release of jQuery. We're releasing it so that everyone can start testing the code in their applications, making sure that there are no major problems.</p>
<p>You can get the code from the jQuery CDN:</p>
<ul>
<li><a href="http://code.jquery.com/jquery-{{short_version}}.js">http://code.jquery.com/jquery-{{short_version}}.js</a></li>
</ul>
<p>You can help us by dropping that code into your existing application and letting us know that if anything no longer works. Please <a href="http://bugs.jquery.com/">file a bug</a> and be sure to mention that you're testing against jQuery {{version}}.</p>
<p>We want to encourage everyone from the community to try and <a href="http://docs.jquery.com/Getting_Involved">get involved</a> in contributing back to jQuery core. We've set up a <a href="http://docs.jquery.com/Getting_Involved">full page</a> of information dedicated towards becoming more involved with the team. The team is here and ready to help you help us!</p>
<h2>jQuery {{version}} Change Log</h2>
<p>The current change log of the {{version}} release.</p>
{{#categories}}
<h3>{{niceName}}</h3>
<ul>
{{#bugs}}
<li><a href="http://bugs.jquery.com/ticket/{{ticket}}">#{{ticket}}</a>: {{title}}</li>
{{/bugs}}
</ul>
{{/categories}}

View file

@ -1,169 +0,0 @@
#!/usr/bin/env node
/*
* jQuery Release Management
*/
var fs = require("fs"),
child = require("child_process"),
debug = false;
var scpURL = "jqadmin@code.origin.jquery.com:/var/www/html/code.jquery.com/",
cdnURL = "http://code.origin.jquery.com/",
version = /^[\d.]+(?:(?:a|b|rc)\d+|pre)?$/,
versionFile = "version.txt",
file = "dist/jquery.js",
minFile = "dist/jquery.min.js",
files = {
"jquery-VER.js": file,
"jquery-VER.min.js": minFile
},
finalFiles = {
"jquery.js": file,
"jquery-latest.js": file,
"jquery.min.js": minFile,
"jquery-latest.min.js": minFile
};
exec( "git pull && git status", function( error, stdout, stderr ) {
if ( /Changes to be committed/i.test( stdout ) ) {
exit( "Please commit changed files before attemping to push a release." );
} else if ( /Changes not staged for commit/i.test( stdout ) ) {
exit( "Please stash files before attempting to push a release." );
} else {
setVersion();
}
});
function setVersion() {
var oldVersion = fs.readFileSync( versionFile, "utf8" );
prompt( "New Version (was " + oldVersion + "): ", function( data ) {
if ( data && version.test( data ) ) {
fs.writeFileSync( versionFile, data );
exec( "git commit -a -m 'Tagging the " + data + " release.' && git push && " +
"git tag " + data + " && git push origin " + data, function() {
make( data );
});
} else {
console.error( "Malformed version number, please try again." );
setVersion();
}
});
}
function make( newVersion ) {
exec( "make clean && make", function( error, stdout, stderr ) {
// TODO: Verify JSLint
Object.keys( files ).forEach(function( oldName ) {
var value = files[ oldName ], name = oldName.replace( /VER/g, newVersion );
copy( value, name );
delete files[ oldName ];
files[ name ] = value;
});
exec( "scp " + Object.keys( files ).join( " " ) + " " + scpURL, function() {
setNextVersion( newVersion );
});
});
}
function setNextVersion( newVersion ) {
var isFinal = false;
if ( /(?:a|b|rc)\d+$/.test( newVersion ) ) {
newVersion = newVersion.replace( /(?:a|b|rc)\d+$/, "pre" );
} else if ( /^\d+\.\d+\.?(\d*)$/.test( newVersion ) ) {
newVersion = newVersion.replace( /^(\d+\.\d+\.?)(\d*)$/, function( all, pre, num ) {
return pre + (pre.charAt( pre.length - 1 ) !== "." ? "." : "") + (num ? parseFloat( num ) + 1 : 1) + "pre";
});
isFinal = true;
}
prompt( "Next Version [" + newVersion + "]: ", function( data ) {
if ( !data ) {
data = newVersion;
}
if ( version.test( data ) ) {
fs.writeFileSync( versionFile, data );
exec( "git commit -a -m 'Updating the source version to " + data + "' && git push", function() {
if ( isFinal ) {
makeFinal( newVersion );
}
});
} else {
console.error( "Malformed version number, please try again." );
setNextVersion( newVersion );
}
});
}
function makeFinal( newVersion ) {
var all = Object.keys( finalFiles );
// Copy all the files
all.forEach(function( name ) {
copy( finalFiles[ name ], name );
});
// Upload files to CDN
exec( "scp " + all.join( " " ) + " " + scpURL, function() {
exec( "curl '" + cdnURL + "{" + all.join( "," ) + "}?reload'", function() {
console.log( "Done." );
});
});
}
function copy( oldFile, newFile ) {
if ( debug ) {
console.log( "Copying " + oldFile + " to " + newFile );
} else {
fs.writeFileSync( newFile, fs.readFileSync( oldFile, "utf8" ) );
}
}
function prompt( msg, callback ) {
process.stdout.write( msg );
process.stdin.resume();
process.stdin.setEncoding( "utf8" );
process.stdin.once( "data", function( chunk ) {
process.stdin.pause();
callback( chunk.replace( /\n*$/g, "" ) );
});
}
function exec( cmd, fn ) {
if ( debug ) {
console.log( cmd );
fn();
} else {
child.exec( cmd, fn );
}
}
function exit( msg ) {
if ( msg ) {
console.error( "\nError: " + msg );
}
process.exit( 1 );
}

View file

@ -1,11 +1,15 @@
#! /usr/bin/env node #! /usr/bin/env node
// -*- js -*- // -*- js2 -*-
global.sys = require(/^v0\.[012]/.test(process.version) ? "sys" : "util"); global.sys = require(/^v0\.[012]/.test(process.version) ? "sys" : "util");
var fs = require("fs"); var fs = require("fs"),
var jsp = require("./lib/parse-js"), jsp = require("./lib/parse-js"),
pro = require("./lib/process"); pro = require("./lib/process");
pro.set_logger(function(msg){
sys.debug(msg);
});
var options = { var options = {
ast: false, ast: false,
mangle: true, mangle: true,
@ -13,16 +17,13 @@ var options = {
squeeze: true, squeeze: true,
make_seqs: true, make_seqs: true,
dead_code: true, dead_code: true,
beautify: false,
verbose: false, verbose: false,
show_copyright: true, show_copyright: true,
out_same_file: false, out_same_file: false,
max_line_length: 32 * 1024, extra: false,
unsafe: false, unsafe: false, // XXX: extra & unsafe? but maybe we don't want both, so....
reserved_names: null, beautify_options: {
defines: { },
codegen_options: {
ascii_only: false,
beautify: false,
indent_level: 4, indent_level: 4,
indent_start: 0, indent_start: 0,
quote_keys: false, quote_keys: false,
@ -39,15 +40,15 @@ out: while (args.length > 0) {
switch (v) { switch (v) {
case "-b": case "-b":
case "--beautify": case "--beautify":
options.codegen_options.beautify = true; options.beautify = true;
break; break;
case "-i": case "-i":
case "--indent": case "--indent":
options.codegen_options.indent_level = args.shift(); options.beautify_options.indent_level = args.shift();
break; break;
case "-q": case "-q":
case "--quote-keys": case "--quote-keys":
options.codegen_options.quote_keys = true; options.beautify_options.quote_keys = true;
break; break;
case "-mt": case "-mt":
case "--mangle-toplevel": case "--mangle-toplevel":
@ -85,109 +86,23 @@ out: while (args.length > 0) {
case "--ast": case "--ast":
options.ast = true; options.ast = true;
break; break;
case "--extra":
options.extra = true;
break;
case "--unsafe": case "--unsafe":
options.unsafe = true; options.unsafe = true;
break; break;
case "--max-line-len":
options.max_line_length = parseInt(args.shift(), 10);
break;
case "--reserved-names":
options.reserved_names = args.shift().split(",");
break;
case "-d":
case "--define":
var defarg = args.shift();
try {
var defsym = function(sym) {
// KEYWORDS_ATOM doesn't include NaN or Infinity - should we check
// for them too ?? We don't check reserved words and the like as the
// define values are only substituted AFTER parsing
if (jsp.KEYWORDS_ATOM.hasOwnProperty(sym)) {
throw "Don't define values for inbuilt constant '"+sym+"'";
}
return sym;
},
defval = function(v) {
if (v.match(/^"(.*)"$/) || v.match(/^'(.*)'$/)) {
return [ "string", RegExp.$1 ];
}
else if (!isNaN(parseFloat(v))) {
return [ "num", parseFloat(v) ];
}
else if (v.match(/^[a-z\$_][a-z\$_0-9]*$/i)) {
return [ "name", v ];
}
else if (!v.match(/"/)) {
return [ "string", v ];
}
else if (!v.match(/'/)) {
return [ "string", v ];
}
throw "Can't understand the specified value: "+v;
};
if (defarg.match(/^([a-z_\$][a-z_\$0-9]*)(=(.*))?$/i)) {
var sym = defsym(RegExp.$1),
val = RegExp.$2 ? defval(RegExp.$2.substr(1)) : [ 'name', 'true' ];
options.defines[sym] = val;
}
else {
throw "The --define option expects SYMBOL[=value]";
}
} catch(ex) {
sys.print("ERROR: In option --define "+defarg+"\n"+ex+"\n");
process.exit(1);
}
break;
case "--define-from-module":
var defmodarg = args.shift(),
defmodule = require(defmodarg),
sym,
val;
for (sym in defmodule) {
if (defmodule.hasOwnProperty(sym)) {
options.defines[sym] = function(val) {
if (typeof val == "string")
return [ "string", val ];
if (typeof val == "number")
return [ "num", val ];
if (val === true)
return [ 'name', 'true' ];
if (val === false)
return [ 'name', 'false' ];
if (val === null)
return [ 'name', 'null' ];
if (val === undefined)
return [ 'name', 'undefined' ];
sys.print("ERROR: In option --define-from-module "+defmodarg+"\n");
sys.print("ERROR: Unknown object type for: "+sym+"="+val+"\n");
process.exit(1);
return null;
}(defmodule[sym]);
}
}
break;
case "--ascii":
options.codegen_options.ascii_only = true;
break;
default: default:
filename = v; filename = v;
break out; break out;
} }
} }
if (options.verbose) {
pro.set_logger(function(msg){
sys.debug(msg);
});
}
jsp.set_logger(function(msg){
sys.debug(msg);
});
if (filename) { if (filename) {
fs.readFile(filename, "utf8", function(err, text){ fs.readFile(filename, "utf8", function(err, text){
if (err) throw err; if (err) {
throw err;
}
output(squeeze_it(text)); output(squeeze_it(text));
}); });
} else { } else {
@ -216,9 +131,7 @@ function output(text) {
}); });
} }
out.write(text); out.write(text);
if (options.output !== true) {
out.end(); out.end();
}
}; };
// --------- main ends here. // --------- main ends here.
@ -239,24 +152,28 @@ function show_copyright(comments) {
function squeeze_it(code) { function squeeze_it(code) {
var result = ""; var result = "";
if (options.show_copyright) { if (options.show_copyright) {
var tok = jsp.tokenizer(code), c; var initial_comments = [];
// keep first comment
var tok = jsp.tokenizer(code, false), c;
c = tok(); c = tok();
result += show_copyright(c.comments_before); var prev = null;
while (/^comment/.test(c.type) && (!prev || prev == c.type)) {
initial_comments.push(c);
prev = c.type;
c = tok();
}
result += show_copyright(initial_comments);
} }
try { try {
var ast = time_it("parse", function(){ return jsp.parse(code); }); var ast = time_it("parse", function(){ return jsp.parse(code); });
if (options.mangle) ast = time_it("mangle", function(){ if (options.mangle)
return pro.ast_mangle(ast, { ast = time_it("mangle", function(){ return pro.ast_mangle(ast, options.mangle_toplevel); });
toplevel: options.mangle_toplevel, if (options.squeeze)
defines: options.defines, ast = time_it("squeeze", function(){
except: options.reserved_names
});
});
if (options.squeeze) ast = time_it("squeeze", function(){
ast = pro.ast_squeeze(ast, { ast = pro.ast_squeeze(ast, {
make_seqs : options.make_seqs, make_seqs : options.make_seqs,
dead_code : options.dead_code, dead_code : options.dead_code,
keep_comps : !options.unsafe extra : options.extra
}); });
if (options.unsafe) if (options.unsafe)
ast = pro.ast_squeeze_more(ast); ast = pro.ast_squeeze_more(ast);
@ -264,10 +181,7 @@ function squeeze_it(code) {
}); });
if (options.ast) if (options.ast)
return sys.inspect(ast, null, null); return sys.inspect(ast, null, null);
result += time_it("generate", function(){ return pro.gen_code(ast, options.codegen_options) }); result += time_it("generate", function(){ return pro.gen_code(ast, options.beautify && options.beautify_options) });
if (!options.codegen_options.beautify && options.max_line_length) {
result = time_it("split", function(){ return pro.split_lines(result, options.max_line_length) });
}
return result; return result;
} catch(ex) { } catch(ex) {
sys.debug(ex.stack); sys.debug(ex.stack);

View file

@ -5,9 +5,9 @@ var r20 = /%20/g,
rCRLF = /\r?\n/g, rCRLF = /\r?\n/g,
rhash = /#.*$/, rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
// #7653, #8125, #8152: local protocol detection // #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|widget):$/,
rnoContent = /^(?:GET|HEAD)$/, rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//, rprotocol = /^\/\//,
rquery = /\?/, rquery = /\?/,
@ -15,6 +15,10 @@ var r20 = /%20/g,
rselectTextarea = /^(?:select|textarea)/i, rselectTextarea = /^(?:select|textarea)/i,
rspacesAjax = /\s+/, rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/, rts = /([?&])_=[^&]*/,
rucHeaders = /(^|\-)([a-z])/g,
rucHeadersFunc = function( _, $1, $2 ) {
return $1 + $2.toUpperCase();
},
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
// Keep a copy of the old load method // Keep a copy of the old load method
@ -45,9 +49,9 @@ var r20 = /%20/g,
ajaxLocParts; ajaxLocParts;
// #8138, IE may throw an exception when accessing // #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set // a field from document.location if document.domain has been set
try { try {
ajaxLocation = location.href; ajaxLocation = document.location.href;
} catch( e ) { } catch( e ) {
// Use the href attribute of an A element // Use the href attribute of an A element
// since IE will modify it given document.location // since IE will modify it given document.location
@ -95,7 +99,7 @@ function addToPrefiltersOrTransports( structure ) {
}; };
} }
// Base inspection function for prefilters and transports //Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) { dataType /* internal */, inspected /* internal */ ) {
@ -244,7 +248,7 @@ jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".sp
jQuery.fn[ o ] = function( f ){ jQuery.fn[ o ] = function( f ){
return this.bind( o, f ); return this.bind( o, f );
}; };
}); } );
jQuery.each( [ "get", "post" ], function( i, method ) { jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) { jQuery[ method ] = function( url, data, callback, type ) {
@ -263,7 +267,7 @@ jQuery.each( [ "get", "post" ], function( i, method ) {
dataType: type dataType: type
}); });
}; };
}); } );
jQuery.extend({ jQuery.extend({
@ -389,7 +393,6 @@ jQuery.extend({
ifModifiedKey, ifModifiedKey,
// Headers (they are sent all at once) // Headers (they are sent all at once)
requestHeaders = {}, requestHeaders = {},
requestHeadersNames = {},
// Response headers // Response headers
responseHeadersString, responseHeadersString,
responseHeaders, responseHeaders,
@ -413,9 +416,7 @@ jQuery.extend({
// Caches the header // Caches the header
setRequestHeader: function( name, value ) { setRequestHeader: function( name, value ) {
if ( !state ) { if ( !state ) {
var lname = name.toLowerCase(); requestHeaders[ name.toLowerCase().replace( rucHeaders, rucHeadersFunc ) ] = value;
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
} }
return this; return this;
}, },
@ -644,8 +645,6 @@ jQuery.extend({
// If data is available, append data to url // If data is available, append data to url
if ( s.data ) { if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
} }
// Get ifModifiedKey before adding the anti-cache parameter // Get ifModifiedKey before adding the anti-cache parameter
@ -665,27 +664,24 @@ jQuery.extend({
// Set the correct header, if data is being sent // Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType ); requestHeaders[ "Content-Type" ] = s.contentType;
} }
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) { if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url; ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) { if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); requestHeaders[ "If-Modified-Since" ] = jQuery.lastModified[ ifModifiedKey ];
} }
if ( jQuery.etag[ ifModifiedKey ] ) { if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); requestHeaders[ "If-None-Match" ] = jQuery.etag[ ifModifiedKey ];
} }
} }
// Set the Accepts header for the server, depending on the dataType // Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader( requestHeaders.Accept = s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) : s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
s.accepts[ "*" ] s.accepts[ "*" ];
);
// Check for headers option // Check for headers option
for ( i in s.headers ) { for ( i in s.headers ) {
@ -729,7 +725,7 @@ jQuery.extend({
transport.send( requestHeaders, done ); transport.send( requestHeaders, done );
} catch (e) { } catch (e) {
// Propagate exception as error if not done // Propagate exception as error if not done
if ( state < 2 ) { if ( status < 2 ) {
done( -1, e ); done( -1, e );
// Simply rethrow otherwise // Simply rethrow otherwise
} else { } else {
@ -761,7 +757,7 @@ jQuery.extend({
// Serialize the form elements // Serialize the form elements
jQuery.each( a, function() { jQuery.each( a, function() {
add( this.name, this.value ); add( this.name, this.value );
}); } );
} else { } else {
// If traditional, encode the "old" way (the way 1.3.2 or older // If traditional, encode the "old" way (the way 1.3.2 or older
@ -777,7 +773,7 @@ jQuery.extend({
}); });
function buildParams( prefix, obj, traditional, add ) { function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray( obj ) ) { if ( jQuery.isArray( obj ) && obj.length ) {
// Serialize array item. // Serialize array item.
jQuery.each( obj, function( i, v ) { jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) { if ( traditional || rbracket.test( prefix ) ) {
@ -797,10 +793,17 @@ function buildParams( prefix, obj, traditional, add ) {
}); });
} else if ( !traditional && obj != null && typeof obj === "object" ) { } else if ( !traditional && obj != null && typeof obj === "object" ) {
// If we see an array here, it is empty and should be treated as an empty
// object
if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
add( prefix, "" );
// Serialize object item. // Serialize object item.
} else {
for ( var name in obj ) { for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
} }
}
} else { } else {
// Serialize scalar item. // Serialize scalar item.

View file

@ -14,12 +14,13 @@ jQuery.ajaxSetup({
// Detect, normalize options and install callbacks for jsonp requests // Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var inspectData = s.contentType === "application/x-www-form-urlencoded" && var dataIsString = ( typeof s.data === "string" );
( typeof s.data === "string" );
if ( s.dataTypes[ 0 ] === "jsonp" || if ( s.dataTypes[ 0 ] === "jsonp" ||
originalSettings.jsonpCallback ||
originalSettings.jsonp != null ||
s.jsonp !== false && ( jsre.test( s.url ) || s.jsonp !== false && ( jsre.test( s.url ) ||
inspectData && jsre.test( s.data ) ) ) { dataIsString && jsre.test( s.data ) ) ) {
var responseContainer, var responseContainer,
jsonpCallback = s.jsonpCallback = jsonpCallback = s.jsonpCallback =
@ -27,12 +28,20 @@ jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
previous = window[ jsonpCallback ], previous = window[ jsonpCallback ],
url = s.url, url = s.url,
data = s.data, data = s.data,
replace = "$1" + jsonpCallback + "$2"; replace = "$1" + jsonpCallback + "$2",
cleanUp = function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
};
if ( s.jsonp !== false ) { if ( s.jsonp !== false ) {
url = url.replace( jsre, replace ); url = url.replace( jsre, replace );
if ( s.url === url ) { if ( s.url === url ) {
if ( inspectData ) { if ( dataIsString ) {
data = data.replace( jsre, replace ); data = data.replace( jsre, replace );
} }
if ( s.data === data ) { if ( s.data === data ) {
@ -50,15 +59,8 @@ jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
responseContainer = [ response ]; responseContainer = [ response ];
}; };
// Clean-up function // Install cleanUp function
jqXHR.always(function() { jqXHR.then( cleanUp, cleanUp );
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
});
// Use data converter to retrieve json after script execution // Use data converter to retrieve json after script execution
s.converters["script json"] = function() { s.converters["script json"] = function() {
@ -74,6 +76,6 @@ jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
// Delegate to script // Delegate to script
return "script"; return "script";
} }
}); } );
})( jQuery ); })( jQuery );

View file

@ -25,7 +25,7 @@ jQuery.ajaxPrefilter( "script", function( s ) {
s.type = "GET"; s.type = "GET";
s.global = false; s.global = false;
} }
}); } );
// Bind script tag hack transport // Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) { jQuery.ajaxTransport( "script", function(s) {
@ -53,7 +53,7 @@ jQuery.ajaxTransport( "script", function(s) {
// Attach handlers for all browsers // Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) { script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { if ( !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE // Handle memory leak in IE
script.onload = script.onreadystatechange = null; script.onload = script.onreadystatechange = null;
@ -84,6 +84,6 @@ jQuery.ajaxTransport( "script", function(s) {
} }
}; };
} }
}); } );
})( jQuery ); })( jQuery );

View file

@ -1,14 +1,21 @@
(function( jQuery ) { (function( jQuery ) {
var // #5280: Internet Explorer will keep connections alive if we don't abort on unload var // #5280: next active xhr id and list of active xhrs' callbacks
xhrOnUnloadAbort = window.ActiveXObject ? function() { xhrId = jQuery.now(),
xhrCallbacks,
// XHR used to determine supports properties
testXHR;
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
function xhrOnUnloadAbort() {
jQuery( window ).unload(function() {
// Abort all pending requests // Abort all pending requests
for ( var key in xhrCallbacks ) { for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 ); xhrCallbacks[ key ]( 0, 1 );
} }
} : false, });
xhrId = 0, }
xhrCallbacks;
// Functions to create xhrs // Functions to create xhrs
function createStandardXHR() { function createStandardXHR() {
@ -38,13 +45,15 @@ jQuery.ajaxSettings.xhr = window.ActiveXObject ?
// For all other browsers, use the standard XMLHttpRequest object // For all other browsers, use the standard XMLHttpRequest object
createStandardXHR; createStandardXHR;
// Determine support properties // Test if we can create an xhr object
(function( xhr ) { testXHR = jQuery.ajaxSettings.xhr();
jQuery.extend( jQuery.support, { jQuery.support.ajax = !!testXHR;
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr ) // Does this browser support crossDomain XHR requests
}); jQuery.support.cors = testXHR && ( "withCredentials" in testXHR );
})( jQuery.ajaxSettings.xhr() );
// No need for the temporary xhr anymore
testXHR = undefined;
// Create transport if the browser can provide an xhr // Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) { if ( jQuery.support.ajax ) {
@ -127,10 +136,8 @@ if ( jQuery.support.ajax ) {
// Do not keep as active anymore // Do not keep as active anymore
if ( handle ) { if ( handle ) {
xhr.onreadystatechange = jQuery.noop; xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ]; delete xhrCallbacks[ handle ];
} }
}
// If it's an abort // If it's an abort
if ( isAbort ) { if ( isAbort ) {
@ -190,18 +197,15 @@ if ( jQuery.support.ajax ) {
if ( !s.async || xhr.readyState === 4 ) { if ( !s.async || xhr.readyState === 4 ) {
callback(); callback();
} else { } else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed // Create the active xhrs callbacks list if needed
// and attach the unload handler // and attach the unload handler
if ( !xhrCallbacks ) { if ( !xhrCallbacks ) {
xhrCallbacks = {}; xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort ); xhrOnUnloadAbort();
} }
// Add to list of active xhrs callbacks // Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback; handle = xhrId++;
} xhr.onreadystatechange = xhrCallbacks[ handle ] = callback;
xhr.onreadystatechange = callback;
} }
}, },

View file

@ -1,67 +1,66 @@
(function( jQuery ) { (function( jQuery ) {
var rclass = /[\n\t\r]/g, var rclass = /[\n\t\r]/g,
rspace = /\s+/, rspaces = /\s+/,
rreturn = /\r/g, rreturn = /\r/g,
rspecialurl = /^(?:href|src|style)$/,
rtype = /^(?:button|input)$/i, rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i, rclickable = /^a(?:rea)?$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, rradiocheck = /^(?:radio|checkbox)$/i;
rinvalidChar = /\:|^on/,
formHook, boolHook; jQuery.props = {
"for": "htmlFor",
"class": "className",
readonly: "readOnly",
maxlength: "maxLength",
cellspacing: "cellSpacing",
rowspan: "rowSpan",
colspan: "colSpan",
tabindex: "tabIndex",
usemap: "useMap",
frameborder: "frameBorder"
};
jQuery.fn.extend({ jQuery.fn.extend({
attr: function( name, value ) { attr: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.attr ); return jQuery.access( this, name, value, true, jQuery.attr );
}, },
removeAttr: function( name ) { removeAttr: function( name, fn ) {
return this.each(function() { return this.each(function(){
jQuery.removeAttr( this, name ); jQuery.attr( this, name, "" );
}); if ( this.nodeType === 1 ) {
}, this.removeAttribute( name );
}
prop: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.prop );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
}); });
}, },
addClass: function( value ) { addClass: function( value ) {
var classNames, i, l, elem, if ( jQuery.isFunction(value) ) {
setClass, c, cl; return this.each(function(i) {
var self = jQuery(this);
if ( jQuery.isFunction( value ) ) { self.addClass( value.call(this, i, self.attr("class")) );
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
}); });
} }
if ( value && typeof value === "string" ) { if ( value && typeof value === "string" ) {
classNames = value.split( rspace ); var classNames = (value || "").split( rspaces );
for ( i = 0, l = this.length; i < l; i++ ) { for ( var i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ]; var elem = this[i];
if ( elem.nodeType === 1 ) { if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) { if ( !elem.className ) {
elem.className = value; elem.className = value;
} else { } else {
setClass = " " + elem.className + " "; var className = " " + elem.className + " ",
setClass = elem.className;
for ( c = 0, cl = classNames.length; c < cl; c++ ) { for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
setClass += classNames[ c ] + " "; setClass += " " + classNames[c];
} }
} }
elem.className = jQuery.trim( setClass ); elem.className = jQuery.trim( setClass );
@ -74,25 +73,24 @@ jQuery.fn.extend({
}, },
removeClass: function( value ) { removeClass: function( value ) {
var classNames, i, l, elem, className, c, cl; if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
if ( jQuery.isFunction( value ) ) { var self = jQuery(this);
return this.each(function( j ) { self.removeClass( value.call(this, i, self.attr("class")) );
jQuery( this ).removeClass( value.call(this, j, this.className) );
}); });
} }
if ( (value && typeof value === "string") || value === undefined ) { if ( (value && typeof value === "string") || value === undefined ) {
classNames = (value || "").split( rspace ); var classNames = (value || "").split( rspaces );
for ( i = 0, l = this.length; i < l; i++ ) { for ( var i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ]; var elem = this[i];
if ( elem.nodeType === 1 && elem.className ) { if ( elem.nodeType === 1 && elem.className ) {
if ( value ) { if ( value ) {
className = (" " + elem.className + " ").replace( rclass, " " ); var className = (" " + elem.className + " ").replace(rclass, " ");
for ( c = 0, cl = classNames.length; c < cl; c++ ) { for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[ c ] + " ", " "); className = className.replace(" " + classNames[c] + " ", " ");
} }
elem.className = jQuery.trim( className ); elem.className = jQuery.trim( className );
@ -111,8 +109,9 @@ jQuery.fn.extend({
isBool = typeof stateVal === "boolean"; isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) { if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) { return this.each(function(i) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); var self = jQuery(this);
self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal );
}); });
} }
@ -123,7 +122,7 @@ jQuery.fn.extend({
i = 0, i = 0,
self = jQuery( this ), self = jQuery( this ),
state = stateVal, state = stateVal,
classNames = value.split( rspace ); classNames = value.split( rspaces );
while ( (className = classNames[ i++ ]) ) { while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list // check each className given, space seperated list
@ -155,79 +154,20 @@ jQuery.fn.extend({
}, },
val: function( value ) { val: function( value ) {
var hooks, ret,
elem = this[0];
if ( !arguments.length ) { if ( !arguments.length ) {
var elem = this[0];
if ( elem ) { if ( elem ) {
hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; if ( jQuery.nodeName( elem, "option" ) ) {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return undefined;
}
var isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var self = jQuery(this), val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but // attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932 // uses .value. See #6932
var val = elem.attributes.value; var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text; return !val || val.specified ? elem.value : elem.text;
} }
},
select: { // We need to handle select boxes special
get: function( elem ) { if ( jQuery.nodeName( elem, "select" ) ) {
var value, var index = elem.selectedIndex,
index = elem.selectedIndex,
values = [], values = [],
options = elem.options, options = elem.options,
one = elem.type === "select-one"; one = elem.type === "select-one";
@ -246,7 +186,7 @@ jQuery.extend({
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option // Get the specific value for the option
value = jQuery( option ).val(); value = jQuery(option).val();
// We don't need an array for one selects // We don't need an array for one selects
if ( one ) { if ( one ) {
@ -264,23 +204,67 @@ jQuery.extend({
} }
return values; return values;
}, }
set: function( elem, value ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
var values = jQuery.makeArray( value ); if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) {
return elem.getAttribute("value") === null ? "on" : elem.value;
}
jQuery(elem).find("option").each(function() { // Everything else, we just grab the value
return (elem.value || "").replace(rreturn, "");
}
return undefined;
}
var isFunction = jQuery.isFunction(value);
return this.each(function(i) {
var self = jQuery(this), val = value;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call(this, i, self.val());
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray(val) ) {
val = jQuery.map(val, function (value) {
return value == null ? "" : value + "";
});
}
if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) {
this.checked = jQuery.inArray( self.val(), val ) >= 0;
} else if ( jQuery.nodeName( this, "select" ) ) {
var values = jQuery.makeArray(val);
jQuery( "option", this ).each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
}); });
if ( !values.length ) { if ( !values.length ) {
elem.selectedIndex = -1; this.selectedIndex = -1;
} }
return values;
}
}
},
} else {
this.value = val;
}
});
}
});
jQuery.extend({
attrFn: { attrFn: {
val: true, val: true,
css: true, css: true,
@ -292,308 +276,32 @@ jQuery.extend({
offset: true offset: true
}, },
attrFix: {
// Always normalize to ensure hook usage
tabindex: "tabIndex"
},
attr: function( elem, name, value, pass ) { attr: function( elem, name, value, pass ) {
var nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes // don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || elem.nodeType === 2 ) {
return undefined; return undefined;
} }
if ( pass && name in jQuery.attrFn ) { if ( pass && name in jQuery.attrFn ) {
return jQuery( elem )[ name ]( value ); return jQuery(elem)[name](value);
} }
// Fallback to prop when attributes are not supported var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ),
if ( !("getAttribute" in elem) ) { // Whether we are setting (or getting)
return jQuery.prop( elem, name, value ); set = value !== undefined;
}
var ret, hooks, // Try to normalize/fix the name
notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); name = notxml && jQuery.props[ name ] || name;
// Normalize the name if needed // Only do all the following if this is a node (faster for style)
if ( notxml ) {
name = jQuery.attrFix[ name ] || name;
hooks = jQuery.attrHooks[ name ];
if ( !hooks ) {
// Use boolHook for boolean attributes
if ( rboolean.test( name ) ) {
hooks = boolHook;
// Use formHook for forms and if the name contains certain characters
} else if ( formHook && name !== "className" &&
(jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ) {
hooks = formHook;
}
}
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return undefined;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, "" + value );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, name ) {
var propName;
if ( elem.nodeType === 1 ) { if ( elem.nodeType === 1 ) {
name = jQuery.attrFix[ name ] || name; // These attributes require special treatment
var special = rspecialurl.test( name );
if ( jQuery.support.getSetAttribute ) { // Safari mis-reports the default selected property of an option
// Use removeAttribute in browsers that support it // Accessing the parent's selectedIndex property fixes it
elem.removeAttribute( name ); if ( name === "selected" && !jQuery.support.optSelected ) {
} else {
jQuery.attr( elem, name, "" );
elem.removeAttributeNode( elem.getAttributeNode( name ) );
}
// Set corresponding property to false for boolean attributes
if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) {
elem[ propName ] = false;
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabIndex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
},
// Use the value property for back compat
// Use the formHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( formHook && jQuery.nodeName( elem, "button" ) ) {
return formHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( formHook && jQuery.nodeName( elem, "button" ) ) {
return formHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return undefined;
}
var ret, hooks,
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return (elem[ name ] = value);
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== undefined ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
return jQuery.prop( elem, name ) ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !jQuery.support.getSetAttribute ) {
// propFix is more comprehensive and contains all fixes
jQuery.attrFix = jQuery.propFix;
// Use this for any attribute on a form in IE6/7
formHook = jQuery.attrHooks.name = jQuery.attrHooks.title = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
// Return undefined if nodeValue is empty string
return ret && ret.nodeValue !== "" ?
ret.nodeValue :
undefined;
},
set: function( elem, value, name ) {
// Check form objects in IE (multiple bugs related)
// Only use nodeValue if the attribute node exists on the form
var ret = elem.getAttributeNode( name );
if ( ret ) {
ret.nodeValue = value;
return value;
}
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return (elem.style.cssText = "" + value);
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode; var parent = elem.parentNode;
if ( parent ) { if ( parent ) {
parent.selectedIndex; parent.selectedIndex;
@ -603,28 +311,79 @@ if ( !jQuery.support.optSelected ) {
} }
} }
} }
});
}
// Radios and checkboxes getter/setter // If applicable, access the attribute via the DOM 0 way
if ( !jQuery.support.checkOn ) { // 'in' checks fail in Blackberry 4.7 #6931
jQuery.each([ "radio", "checkbox" ], function() { if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) {
jQuery.valHooks[ this ] = { if ( set ) {
get: function( elem ) { // We can't allow the type property to be changed (since it causes problems in IE)
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) {
return elem.getAttribute("value") === null ? "on" : elem.value; jQuery.error( "type property can't be changed" );
} }
};
}); if ( value === null ) {
} if ( elem.nodeType === 1 ) {
jQuery.each([ "radio", "checkbox" ], function() { elem.removeAttribute( name );
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { }
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) { } else {
return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0); elem[ name ] = value;
} }
} }
});
// browsers index elements by id/name on forms, give priority to attributes.
if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) {
return elem.getAttributeNode( name ).nodeValue;
}
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
if ( name === "tabIndex" ) {
var attributeNode = elem.getAttributeNode( "tabIndex" );
return attributeNode && attributeNode.specified ?
attributeNode.value :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
return elem[ name ];
}
if ( !jQuery.support.style && notxml && name === "style" ) {
if ( set ) {
elem.style.cssText = "" + value;
}
return elem.style.cssText;
}
if ( set ) {
// convert the value to a string (all browsers do this but IE) see #1070
elem.setAttribute( name, "" + value );
}
// Ensure that missing attributes return undefined
// Blackberry 4.7 returns "" from getAttribute #6938
if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) {
return undefined;
}
var attr = !jQuery.support.hrefNormalized && notxml && special ?
// Some attributes require a special call on IE
elem.getAttribute( name, 2 ) :
elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return attr === null ? undefined : attr;
}
// Handle everything which isn't a DOM element node
if ( set ) {
elem[ name ] = value;
}
return elem[ name ];
}
}); });
})( jQuery ); })( jQuery );

View file

@ -17,7 +17,7 @@ var jQuery = function( selector, context ) {
// A simple way to check for HTML strings or ID strings // A simple way to check for HTML strings or ID strings
// (both of which we optimize for) // (both of which we optimize for)
quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,
// Check if a string has a non-whitespace character in it // Check if a string has a non-whitespace character in it
rnotwhite = /\S/, rnotwhite = /\S/,
@ -44,14 +44,6 @@ var jQuery = function( selector, context ) {
rmsie = /(msie) ([\w.]+)/, rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Matches dashed string for camelizing
rdashAlpha = /-([a-z])/ig,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// Keep a UserAgent string for use with jQuery.browser // Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent, userAgent = navigator.userAgent,
@ -96,7 +88,7 @@ jQuery.fn = jQuery.prototype = {
if ( selector === "body" && !context && document.body ) { if ( selector === "body" && !context && document.body ) {
this.context = document; this.context = document;
this[0] = document.body; this[0] = document.body;
this.selector = selector; this.selector = "body";
this.length = 1; this.length = 1;
return this; return this;
} }
@ -104,13 +96,7 @@ jQuery.fn = jQuery.prototype = {
// Handle HTML strings // Handle HTML strings
if ( typeof selector === "string" ) { if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID? // Are we dealing with HTML string or an ID?
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = quickExpr.exec( selector ); match = quickExpr.exec( selector );
}
// Verify a match, and that no context was specified for #id // Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) { if ( match && (match[1] || !context) ) {
@ -367,11 +353,9 @@ jQuery.extend = jQuery.fn.extend = function() {
jQuery.extend({ jQuery.extend({
noConflict: function( deep ) { noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$; window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) { if ( deep ) {
window.jQuery = _jQuery; window.jQuery = _jQuery;
} }
@ -385,19 +369,15 @@ jQuery.extend({
// the ready event fires. See #6781 // the ready event fires. See #6781
readyWait: 1, readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready // Handle when the DOM is ready
ready: function( wait ) { ready: function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready // A third-party is pushing the ready event forwards
if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { if ( wait === true ) {
jQuery.readyWait--;
}
// Make sure that the DOM is not already loaded
if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) { if ( !document.body ) {
return setTimeout( jQuery.ready, 1 ); return setTimeout( jQuery.ready, 1 );
@ -447,7 +427,7 @@ jQuery.extend({
} else if ( document.attachEvent ) { } else if ( document.attachEvent ) {
// ensure firing before onload, // ensure firing before onload,
// maybe late but safe also for iframes // maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded ); document.attachEvent("onreadystatechange", DOMContentLoaded);
// A fallback to window.onload, that will always work // A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready ); window.attachEvent( "onload", jQuery.ready );
@ -535,21 +515,20 @@ jQuery.extend({
// Make sure leading/trailing whitespace is removed (IE can't handle it) // Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data ); data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON // Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js // Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" ) if ( rvalidchars.test(data.replace(rvalidescape, "@")
.replace( rvalidtokens, "]" ) .replace(rvalidtokens, "]")
.replace( rvalidbraces, "")) ) { .replace(rvalidbraces, "")) ) {
return (new Function( "return " + data ))(); // Try to use the native JSON parser first
return window.JSON && window.JSON.parse ?
window.JSON.parse( data ) :
(new Function("return " + data))();
} } else {
jQuery.error( "Invalid JSON: " + data ); jQuery.error( "Invalid JSON: " + data );
}
}, },
// Cross-browser xml parsing // Cross-browser xml parsing
@ -576,24 +555,25 @@ jQuery.extend({
noop: function() {}, noop: function() {},
// Evaluates a script in a global context // Evalulates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) { globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) { if ( data && rnotwhite.test(data) ) {
// We use execScript on Internet Explorer // Inspired by code by Andrea Giammarchi
// We use an anonymous function so that context is window // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
// rather than jQuery in Firefox var head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement,
( window.execScript || function( data ) { script = document.createElement( "script" );
window[ "eval" ].call( window, data );
} )( data );
}
},
// Converts a dashed string to camelCased string; if ( jQuery.support.scriptEval() ) {
// Used by both the css and data modules script.appendChild( document.createTextNode( data ) );
camelCase: function( string ) { } else {
return string.replace( rdashAlpha, fcamelCase ); script.text = data;
}
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709).
head.insertBefore( script, head.firstChild );
head.removeChild( script );
}
}, },
nodeName: function( elem, name ) { nodeName: function( elem, name ) {
@ -604,7 +584,7 @@ jQuery.extend({
each: function( object, callback, args ) { each: function( object, callback, args ) {
var name, i = 0, var name, i = 0,
length = object.length, length = object.length,
isObj = length === undefined || jQuery.isFunction( object ); isObj = length === undefined || jQuery.isFunction(object);
if ( args ) { if ( args ) {
if ( isObj ) { if ( isObj ) {
@ -630,11 +610,8 @@ jQuery.extend({
} }
} }
} else { } else {
for ( ; i < length; ) { for ( var value = object[0];
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
break;
}
}
} }
} }
@ -665,7 +642,7 @@ jQuery.extend({
// The extra typeof function check is to prevent crashes // The extra typeof function check is to prevent crashes
// in Safari 2 (See: #3039) // in Safari 2 (See: #3039)
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type( array ); var type = jQuery.type(array);
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array ); push.call( ret, array );
@ -678,9 +655,8 @@ jQuery.extend({
}, },
inArray: function( elem, array ) { inArray: function( elem, array ) {
if ( array.indexOf ) {
if ( indexOf ) { return array.indexOf( elem );
return indexOf.call( array, elem );
} }
for ( var i = 0, length = array.length; i < length; i++ ) { for ( var i = 0, length = array.length; i < length; i++ ) {
@ -730,15 +706,11 @@ jQuery.extend({
// arg is for internal usage only // arg is for internal usage only
map: function( elems, callback, arg ) { map: function( elems, callback, arg ) {
var value, key, ret = [], var ret = [], value;
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their // Go through the array, translating each of the items to their
if ( isArray ) { // new value (or values).
for ( ; i < length; i++ ) { for ( var i = 0, length = elems.length; i < length; i++ ) {
value = callback( elems[ i ], i, arg ); value = callback( elems[ i ], i, arg );
if ( value != null ) { if ( value != null ) {
@ -746,17 +718,6 @@ jQuery.extend({
} }
} }
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays // Flatten any nested arrays
return ret.concat.apply( [], ret ); return ret.concat.apply( [], ret );
}, },
@ -764,35 +725,36 @@ jQuery.extend({
// A global GUID counter for objects // A global GUID counter for objects
guid: 1, guid: 1,
// Bind a function to a context, optionally partially applying any proxy: function( fn, proxy, thisObject ) {
// arguments. if ( arguments.length === 2 ) {
proxy: function( fn, context ) { if ( typeof proxy === "string" ) {
if ( typeof context === "string" ) { thisObject = fn;
var tmp = fn[ context ]; fn = thisObject[ proxy ];
context = fn; proxy = undefined;
fn = tmp;
} else if ( proxy && !jQuery.isFunction( proxy ) ) {
thisObject = proxy;
proxy = undefined;
}
} }
// Quick check to determine if target is callable, in the spec if ( !proxy && fn ) {
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
var args = slice.call( arguments, 2 ),
proxy = function() { proxy = function() {
return fn.apply( context, args.concat( slice.call( arguments ) ) ); return fn.apply( thisObject || this, arguments );
}; };
}
// Set the guid of unique handler to the same of original handler, so it can be removed // Set the guid of unique handler to the same of original handler, so it can be removed
if ( fn ) {
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
}
// So proxy can be declared as an argument
return proxy; return proxy;
}, },
// Mutifunctional method to get and set values to a collection // Mutifunctional method to get and set values to a collection
// The value/s can optionally be executed if it's a function // The value/s can be optionally by executed if its a function
access: function( elems, key, value, exec, fn, pass ) { access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length; var length = elems.length;
@ -839,24 +801,24 @@ jQuery.extend({
}, },
sub: function() { sub: function() {
function jQuerySub( selector, context ) { function jQuerySubclass( selector, context ) {
return new jQuerySub.fn.init( selector, context ); return new jQuerySubclass.fn.init( selector, context );
} }
jQuery.extend( true, jQuerySub, this ); jQuery.extend( true, jQuerySubclass, this );
jQuerySub.superclass = this; jQuerySubclass.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this(); jQuerySubclass.fn = jQuerySubclass.prototype = this();
jQuerySub.fn.constructor = jQuerySub; jQuerySubclass.fn.constructor = jQuerySubclass;
jQuerySub.sub = this.sub; jQuerySubclass.subclass = this.subclass;
jQuerySub.fn.init = function init( selector, context ) { jQuerySubclass.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySubclass) ) {
context = jQuerySub( context ); context = jQuerySubclass(context);
} }
return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); return jQuery.fn.init.call( this, selector, context, rootjQuerySubclass );
}; };
jQuerySub.fn.init.prototype = jQuerySub.fn; jQuerySubclass.fn.init.prototype = jQuerySubclass.fn;
var rootjQuerySub = jQuerySub(document); var rootjQuerySubclass = jQuerySubclass(document);
return jQuerySub; return jQuerySubclass;
}, },
browser: {} browser: {}
@ -878,6 +840,12 @@ if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true; jQuery.browser.safari = true;
} }
if ( indexOf ) {
jQuery.inArray = function( elem, array ) {
return indexOf.call( array, elem );
};
}
// IE doesn't match non-breaking spaces with \s // IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) { if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/; trimLeft = /^[\s\xA0]+/;
@ -923,6 +891,7 @@ function doScrollCheck() {
jQuery.ready(); jQuery.ready();
} }
// Expose jQuery to the global object
return jQuery; return jQuery;
})(); })();

View file

@ -2,12 +2,11 @@
var ralpha = /alpha\([^)]*\)/i, var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/, ropacity = /opacity=([^)]*)/,
rdashAlpha = /-([a-z])/ig,
// fixed for IE9, see #8346 // fixed for IE9, see #8346
rupper = /([A-Z]|^ms)/g, rupper = /([A-Z]|^ms)/g,
rnumpx = /^-?\d+(?:px)?$/i, rnumpx = /^-?\d+(?:px)?$/i,
rnum = /^-?\d/, rnum = /^-?\d/,
rrelNum = /^[+\-]=/,
rrelNumFilter = /[^+\-\.\de]+/g,
cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssWidth = [ "Left", "Right" ], cssWidth = [ "Left", "Right" ],
@ -15,7 +14,11 @@ var ralpha = /alpha\([^)]*\)/i,
curCSS, curCSS,
getComputedStyle, getComputedStyle,
currentStyle; currentStyle,
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn.css = function( name, value ) { jQuery.fn.css = function( name, value ) {
// Setting 'undefined' is a no-op // Setting 'undefined' is a no-op
@ -50,14 +53,11 @@ jQuery.extend({
// Exclude the following css properties to add px // Exclude the following css properties to add px
cssNumber: { cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true, "zIndex": true,
"zoom": true "fontWeight": true,
"opacity": true,
"zoom": true,
"lineHeight": true
}, },
// Add in properties whose names you wish to fix before // Add in properties whose names you wish to fix before
@ -75,29 +75,20 @@ jQuery.extend({
} }
// Make sure that we're working with the right name // Make sure that we're working with the right name
var ret, type, origName = jQuery.camelCase( name ), var ret, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ]; style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName; name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value // Check if we're setting a value
if ( value !== undefined ) { if ( value !== undefined ) {
type = typeof value;
// Make sure that NaN and null values aren't set. See: #7116 // Make sure that NaN and null values aren't set. See: #7116
if ( type === "number" && isNaN( value ) || value == null ) { if ( typeof value === "number" && isNaN( value ) || value == null ) {
return; return;
} }
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && rrelNum.test( value ) ) {
value = +value.replace( rrelNumFilter, "" ) + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// If a number was passed in, add 'px' to the (except for certain CSS properties) // If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) { if ( typeof value === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px"; value += "px";
} }
@ -122,17 +113,11 @@ jQuery.extend({
}, },
css: function( elem, name, extra ) { css: function( elem, name, extra ) {
var ret, hooks;
// Make sure that we're working with the right name // Make sure that we're working with the right name
name = jQuery.camelCase( name ); var ret, origName = jQuery.camelCase( name ),
hooks = jQuery.cssHooks[ name ]; hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ name ] || name;
// cssFloat needs a special treatment name = jQuery.cssProps[ origName ] || origName;
if ( name === "cssFloat" ) {
name = "float";
}
// If a hook was provided get the computed value from there // If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
@ -140,7 +125,7 @@ jQuery.extend({
// Otherwise, if a way to get the computed value exists, use that // Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) { } else if ( curCSS ) {
return curCSS( elem, name ); return curCSS( elem, name, origName );
} }
}, },
@ -160,6 +145,10 @@ jQuery.extend({
for ( name in options ) { for ( name in options ) {
elem.style[ name ] = old[ name ]; elem.style[ name ] = old[ name ];
} }
},
camelCase: function( string ) {
return string.replace( rdashAlpha, fcamelCase );
} }
}); });
@ -173,21 +162,44 @@ jQuery.each(["height", "width"], function( i, name ) {
if ( computed ) { if ( computed ) {
if ( elem.offsetWidth !== 0 ) { if ( elem.offsetWidth !== 0 ) {
return getWH( elem, name, extra ); val = getWH( elem, name, extra );
} else { } else {
jQuery.swap( elem, cssShow, function() { jQuery.swap( elem, cssShow, function() {
val = getWH( elem, name, extra ); val = getWH( elem, name, extra );
}); });
} }
return val; if ( val <= 0 ) {
val = curCSS( elem, name, name );
if ( val === "0px" && currentStyle ) {
val = currentStyle( elem, name, name );
}
if ( val != null ) {
// Should return "auto" instead of 0, use 0 for
// temporary backwards-compat
return val === "" || val === "auto" ? "0px" : val;
}
}
if ( val < 0 || val == null ) {
val = elem.style[ name ];
// Should return "auto" instead of 0, use 0 for
// temporary backwards-compat
return val === "" || val === "auto" ? "0px" : val;
}
return typeof val === "string" ? val : val + "px";
} }
}, },
set: function( elem, value ) { set: function( elem, value ) {
if ( rnumpx.test( value ) ) { if ( rnumpx.test( value ) ) {
// ignore negative width and height values #1599 // ignore negative width and height values #1599
value = parseFloat( value ); value = parseFloat(value);
if ( value >= 0 ) { if ( value >= 0 ) {
return value + "px"; return value + "px";
@ -204,28 +216,27 @@ if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = { jQuery.cssHooks.opacity = {
get: function( elem, computed ) { get: function( elem, computed ) {
// IE uses filters for opacity // IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ?
( parseFloat( RegExp.$1 ) / 100 ) + "" : (parseFloat(RegExp.$1) / 100) + "" :
computed ? "1" : ""; computed ? "1" : "";
}, },
set: function( elem, value ) { set: function( elem, value ) {
var style = elem.style, var style = elem.style;
currentStyle = elem.currentStyle;
// IE has trouble with opacity if it does not have layout // IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level // Force it by setting the zoom level
style.zoom = 1; style.zoom = 1;
// Set the alpha filter to set the opacity // Set the alpha filter to set the opacity
var opacity = jQuery.isNaN( value ) ? var opacity = jQuery.isNaN(value) ?
"" : "" :
"alpha(opacity=" + value * 100 + ")", "alpha(opacity=" + value * 100 + ")",
filter = currentStyle && currentStyle.filter || style.filter || ""; filter = style.filter || "";
style.filter = ralpha.test( filter ) ? style.filter = ralpha.test(filter) ?
filter.replace( ralpha, opacity ) : filter.replace(ralpha, opacity) :
filter + " " + opacity; style.filter + ' ' + opacity;
} }
}; };
} }
@ -253,7 +264,7 @@ jQuery(function() {
}); });
if ( document.defaultView && document.defaultView.getComputedStyle ) { if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, name ) { getComputedStyle = function( elem, newName, name ) {
var ret, defaultView, computedStyle; var ret, defaultView, computedStyle;
name = name.replace( rupper, "-$1" ).toLowerCase(); name = name.replace( rupper, "-$1" ).toLowerCase();
@ -310,50 +321,27 @@ if ( document.documentElement.currentStyle ) {
curCSS = getComputedStyle || currentStyle; curCSS = getComputedStyle || currentStyle;
function getWH( elem, name, extra ) { function getWH( elem, name, extra ) {
var which = name === "width" ? cssWidth : cssHeight,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight;
// Start with offset property if ( extra === "border" ) {
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, return val;
which = name === "width" ? cssWidth : cssHeight; }
if ( val > 0 ) {
if ( extra !== "border" ) {
jQuery.each( which, function() { jQuery.each( which, function() {
if ( !extra ) { if ( !extra ) {
val -= parseFloat( jQuery.css( elem, "padding" + this ) ) || 0; val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0;
} }
if ( extra === "margin" ) { if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + this ) ) || 0; val += parseFloat(jQuery.css( elem, "margin" + this )) || 0;
} else { } else {
val -= parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0; val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0;
} }
}); });
}
return val + "px"; return val;
}
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ] || 0;
}
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
// Add padding, border, margin
if ( extra ) {
jQuery.each( which, function() {
val += parseFloat( jQuery.css( elem, "padding" + this ) ) || 0;
if ( extra !== "padding" ) {
val += parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + this ) ) || 0;
}
});
}
return val + "px";
} }
if ( jQuery.expr && jQuery.expr.filters ) { if ( jQuery.expr && jQuery.expr.filters ) {

View file

@ -1,7 +1,6 @@
(function( jQuery ) { (function( jQuery ) {
var rbrace = /^(?:\{.*\}|\[.*\])$/, var rbrace = /^(?:\{.*\}|\[.*\])$/;
rmultiDash = /([a-z])([A-Z])/g;
jQuery.extend({ jQuery.extend({
cache: {}, cache: {},
@ -98,7 +97,7 @@ jQuery.extend({
} }
if ( data !== undefined ) { if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data; thisCache[ name ] = data;
} }
// TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
@ -108,10 +107,7 @@ jQuery.extend({
return thisCache[ internalKey ] && thisCache[ internalKey ].events; return thisCache[ internalKey ] && thisCache[ internalKey ].events;
} }
return getByName ? return getByName ? thisCache[ name ] : thisCache;
// Check for both converted-to-camel and non-converted data property names
thisCache[ jQuery.camelCase( name ) ] || thisCache[ name ] :
thisCache;
}, },
removeData: function( elem, name, pvt /* Internal Use Only */ ) { removeData: function( elem, name, pvt /* Internal Use Only */ ) {
@ -232,8 +228,7 @@ jQuery.fn.extend({
name = attr[i].name; name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) { if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.substring(5) ); name = name.substr( 5 );
dataAttr( this[0], name, data[ name ] ); dataAttr( this[0], name, data[ name ] );
} }
} }
@ -287,9 +282,7 @@ function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any // If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute // data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) { if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase(); data = elem.getAttribute( "data-" + key );
data = elem.getAttribute( name );
if ( typeof data === "string" ) { if ( typeof data === "string" ) {
try { try {

View file

@ -1,7 +1,7 @@
(function( jQuery ) { (function( jQuery ) {
var // Promise methods var // Promise methods
promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ), promiseMethods = "then done fail isResolved isRejected promise".split( " " ),
// Static reference to slice // Static reference to slice
sliceDeferred = [].slice; sliceDeferred = [].slice;
@ -100,37 +100,10 @@ jQuery.extend({
deferred.done( doneCallbacks ).fail( failCallbacks ); deferred.done( doneCallbacks ).fail( failCallbacks );
return this; return this;
}, },
always: function() {
return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments );
},
fail: failDeferred.done, fail: failDeferred.done,
rejectWith: failDeferred.resolveWith, rejectWith: failDeferred.resolveWith,
reject: failDeferred.resolve, reject: failDeferred.resolve,
isRejected: failDeferred.isResolved, isRejected: failDeferred.isResolved,
pipe: function( fnDone, fnFail ) {
return jQuery.Deferred(function( newDefer ) {
jQuery.each( {
done: [ fnDone, "resolve" ],
fail: [ fnFail, "reject" ]
}, function( handler, data ) {
var fn = data[ 0 ],
action = data[ 1 ],
returned;
if ( jQuery.isFunction( fn ) ) {
deferred[ handler ](function() {
returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise().then( newDefer.resolve, newDefer.reject );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
});
} else {
deferred[ handler ]( newDefer[ action ] );
}
});
}).promise();
},
// Get a promise for this deferred // Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object // If obj is provided, the promise aspect is added to the object
promise: function( obj ) { promise: function( obj ) {
@ -146,7 +119,7 @@ jQuery.extend({
} }
return obj; return obj;
} }
}); } );
// Make sure only one callback list will be used // Make sure only one callback list will be used
deferred.done( failDeferred.cancel ).fail( deferred.cancel ); deferred.done( failDeferred.cancel ).fail( deferred.cancel );
// Unexpose cancel // Unexpose cancel

View file

@ -1,23 +1,21 @@
(function( jQuery ) { (function( jQuery ) {
// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods // Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function( i, name ) { jQuery.each([ "Height", "Width" ], function( i, name ) {
var type = name.toLowerCase(); var type = name.toLowerCase();
// innerHeight and innerWidth // innerHeight and innerWidth
jQuery.fn[ "inner" + name ] = function() { jQuery.fn["inner" + name] = function() {
var elem = this[0]; return this[0] ?
return elem && elem.style ? parseFloat( jQuery.css( this[0], type, "padding" ) ) :
parseFloat( jQuery.css( elem, type, "padding" ) ) :
null; null;
}; };
// outerHeight and outerWidth // outerHeight and outerWidth
jQuery.fn[ "outer" + name ] = function( margin ) { jQuery.fn["outer" + name] = function( margin ) {
var elem = this[0]; return this[0] ?
return elem && elem.style ? parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) :
parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
null; null;
}; };

229
src/effects.js vendored
View file

@ -1,7 +1,6 @@
(function( jQuery ) { (function( jQuery ) {
var elemdisplay = {}, var elemdisplay = {},
iframe, iframeDoc,
rfxtypes = /^(?:toggle|show|hide)$/, rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId, timerId,
@ -12,11 +11,7 @@ var elemdisplay = {},
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations // opacity animations
[ "opacity" ] [ "opacity" ]
], ];
fxNow,
requestAnimationFrame = window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame;
jQuery.fn.extend({ jQuery.fn.extend({
show: function( speed, easing, callback ) { show: function( speed, easing, callback ) {
@ -28,8 +23,6 @@ jQuery.fn.extend({
} else { } else {
for ( var i = 0, j = this.length; i < j; i++ ) { for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[i]; elem = this[i];
if ( elem.style ) {
display = elem.style.display; display = elem.style.display;
// Reset the inline display of this element to learn if it is // Reset the inline display of this element to learn if it is
@ -45,21 +38,17 @@ jQuery.fn.extend({
jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName)); jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName));
} }
} }
}
// Set the display of most of the elements in a second loop // Set the display of most of the elements in a second loop
// to avoid the constant reflow // to avoid the constant reflow
for ( i = 0; i < j; i++ ) { for ( i = 0; i < j; i++ ) {
elem = this[i]; elem = this[i];
if ( elem.style ) {
display = elem.style.display; display = elem.style.display;
if ( display === "" || display === "none" ) { if ( display === "" || display === "none" ) {
elem.style.display = jQuery._data(elem, "olddisplay") || ""; elem.style.display = jQuery._data(elem, "olddisplay") || "";
} }
} }
}
return this; return this;
} }
@ -71,22 +60,18 @@ jQuery.fn.extend({
} else { } else {
for ( var i = 0, j = this.length; i < j; i++ ) { for ( var i = 0, j = this.length; i < j; i++ ) {
if ( this[i].style ) {
var display = jQuery.css( this[i], "display" ); var display = jQuery.css( this[i], "display" );
if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) { if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) {
jQuery._data( this[i], "olddisplay", display ); jQuery._data( this[i], "olddisplay", display );
} }
} }
}
// Set the display of the elements in a second loop // Set the display of the elements in a second loop
// to avoid the constant reflow // to avoid the constant reflow
for ( i = 0; i < j; i++ ) { for ( i = 0; i < j; i++ ) {
if ( this[i].style ) {
this[i].style.display = "none"; this[i].style.display = "none";
} }
}
return this; return this;
} }
@ -123,54 +108,32 @@ jQuery.fn.extend({
var optall = jQuery.speed(speed, easing, callback); var optall = jQuery.speed(speed, easing, callback);
if ( jQuery.isEmptyObject( prop ) ) { if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] ); return this.each( optall.complete );
} }
// Do not change referenced properties as per-property easing will be lost
prop = jQuery.extend( {}, prop );
return this[ optall.queue === false ? "each" : "queue" ](function() { return this[ optall.queue === false ? "each" : "queue" ](function() {
// XXX 'this' does not always have a nodeName when running the // XXX 'this' does not always have a nodeName when running the
// test suite // test suite
if ( optall.queue === false ) { var opt = jQuery.extend({}, optall), p,
jQuery._mark( this );
}
var opt = jQuery.extend( {}, optall ),
isElement = this.nodeType === 1, isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"), hidden = isElement && jQuery(this).is(":hidden"),
name, val, p, self = this;
display, e,
parts, start, end, unit;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
for ( p in prop ) { for ( p in prop ) {
var name = jQuery.camelCase( p );
// property name normalization
name = jQuery.camelCase( p );
if ( p !== name ) { if ( p !== name ) {
prop[ name ] = prop[ p ]; prop[ name ] = prop[ p ];
delete prop[ p ]; delete prop[ p ];
p = name;
} }
val = prop[ name ]; if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) {
return opt.complete.call(this);
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
} }
if ( val === "hide" && hidden || val === "show" && !hidden ) { if ( isElement && ( p === "height" || p === "width" ) ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out // Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not // Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and // change the overflow attribute when overflowX and
@ -186,7 +149,7 @@ jQuery.fn.extend({
this.style.display = "inline-block"; this.style.display = "inline-block";
} else { } else {
display = defaultDisplay( this.nodeName ); var display = defaultDisplay(this.nodeName);
// inline-level elements accept inline-block; // inline-level elements accept inline-block;
// block-level elements need to be inline with layout // block-level elements need to be inline with layout
@ -200,37 +163,44 @@ jQuery.fn.extend({
} }
} }
} }
if ( jQuery.isArray( prop[p] ) ) {
// Create (if needed) and add to specialEasing
(opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1];
prop[p] = prop[p][0];
}
} }
if ( opt.overflow != null ) { if ( opt.overflow != null ) {
this.style.overflow = "hidden"; this.style.overflow = "hidden";
} }
for ( p in prop ) { opt.curAnim = jQuery.extend({}, prop);
e = new jQuery.fx( this, opt, p );
val = prop[ p ]; jQuery.each( prop, function( name, val ) {
var e = new jQuery.fx( self, opt, name );
if ( rfxtypes.test(val) ) { if ( rfxtypes.test(val) ) {
e[ val === "toggle" ? hidden ? "show" : "hide" : val ](); e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop );
} else { } else {
parts = rfxnum.exec( val ); var parts = rfxnum.exec(val),
start = e.cur(); start = e.cur();
if ( parts ) { if ( parts ) {
end = parseFloat( parts[2] ); var end = parseFloat( parts[2] ),
unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); unit = parts[3] || ( jQuery.cssNumber[ name ] ? "" : "px" );
// We need to compute starting value // We need to compute starting value
if ( unit !== "px" ) { if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit); jQuery.style( self, name, (end || 1) + unit);
start = ((end || 1) / e.cur()) * start; start = ((end || 1) / e.cur()) * start;
jQuery.style( this, p, start + unit); jQuery.style( self, name, start + unit);
} }
// If a +=/-= token was provided, we're doing a relative animation // If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) { if ( parts[1] ) {
end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start; end = ((parts[1] === "-=" ? -1 : 1) * end) + start;
} }
e.custom( start, end, unit ); e.custom( start, end, unit );
@ -239,7 +209,7 @@ jQuery.fn.extend({
e.custom( start, val, "" ); e.custom( start, val, "" );
} }
} }
} });
// For JS strict compliance // For JS strict compliance
return true; return true;
@ -247,18 +217,15 @@ jQuery.fn.extend({
}, },
stop: function( clearQueue, gotoEnd ) { stop: function( clearQueue, gotoEnd ) {
var timers = jQuery.timers;
if ( clearQueue ) { if ( clearQueue ) {
this.queue([]); this.queue([]);
} }
this.each(function() { this.each(function() {
var timers = jQuery.timers, // go in reverse order so anything added to the queue during the loop is ignored
i = timers.length; for ( var i = timers.length - 1; i >= 0; i-- ) {
// clear marker counters if we know they won't be
if ( !gotoEnd ) {
jQuery._unmark( true, this );
}
while ( i-- ) {
if ( timers[i].elem === this ) { if ( timers[i].elem === this ) {
if (gotoEnd) { if (gotoEnd) {
// force the next step to be the last // force the next step to be the last
@ -280,17 +247,6 @@ jQuery.fn.extend({
}); });
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout( clearFxNow, 0 );
return ( fxNow = jQuery.now() );
}
function clearFxNow() {
fxNow = undefined;
}
// Generate parameters to create a standard animation
function genFx( type, num ) { function genFx( type, num ) {
var obj = {}; var obj = {};
@ -329,16 +285,13 @@ jQuery.extend({
// Queueing // Queueing
opt.old = opt.complete; opt.old = opt.complete;
opt.complete = function( noUnmark ) { opt.complete = function() {
if ( opt.queue !== false ) {
jQuery(this).dequeue();
}
if ( jQuery.isFunction( opt.old ) ) { if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this ); opt.old.call( this );
} }
if ( opt.queue !== false ) {
jQuery.dequeue( this );
} else if ( noUnmark !== false ) {
jQuery._unmark( this );
}
}; };
return opt; return opt;
@ -360,7 +313,9 @@ jQuery.extend({
this.elem = elem; this.elem = elem;
this.prop = prop; this.prop = prop;
options.orig = options.orig || {}; if ( !options.orig ) {
options.orig = {};
}
} }
}); });
@ -392,10 +347,9 @@ jQuery.fx.prototype = {
// Start an animation from one number to another // Start an animation from one number to another
custom: function( from, to, unit ) { custom: function( from, to, unit ) {
var self = this, var self = this,
fx = jQuery.fx, fx = jQuery.fx;
raf;
this.startTime = fxNow || createFxNow(); this.startTime = jQuery.now();
this.start = from; this.start = from;
this.end = to; this.end = to;
this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
@ -409,20 +363,7 @@ jQuery.fx.prototype = {
t.elem = this.elem; t.elem = this.elem;
if ( t() && jQuery.timers.push(t) && !timerId ) { if ( t() && jQuery.timers.push(t) && !timerId ) {
// Use requestAnimationFrame instead of setInterval if available timerId = setInterval(fx.tick, fx.interval);
if ( requestAnimationFrame ) {
timerId = true;
raf = function() {
// When timerId gets set to null at any point, this stops
if ( timerId ) {
requestAnimationFrame( raf );
fx.tick();
}
};
requestAnimationFrame( raf );
} else {
timerId = setInterval( fx.tick, fx.interval );
}
} }
}, },
@ -453,64 +394,60 @@ jQuery.fx.prototype = {
// Each step of an animation // Each step of an animation
step: function( gotoEnd ) { step: function( gotoEnd ) {
var t = fxNow || createFxNow(), var t = jQuery.now(), done = true;
done = true,
elem = this.elem,
options = this.options,
i, n;
if ( gotoEnd || t >= options.duration + this.startTime ) { if ( gotoEnd || t >= this.options.duration + this.startTime ) {
this.now = this.end; this.now = this.end;
this.pos = this.state = 1; this.pos = this.state = 1;
this.update(); this.update();
options.animatedProperties[ this.prop ] = true; this.options.curAnim[ this.prop ] = true;
for ( i in options.animatedProperties ) { for ( var i in this.options.curAnim ) {
if ( options.animatedProperties[i] !== true ) { if ( this.options.curAnim[i] !== true ) {
done = false; done = false;
} }
} }
if ( done ) { if ( done ) {
// Reset the overflow // Reset the overflow
if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { if ( this.options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
var elem = this.elem,
options = this.options;
jQuery.each( [ "", "X", "Y" ], function (index, value) { jQuery.each( [ "", "X", "Y" ], function (index, value) {
elem.style[ "overflow" + value ] = options.overflow[index]; elem.style[ "overflow" + value ] = options.overflow[index];
}); } );
} }
// Hide the element if the "hide" operation was done // Hide the element if the "hide" operation was done
if ( options.hide ) { if ( this.options.hide ) {
jQuery(elem).hide(); jQuery(this.elem).hide();
} }
// Reset the properties, if the item has been hidden or shown // Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show ) { if ( this.options.hide || this.options.show ) {
for ( var p in options.animatedProperties ) { for ( var p in this.options.curAnim ) {
jQuery.style( elem, p, options.orig[p] ); jQuery.style( this.elem, p, this.options.orig[p] );
} }
} }
// Execute the complete function // Execute the complete function
options.complete.call( elem ); this.options.complete.call( this.elem );
} }
return false; return false;
} else { } else {
// classical easing cannot be used with an Infinity duration var n = t - this.startTime;
if ( options.duration == Infinity ) { this.state = n / this.options.duration;
this.now = t;
} else {
n = t - this.startTime;
this.state = n / options.duration;
// Perform the easing function, defaults to swing // Perform the easing function, defaults to swing
this.pos = jQuery.easing[ options.animatedProperties[ this.prop ] ]( this.state, n, 0, 1, options.duration ); var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop];
var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear");
this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration);
this.now = this.start + ((this.end - this.start) * this.pos); this.now = this.start + ((this.end - this.start) * this.pos);
}
// Perform the next step of the animation // Perform the next step of the animation
this.update(); this.update();
} }
@ -521,7 +458,9 @@ jQuery.fx.prototype = {
jQuery.extend( jQuery.fx, { jQuery.extend( jQuery.fx, {
tick: function() { tick: function() {
for ( var timers = jQuery.timers, i = 0 ; i < timers.length ; ++i ) { var timers = jQuery.timers;
for ( var i = 0; i < timers.length; i++ ) {
if ( !timers[i]() ) { if ( !timers[i]() ) {
timers.splice(i--, 1); timers.splice(i--, 1);
} }
@ -569,47 +508,17 @@ if ( jQuery.expr && jQuery.expr.filters ) {
}; };
} }
// Try to restore the default display value of an element
function defaultDisplay( nodeName ) { function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) { if ( !elemdisplay[ nodeName ] ) {
var elem = jQuery("<" + nodeName + ">").appendTo("body"),
var body = document.body, display = elem.css("display");
elem = jQuery( "<" + nodeName + ">" ).appendTo( body ),
display = elem.css( "display" );
elem.remove(); elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) { if ( display === "none" || display === "" ) {
// No iframe to use yet, so create it display = "block";
if ( !iframe ) {
iframe = document.createElement( "iframe" );
iframe.frameBorder = iframe.width = iframe.height = 0;
} }
body.appendChild( iframe );
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" );
iframeDoc.close();
}
elem = iframeDoc.createElement( nodeName );
iframeDoc.body.appendChild( elem );
display = jQuery.css( elem, "display" );
body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display; elemdisplay[ nodeName ] = display;
} }

View file

@ -3,7 +3,7 @@
var rnamespaces = /\.(.*)$/, var rnamespaces = /\.(.*)$/,
rformElems = /^(?:textarea|input|select)$/i, rformElems = /^(?:textarea|input|select)$/i,
rperiod = /\./g, rperiod = /\./g,
rspaces = / /g, rspace = / /g,
rescape = /[^\w\s.|`]/g, rescape = /[^\w\s.|`]/g,
fcleanup = function( nm ) { fcleanup = function( nm ) {
return nm.replace(rescape, "\\$&"); return nm.replace(rescape, "\\$&");
@ -23,6 +23,17 @@ jQuery.event = {
return; return;
} }
// TODO :: Use a try/catch until it's safe to pull this out (likely 1.6)
// Minor release fix for bug #8018
try {
// For whatever reason, IE has trouble passing the window object
// around, causing it to be cloned in the process
if ( jQuery.isWindow( elem ) && ( elem !== window && !elem.frameElement ) ) {
elem = window;
}
}
catch ( e ) {}
if ( handler === false ) { if ( handler === false ) {
handler = returnFalse; handler = returnFalse;
} else if ( !handler ) { } else if ( !handler ) {
@ -60,9 +71,9 @@ jQuery.event = {
if ( !eventHandle ) { if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) { elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and // Handle the second event of a trigger and when
// when an event is called after a page has unloaded // an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
jQuery.event.handle.apply( eventHandle.elem, arguments ) : jQuery.event.handle.apply( eventHandle.elem, arguments ) :
undefined; undefined;
}; };
@ -132,7 +143,7 @@ jQuery.event = {
// Add the function to the element's handler list // Add the function to the element's handler list
handlers.push( handleObj ); handlers.push( handleObj );
// Keep track of which events have been used, for event optimization // Keep track of which events have been used, for global triggering
jQuery.event.global[ type ] = true; jQuery.event.global[ type ] = true;
} }
@ -266,61 +277,35 @@ jQuery.event = {
} }
}, },
// Events that are safe to short-circuit if no handlers are attached. // bubbling is internal
// Native DOM events should not be added, they may have inline handlers. trigger: function( event, data, elem /*, bubbling */ ) {
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Event object or event type // Event object or event type
var type = event.type || event, var type = event.type || event,
namespaces = [], bubbling = arguments[3];
exclusive;
if ( type.indexOf("!") >= 0 ) { if ( !bubbling ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ? event = typeof event === "object" ?
// jQuery.Event object // jQuery.Event object
event[ jQuery.expando ] ? event : event[ jQuery.expando ] ? event :
// Object literal // Object literal
new jQuery.Event( type, event ) : jQuery.extend( jQuery.Event(type), event ) :
// Just the event type (string) // Just the event type (string)
new jQuery.Event( type ); jQuery.Event(type);
event.type = type; if ( type.indexOf("!") >= 0 ) {
event.exclusive = exclusive; event.type = type = type.slice(0, -1);
event.namespace = namespaces.join("."); event.exclusive = true;
event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)");
// triggerHandler() and global events don't bubble or run the default action
if ( onlyHandlers || !elem ) {
event.preventDefault();
event.stopPropagation();
} }
// Handle a global trigger // Handle a global trigger
if ( !elem ) { if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document // Don't bubble custom events when global (to avoid too much overhead)
event.stopPropagation();
// Only trigger if we've ever bound an event for it
if ( jQuery.event.global[ type ] ) {
// XXX This code smells terrible. event.js should not be directly
// inspecting the data cache
jQuery.each( jQuery.cache, function() { jQuery.each( jQuery.cache, function() {
// internalKey variable is just used to make it easier to find // internalKey variable is just used to make it easier to find
// and potentially change this stuff later; currently it just // and potentially change this stuff later; currently it just
@ -331,98 +316,119 @@ jQuery.event = {
jQuery.event.trigger( event, data, internalCache.handle.elem ); jQuery.event.trigger( event, data, internalCache.handle.elem );
} }
}); });
return; }
} }
// Don't do events on text and comment nodes // Handle triggering a single element
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return; // don't do events on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
return undefined;
} }
// Clean up the event in case it is being reused // Clean up in case it is reused
event.result = undefined; event.result = undefined;
event.target = elem; event.target = elem;
// Clone any incoming data and prepend the event, creating the handler arg list // Clone the incoming data, if any
data = data != null ? jQuery.makeArray( data ) : []; data = jQuery.makeArray( data );
data.unshift( event ); data.unshift( event );
var cur = elem,
// IE doesn't like method names with a colon (#3533, #8272)
ontype = type.indexOf(":") < 0 ? "on" + type : "";
// Fire event on the current element, then bubble up the DOM tree
do {
var handle = jQuery._data( cur, "handle" );
event.currentTarget = cur;
if ( handle ) {
handle.apply( cur, data );
} }
event.currentTarget = elem;
// Trigger the event, it is assumed that "handle" is a function
var handle = jQuery._data( elem, "handle" );
if ( handle ) {
handle.apply( elem, data );
}
var parent = elem.parentNode || elem.ownerDocument;
// Trigger an inline bound script // Trigger an inline bound script
if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) { try {
if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) {
if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) {
event.result = false; event.result = false;
event.preventDefault(); event.preventDefault();
} }
}
// Bubble up to document, then to window // prevent IE from throwing an error for some elements with some event types, see #3533
cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window; } catch (inlineError) {}
} while ( cur && !event.isPropagationStopped() );
// If nobody prevented the default action, do it now if ( !event.isPropagationStopped() && parent ) {
if ( !event.isDefaultPrevented() ) { jQuery.event.trigger( event, data, parent, true );
} else if ( !event.isDefaultPrevented() ) {
var old, var old,
special = jQuery.event.special[ type ] || {}; target = event.target,
targetType = type.replace( rnamespaces, "" ),
isClick = jQuery.nodeName( target, "a" ) && targetType === "click",
special = jQuery.event.special[ targetType ] || {};
if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) && if ( (!special._default || special._default.call( elem, event ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction)() check here because IE6/7 fails that test.
// IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch.
try { try {
if ( ontype && elem[ type ] ) { if ( target[ targetType ] ) {
// Don't re-trigger an onFOO event when we call its FOO() method // Make sure that we don't accidentally re-trigger the onFOO events
old = elem[ ontype ]; old = target[ "on" + targetType ];
if ( old ) { if ( old ) {
elem[ ontype ] = null; target[ "on" + targetType ] = null;
} }
jQuery.event.triggered = type; jQuery.event.triggered = event.type;
elem[ type ](); target[ targetType ]();
} }
} catch ( ieError ) {}
// prevent IE from throwing an error for some elements with some event types, see #3533
} catch (triggerError) {}
if ( old ) { if ( old ) {
elem[ ontype ] = old; target[ "on" + targetType ] = old;
} }
jQuery.event.triggered = undefined; jQuery.event.triggered = undefined;
} }
} }
return event.result;
}, },
handle: function( event ) { handle: function( event ) {
event = jQuery.event.fix( event || window.event ); var all, handlers, namespaces, namespace_re, events,
// Snapshot the handlers list since a called handler may add/remove events. namespace_sort = [],
var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0), args = jQuery.makeArray( arguments );
run_all = !event.exclusive && !event.namespace,
args = Array.prototype.slice.call( arguments, 0 );
// Use the fix-ed Event rather than the (read-only) native event event = args[0] = jQuery.event.fix( event || window.event );
args[0] = event;
event.currentTarget = this; event.currentTarget = this;
// Namespaced event handlers
all = event.type.indexOf(".") < 0 && !event.exclusive;
if ( !all ) {
namespaces = event.type.split(".");
event.type = namespaces.shift();
namespace_sort = namespaces.slice(0).sort();
namespace_re = new RegExp("(^|\\.)" + namespace_sort.join("\\.(?:.*\\.)?") + "(\\.|$)");
}
event.namespace = event.namespace || namespace_sort.join(".");
events = jQuery._data(this, "events");
handlers = (events || {})[ event.type ];
if ( events && handlers ) {
// Clone the handlers to prevent manipulation
handlers = handlers.slice(0);
for ( var j = 0, l = handlers.length; j < l; j++ ) { for ( var j = 0, l = handlers.length; j < l; j++ ) {
var handleObj = handlers[ j ]; var handleObj = handlers[ j ];
// Triggered event must 1) be non-exclusive and have no namespace, or // Filter the functions by class
// 2) have namespace(s) a subset or equal to those in the bound event. if ( all || namespace_re.test( handleObj.namespace ) ) {
if ( run_all || event.namespace_re.test( handleObj.namespace ) ) {
// Pass in a reference to the handler function itself // Pass in a reference to the handler function itself
// So that we can later remove it // So that we can later remove it
event.handler = handleObj.handler; event.handler = handleObj.handler;
@ -444,6 +450,8 @@ jQuery.event = {
} }
} }
} }
}
return event.result; return event.result;
}, },
@ -482,9 +490,8 @@ jQuery.event = {
// Calculate pageX/Y if missing and clientX/Y available // Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) { if ( event.pageX == null && event.clientX != null ) {
var eventDocument = event.target.ownerDocument || document, var doc = document.documentElement,
doc = eventDocument.documentElement, body = document.body;
body = eventDocument.body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
@ -563,10 +570,10 @@ jQuery.removeEvent = document.removeEventListener ?
} }
}; };
jQuery.Event = function( src, props ) { jQuery.Event = function( src ) {
// Allow instantiation without the 'new' keyword // Allow instantiation without the 'new' keyword
if ( !this.preventDefault ) { if ( !this.preventDefault ) {
return new jQuery.Event( src, props ); return new jQuery.Event( src );
} }
// Event object // Event object
@ -584,11 +591,6 @@ jQuery.Event = function( src, props ) {
this.type = src; this.type = src;
} }
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// timeStamp is buggy for some events on Firefox(#3843) // timeStamp is buggy for some events on Firefox(#3843)
// So we won't rely on the native value // So we won't rely on the native value
this.timeStamp = jQuery.now(); this.timeStamp = jQuery.now();
@ -650,27 +652,33 @@ jQuery.Event.prototype = {
// Checks if an event happened on an element within another element // Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers // Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function( event ) { var withinElement = function( event ) {
// Check if mouse(over|out) are still within the same parent element // Check if mouse(over|out) are still within the same parent element
var related = event.relatedTarget, var parent = event.relatedTarget;
inside = false,
eventType = event.type;
// Firefox sometimes assigns relatedTarget a XUL element
// which we cannot access the parentNode property of
try {
// Chrome does something similar, the parentNode property
// can be accessed but is null.
if ( parent && parent !== document && !parent.parentNode ) {
return;
}
// Traverse up the tree
while ( parent && parent !== this ) {
parent = parent.parentNode;
}
if ( parent !== this ) {
// set the correct event type
event.type = event.data; event.type = event.data;
if ( related !== this ) { // handle event if we actually just moused on to a non sub-element
if ( related ) {
inside = jQuery.contains( this, related );
}
if ( !inside ) {
jQuery.event.handle.apply( this, arguments ); jQuery.event.handle.apply( this, arguments );
}
event.type = eventType; // assuming we've left the element since we most likely mousedover a xul element
} } catch(e) { }
}
}, },
// In case of event delegation, we only need to rename the event.type, // In case of event delegation, we only need to rename the event.type,
@ -700,7 +708,7 @@ if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = { jQuery.event.special.submit = {
setup: function( data, namespaces ) { setup: function( data, namespaces ) {
if ( !jQuery.nodeName( this, "form" ) ) { if ( this.nodeName && this.nodeName.toLowerCase() !== "form" ) {
jQuery.event.add(this, "click.specialSubmit", function( e ) { jQuery.event.add(this, "click.specialSubmit", function( e ) {
var elem = e.target, var elem = e.target,
type = elem.type; type = elem.type;
@ -749,7 +757,7 @@ if ( !jQuery.support.changeBubbles ) {
}).join("-") : }).join("-") :
""; "";
} else if ( jQuery.nodeName( elem, "select" ) ) { } else if ( elem.nodeName.toLowerCase() === "select" ) {
val = elem.selectedIndex; val = elem.selectedIndex;
} }
@ -789,9 +797,9 @@ if ( !jQuery.support.changeBubbles ) {
beforedeactivate: testChange, beforedeactivate: testChange,
click: function( e ) { click: function( e ) {
var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; var elem = e.target, type = elem.type;
if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) { if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) {
testChange.call( this, e ); testChange.call( this, e );
} }
}, },
@ -799,9 +807,9 @@ if ( !jQuery.support.changeBubbles ) {
// Change has to be called before submit // Change has to be called before submit
// Keydown will be called before keypress, which is used in submit-event delegation // Keydown will be called before keypress, which is used in submit-event delegation
keydown: function( e ) { keydown: function( e ) {
var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; var elem = e.target, type = elem.type;
if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) || if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") ||
(e.keyCode === 32 && (type === "checkbox" || type === "radio")) || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
type === "select-multiple" ) { type === "select-multiple" ) {
testChange.call( this, e ); testChange.call( this, e );
@ -858,7 +866,7 @@ function trigger( type, elem, args ) {
} }
// Create "bubbling" focus and blur events // Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) { if ( document.addEventListener ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout // Attach a single capturing handler while someone wants focusin/focusout
@ -893,8 +901,6 @@ if ( !jQuery.support.focusinBubbles ) {
jQuery.each(["bind", "one"], function( i, name ) { jQuery.each(["bind", "one"], function( i, name ) {
jQuery.fn[ name ] = function( type, data, fn ) { jQuery.fn[ name ] = function( type, data, fn ) {
var handler;
// Handle object literals // Handle object literals
if ( typeof type === "object" ) { if ( typeof type === "object" ) {
for ( var key in type ) { for ( var key in type ) {
@ -903,20 +909,15 @@ jQuery.each(["bind", "one"], function( i, name ) {
return this; return this;
} }
if ( arguments.length === 2 || data === false ) { if ( jQuery.isFunction( data ) || data === false ) {
fn = data; fn = data;
data = undefined; data = undefined;
} }
if ( name === "one" ) { var handler = name === "one" ? jQuery.proxy( fn, function( event ) {
handler = function( event ) {
jQuery( this ).unbind( event, handler ); jQuery( this ).unbind( event, handler );
return fn.apply( this, arguments ); return fn.apply( this, arguments );
}; }) : fn;
handler.guid = fn.guid || jQuery.guid++;
} else {
handler = fn;
}
if ( type === "unload" && name !== "one" ) { if ( type === "unload" && name !== "one" ) {
this.one( type, data, fn ); this.one( type, data, fn );
@ -969,34 +970,35 @@ jQuery.fn.extend({
triggerHandler: function( type, data ) { triggerHandler: function( type, data ) {
if ( this[0] ) { if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true ); var event = jQuery.Event( type );
event.preventDefault();
event.stopPropagation();
jQuery.event.trigger( event, data, this[0] );
return event.result;
} }
}, },
toggle: function( fn ) { toggle: function( fn ) {
// Save reference to arguments for access in closure // Save reference to arguments for access in closure
var args = arguments, var args = arguments,
guid = fn.guid || jQuery.guid++, i = 1;
i = 0,
toggler = function( event ) { // link all the functions, so any of them can unbind this click handler
while ( i < args.length ) {
jQuery.proxy( fn, args[ i++ ] );
}
return this.click( jQuery.proxy( fn, function( event ) {
// Figure out which function to execute // Figure out which function to execute
var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop // Make sure that clicks stop
event.preventDefault(); event.preventDefault();
// and execute the function // and execute the function
return args[ lastToggle ].apply( this, arguments ) || false; return args[ lastToggle ].apply( this, arguments ) || false;
}; }));
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
}, },
hover: function( fnOver, fnOut ) { hover: function( fnOver, fnOut ) {
@ -1025,16 +1027,8 @@ jQuery.each(["live", "die"], function( i, name ) {
return this; return this;
} }
if ( name === "die" && !types && if ( jQuery.isFunction( data ) ) {
origSelector && origSelector.charAt(0) === "." ) { fn = data;
context.unbind( origSelector );
return this;
}
if ( data === false || jQuery.isFunction( data ) ) {
fn = data || returnFalse;
data = undefined; data = undefined;
} }
@ -1056,7 +1050,7 @@ jQuery.each(["live", "die"], function( i, name ) {
preType = type; preType = type;
if ( liveMap[ type ] ) { if ( type === "focus" || type === "blur" ) {
types.push( liveMap[ type ] + namespaces ); types.push( liveMap[ type ] + namespaces );
type = type + namespaces; type = type + namespaces;
@ -1127,11 +1121,6 @@ function liveHandler( event ) {
if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
event.type = handleObj.preType; event.type = handleObj.preType;
related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];
// Make sure not to accidentally match a child element with the same selector
if ( related && jQuery.contains( elem, related ) ) {
related = elem;
}
} }
if ( !related || related !== elem ) { if ( !related || related !== elem ) {
@ -1170,7 +1159,7 @@ function liveHandler( event ) {
} }
function liveConvert( type, selector ) { function liveConvert( type, selector ) {
return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&"); return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspace, "&");
} }
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
@ -1195,4 +1184,3 @@ jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblcl
}); });
})( jQuery ); })( jQuery );

View file

@ -16,6 +16,4 @@
(function( window, undefined ) { (function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox) // Use the correct document accordingly with window argument (sandbox)
var document = window.document, var document = window.document;
navigator = window.navigator,
location = window.location;

View file

@ -9,8 +9,6 @@ var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rnocache = /<(?:script|object|embed|option|style)/i, rnocache = /<(?:script|object|embed|option|style)/i,
// checked="checked" or checked // checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
wrapMap = { wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ], option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ], legend: [ 1, "<fieldset>", "</fieldset>" ],
@ -71,7 +69,7 @@ jQuery.fn.extend({
} }
return elem; return elem;
}).append( this ); }).append(this);
} }
return this; return this;
@ -379,27 +377,21 @@ function cloneCopyEvent( src, dest ) {
} }
} }
function cloneFixAttributes( src, dest ) { function cloneFixAttributes(src, dest) {
var nodeName;
// We do not need to do anything for non-Elements // We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) { if ( dest.nodeType !== 1 ) {
return; return;
} }
var nodeName = dest.nodeName.toLowerCase();
// clearAttributes removes the attributes, which we don't want, // clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want // but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes(); dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the // mergeAttributes, in contrast, only merges back on the
// original attributes, not the events // original attributes, not the events
if ( dest.mergeAttributes ) { dest.mergeAttributes(src);
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 fail to clone children inside object elements that use // IE6-8 fail to clone children inside object elements that use
// the proprietary classid attribute value (rather than the type // the proprietary classid attribute value (rather than the type
@ -438,21 +430,8 @@ function cloneFixAttributes( src, dest ) {
} }
jQuery.buildFragment = function( args, nodes, scripts ) { jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults, doc; var fragment, cacheable, cacheresults,
doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
// nodes may contain either an explicit document object,
// a jQuery collection or context object.
// If nodes[0] contains a valid object to assign to doc
if ( nodes && nodes[0] ) {
doc = nodes[0].ownerDocument || nodes[0];
}
// Ensure that an attr object doesn't incorrectly stand in as a document object
// Chrome and Firefox seem to allow this to occur and will throw exception
// Fixes #8950
if ( !doc.createDocumentFragment ) {
doc = document;
}
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them // Cloning options loses the selected state, so don't cache them
@ -462,12 +441,13 @@ jQuery.buildFragment = function( args, nodes, scripts ) {
args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
cacheable = true; cacheable = true;
cacheresults = jQuery.fragments[ args[0] ]; cacheresults = jQuery.fragments[ args[0] ];
if ( cacheresults && cacheresults !== 1 ) { if ( cacheresults ) {
if ( cacheresults !== 1 ) {
fragment = cacheresults; fragment = cacheresults;
} }
} }
}
if ( !fragment ) { if ( !fragment ) {
fragment = doc.createDocumentFragment(); fragment = doc.createDocumentFragment();
@ -523,21 +503,6 @@ function getAll( elem ) {
} }
} }
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( elem.type === "checkbox" || elem.type === "radio" ) {
elem.defaultChecked = elem.checked;
}
}
// Finds all inputs and passes them to fixDefaultChecked
function findInputs( elem ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( "getElementsByTagName" in elem ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
jQuery.extend({ jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) { clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var clone = elem.cloneNode(true), var clone = elem.cloneNode(true),
@ -582,15 +547,10 @@ jQuery.extend({
} }
} }
srcElements = destElements = null;
// Return the cloned set // Return the cloned set
return clone; return clone;
}, },
clean: function( elems, context, fragment, scripts ) { clean: function( elems, context, fragment, scripts ) {
var checkScriptType;
context = context || document; context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object' // !context.createElement fails in IE with an error but returns typeof 'object'
@ -598,7 +558,7 @@ jQuery.extend({
context = context.ownerDocument || context[0] && context[0].ownerDocument || document; context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
} }
var ret = [], j; var ret = [];
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) { if ( typeof elem === "number" ) {
@ -610,10 +570,10 @@ jQuery.extend({
} }
// Convert html string into DOM nodes // Convert html string into DOM nodes
if ( typeof elem === "string" ) { if ( typeof elem === "string" && !rhtml.test( elem ) ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem ); elem = context.createTextNode( elem );
} else {
} else if ( typeof elem === "string" ) {
// Fix "XHTML"-style tags in all browsers // Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>"); elem = elem.replace(rxhtmlTag, "<$1></$2>");
@ -644,11 +604,12 @@ jQuery.extend({
div.childNodes : div.childNodes :
[]; [];
for ( j = tbody.length - 1; j >= 0 ; --j ) { for ( var j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] ); tbody[ j ].parentNode.removeChild( tbody[ j ] );
} }
} }
} }
// IE completely kills leading whitespace when innerHTML is used // IE completely kills leading whitespace when innerHTML is used
@ -658,20 +619,6 @@ jQuery.extend({
elem = div.childNodes; elem = div.childNodes;
} }
}
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;
if ( !jQuery.support.appendChecked ) {
if ( elem[0] && typeof (len = elem.length) === "number" ) {
for ( j = 0; j < len; j++ ) {
findInputs( elem[j] );
}
} else {
findInputs( elem );
}
}
if ( elem.nodeType ) { if ( elem.nodeType ) {
ret.push( elem ); ret.push( elem );
@ -681,18 +628,13 @@ jQuery.extend({
} }
if ( fragment ) { if ( fragment ) {
checkScriptType = function( elem ) {
return !elem.type || rscriptType.test( elem.type );
};
for ( i = 0; ret[i]; i++ ) { for ( i = 0; ret[i]; i++ ) {
if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
} else { } else {
if ( ret[i].nodeType === 1 ) { if ( ret[i].nodeType === 1 ) {
var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
} }
fragment.appendChild( ret[i] ); fragment.appendChild( ret[i] );
} }
@ -754,7 +696,7 @@ function evalScript( i, elem ) {
dataType: "script" dataType: "script"
}); });
} else { } else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) ); jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
} }
if ( elem.parentNode ) { if ( elem.parentNode ) {

View file

@ -180,19 +180,17 @@ jQuery.offset = {
curOffset = curElem.offset(), curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ), curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ), curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray('auto', [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft; props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed // need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) { if ( calculatePosition ) {
curPosition = curElem.position(); curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
} }
curTop = calculatePosition ? curPosition.top : parseInt( curCSSTop, 10 ) || 0;
curLeft = calculatePosition ? curPosition.left : parseInt( curCSSLeft, 10 ) || 0;
if ( jQuery.isFunction( options ) ) { if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset ); options = options.call( elem, i, curOffset );
} }
@ -261,16 +259,29 @@ jQuery.fn.extend({
jQuery.each( ["Left", "Top"], function( i, name ) { jQuery.each( ["Left", "Top"], function( i, name ) {
var method = "scroll" + name; var method = "scroll" + name;
jQuery.fn[ method ] = function( val ) { jQuery.fn[ method ] = function(val) {
var elem, win; var elem = this[0], win;
if ( val === undefined ) {
elem = this[ 0 ];
if ( !elem ) { if ( !elem ) {
return null; return null;
} }
if ( val !== undefined ) {
// Set the scroll offset
return this.each(function() {
win = getWindow( this );
if ( win ) {
win.scrollTo(
!i ? val : jQuery(win).scrollLeft(),
i ? val : jQuery(win).scrollTop()
);
} else {
this[ method ] = val;
}
});
} else {
win = getWindow( elem ); win = getWindow( elem );
// Return the scroll offset // Return the scroll offset
@ -279,21 +290,6 @@ jQuery.each( ["Left", "Top"], function( i, name ) {
win.document.body[ method ] : win.document.body[ method ] :
elem[ method ]; elem[ method ];
} }
// Set the scroll offset
return this.each(function() {
win = getWindow( this );
if ( win ) {
win.scrollTo(
!i ? val : jQuery( win ).scrollLeft(),
i ? val : jQuery( win ).scrollTop()
);
} else {
this[ method ] = val;
}
});
}; };
}); });

View file

@ -1,3 +1,2 @@
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery; window.jQuery = window.$ = jQuery;
})(window); })(window);

View file

@ -1,75 +1,34 @@
(function( jQuery ) { (function( jQuery ) {
function handleQueueMarkDefer( elem, type, src ) {
var deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
defer = jQuery.data( elem, deferDataKey, undefined, true );
if ( defer &&
( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) &&
( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) {
// Give room for hard-coded callbacks to fire first
// and eventually mark/queue something else on the element
setTimeout( function() {
if ( !jQuery.data( elem, queueDataKey, undefined, true ) &&
!jQuery.data( elem, markDataKey, undefined, true ) ) {
jQuery.removeData( elem, deferDataKey, true );
defer.resolve();
}
}, 0 );
}
}
jQuery.extend({ jQuery.extend({
_mark: function( elem, type ) {
if ( elem ) {
type = (type || "fx") + "mark";
jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true );
}
},
_unmark: function( force, elem, type ) {
if ( force !== true ) {
type = elem;
elem = force;
force = false;
}
if ( elem ) {
type = type || "fx";
var key = type + "mark",
count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 );
if ( count ) {
jQuery.data( elem, key, count, true );
} else {
jQuery.removeData( elem, key, true );
handleQueueMarkDefer( elem, type, "mark" );
}
}
},
queue: function( elem, type, data ) { queue: function( elem, type, data ) {
if ( elem ) { if ( !elem ) {
return;
}
type = (type || "fx") + "queue"; type = (type || "fx") + "queue";
var q = jQuery.data( elem, type, undefined, true ); var q = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup // Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) { if ( !data ) {
return q || [];
}
if ( !q || jQuery.isArray(data) ) { if ( !q || jQuery.isArray(data) ) {
q = jQuery.data( elem, type, jQuery.makeArray(data), true ); q = jQuery._data( elem, type, jQuery.makeArray(data) );
} else { } else {
q.push( data ); q.push( data );
} }
}
return q || []; return q;
}
}, },
dequeue: function( elem, type ) { dequeue: function( elem, type ) {
type = type || "fx"; type = type || "fx";
var queue = jQuery.queue( elem, type ), var queue = jQuery.queue( elem, type ),
fn = queue.shift(), fn = queue.shift();
defer;
// If the fx queue is dequeued, always remove the progress sentinel // If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) { if ( fn === "inprogress" ) {
@ -90,7 +49,6 @@ jQuery.extend({
if ( !queue.length ) { if ( !queue.length ) {
jQuery.removeData( elem, type + "queue", true ); jQuery.removeData( elem, type + "queue", true );
handleQueueMarkDefer( elem, type, "queue" );
} }
} }
}); });
@ -105,7 +63,7 @@ jQuery.fn.extend({
if ( data === undefined ) { if ( data === undefined ) {
return jQuery.queue( this[0], type ); return jQuery.queue( this[0], type );
} }
return this.each(function() { return this.each(function( i ) {
var queue = jQuery.queue( this, type, data ); var queue = jQuery.queue( this, type, data );
if ( type === "fx" && queue[0] !== "inprogress" ) { if ( type === "fx" && queue[0] !== "inprogress" ) {
@ -118,6 +76,7 @@ jQuery.fn.extend({
jQuery.dequeue( this, type ); jQuery.dequeue( this, type );
}); });
}, },
// Based off of the plugin by Clint Helfers, with permission. // Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/ // http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) { delay: function( time, type ) {
@ -131,41 +90,9 @@ jQuery.fn.extend({
}, time ); }, time );
}); });
}, },
clearQueue: function( type ) { clearQueue: function( type ) {
return this.queue( type || "fx", [] ); return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, object ) {
if ( typeof type !== "string" ) {
object = type;
type = undefined;
}
type = type || "fx";
var defer = jQuery.Deferred(),
elements = this,
i = elements.length,
count = 1,
deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
tmp;
function resolve() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
}
while( i-- ) {
if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) {
count++;
tmp.done( resolve );
}
}
resolve();
return defer.promise();
} }
}); });

@ -1 +1 @@
Subproject commit 3ba396e439a07c2a2facafbe07cdaa1b80a24c00 Subproject commit f12b9309269ba7e705a99efe099f86ed1fe98d58

View file

@ -1,63 +1,44 @@
(function( jQuery ) { (function( jQuery ) {
jQuery.support = (function() { (function() {
var div = document.createElement( "div" ), jQuery.support = {};
documentElement = document.documentElement,
all,
a,
select,
opt,
input,
marginDiv,
support,
fragment,
body,
testElementParent,
testElement,
testElementStyle,
tds,
events,
eventName,
i,
isSupported;
// Preliminary tests var div = document.createElement("div");
div.setAttribute("className", "t");
div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName( "*" ); div.style.display = "none";
a = div.getElementsByTagName( "a" )[ 0 ]; div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
var all = div.getElementsByTagName("*"),
a = div.getElementsByTagName("a")[0],
select = document.createElement("select"),
opt = select.appendChild( document.createElement("option") ),
input = div.getElementsByTagName("input")[0];
// Can't get basic test support // Can't get basic test support
if ( !all || !all.length || !a ) { if ( !all || !all.length || !a ) {
return {}; return;
} }
// First batch of supports tests jQuery.support = {
select = document.createElement( "select" );
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName( "input" )[ 0 ];
support = {
// IE strips leading whitespace when .innerHTML is used // IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ), leadingWhitespace: div.firstChild.nodeType === 3,
// Make sure that tbody elements aren't automatically inserted // Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables // IE will insert them into empty tables
tbody: !div.getElementsByTagName( "tbody" ).length, tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML // Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE // This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName( "link" ).length, htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute // Get the style information from getAttribute
// (IE uses .cssText instead) // (IE uses .cssText insted)
style: /top/.test( a.getAttribute("style") ), style: /red/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated // Make sure that URLs aren't manipulated
// (IE normalizes it by default) // (IE normalizes it by default)
hrefNormalized: ( a.getAttribute( "href" ) === "/a" ), hrefNormalized: a.getAttribute("href") === "/a",
// Make sure that element opacity exists // Make sure that element opacity exists
// (IE uses filter instead) // (IE uses filter instead)
@ -71,102 +52,104 @@ jQuery.support = (function() {
// Make sure that if no value is specified for a checkbox // Make sure that if no value is specified for a checkbox
// that it defaults to "on". // that it defaults to "on".
// (WebKit defaults to "" instead) // (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ), checkOn: input.value === "on",
// Make sure that a selected-by-default option has a working selected property. // Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup) // (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected, optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Will be defined later // Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true, deleteExpando: true,
optDisabled: false,
checkClone: false,
noCloneEvent: true, noCloneEvent: true,
noCloneChecked: true,
boxModel: null,
inlineBlockNeedsLayout: false, inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false, shrinkWrapBlocks: false,
reliableHiddenOffsets: true,
reliableMarginRight: true reliableMarginRight: true
}; };
// Make sure checked status is properly cloned
input.checked = true; input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked; jQuery.support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled // Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled) // (WebKit marks them as diabled)
select.disabled = true; select.disabled = true;
support.optDisabled = !opt.disabled; jQuery.support.optDisabled = !opt.disabled;
var _scriptEval = null;
jQuery.support.scriptEval = function() {
if ( _scriptEval === null ) {
var root = document.documentElement,
script = document.createElement("script"),
id = "script" + jQuery.now();
// Make sure that the execution of code works by injecting a script
// tag with appendChild/createTextNode
// (IE doesn't support this, fails, and uses .text instead)
try {
script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
} catch(e) {}
root.insertBefore( script, root.firstChild );
if ( window[ id ] ) {
_scriptEval = true;
delete window[ id ];
} else {
_scriptEval = false;
}
root.removeChild( script );
}
return _scriptEval;
};
// Test to see if it's possible to delete an expando from an element // Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer // Fails in Internet Explorer
try { try {
delete div.test; delete div.test;
} catch( e ) {
support.deleteExpando = false; } catch(e) {
jQuery.support.deleteExpando = false;
} }
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", function() { div.attachEvent("onclick", function click() {
// Cloning a node shouldn't copy over any // Cloning a node shouldn't copy over any
// bound event handlers (IE does this) // bound event handlers (IE does this)
support.noCloneEvent = false; jQuery.support.noCloneEvent = false;
div.detachEvent("onclick", click);
}); });
div.cloneNode( true ).fireEvent( "onclick" ); div.cloneNode(true).fireEvent("onclick");
} }
// Check if a radio maintains it's value div = document.createElement("div");
// after being appended to the DOM div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>";
input = document.createElement("input");
input.value = "t";
input.setAttribute("type", "radio");
support.radioValue = input.value === "t";
input.setAttribute("checked", "checked"); var fragment = document.createDocumentFragment();
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.firstChild ); fragment.appendChild( div.firstChild );
// WebKit doesn't clone checked state correctly in fragments // WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked;
div.innerHTML = "";
// Figure out if the W3C box model works as expected // Figure out if the W3C box model works as expected
// document.body must exist before we can do this
jQuery(function() {
var div = document.createElement("div"),
body = document.getElementsByTagName("body")[0];
// Frameset documents with no body should not run this code
if ( !body ) {
return;
}
div.style.width = div.style.paddingLeft = "1px"; div.style.width = div.style.paddingLeft = "1px";
body.appendChild( div );
body = document.getElementsByTagName( "body" )[ 0 ]; jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
// We use our own, invisible, body unless the body is already present
// in which case we use a div (#9239)
testElement = document.createElement( body ? "div" : "body" );
testElementStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0
};
if ( body ) {
jQuery.extend( testElementStyle, {
position: "absolute",
left: -1000,
top: -1000
});
}
for ( i in testElementStyle ) {
testElement.style[ i ] = testElementStyle[ i ];
}
testElement.appendChild( div );
testElementParent = body || documentElement;
testElementParent.insertBefore( testElement, testElementParent.firstChild );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
support.boxModel = div.offsetWidth === 2;
if ( "zoom" in div.style ) { if ( "zoom" in div.style ) {
// Check if natively block-level elements act like inline-block // Check if natively block-level elements act like inline-block
@ -175,17 +158,17 @@ jQuery.support = (function() {
// (IE < 8 does this) // (IE < 8 does this)
div.style.display = "inline"; div.style.display = "inline";
div.style.zoom = 1; div.style.zoom = 1;
support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); jQuery.support.inlineBlockNeedsLayout = div.offsetWidth === 2;
// Check if elements with layout shrink-wrap their children // Check if elements with layout shrink-wrap their children
// (IE 6 does this) // (IE 6 does this)
div.style.display = ""; div.style.display = "";
div.innerHTML = "<div style='width:4px;'></div>"; div.innerHTML = "<div style='width:4px;'></div>";
support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2;
} }
div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>"; div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" ); var tds = div.getElementsByTagName("td");
// Check if table cells still have offsetWidth/Height when they are set // Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a // to display:none and there are still other visible table cells in a
@ -194,14 +177,14 @@ jQuery.support = (function() {
// display:none (it is still safe to use offsets if a parent element is // display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information). // hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test) // (only IE 8 fails this test)
isSupported = ( tds[ 0 ].offsetHeight === 0 ); jQuery.support.reliableHiddenOffsets = tds[0].offsetHeight === 0;
tds[ 0 ].style.display = ""; tds[0].style.display = "";
tds[ 1 ].style.display = "none"; tds[1].style.display = "none";
// Check if empty table cells still have offsetWidth/Height // Check if empty table cells still have offsetWidth/Height
// (IE < 8 fail this test) // (IE < 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0;
div.innerHTML = ""; div.innerHTML = "";
// Check if div with explicit width and no margin-right incorrectly // Check if div with explicit width and no margin-right incorrectly
@ -210,47 +193,41 @@ jQuery.support = (function() {
// Fails in WebKit before Feb 2011 nightlies // Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
if ( document.defaultView && document.defaultView.getComputedStyle ) { if ( document.defaultView && document.defaultView.getComputedStyle ) {
marginDiv = document.createElement( "div" ); div.style.width = "1px";
marginDiv.style.width = "0"; div.style.marginRight = "0";
marginDiv.style.marginRight = "0"; jQuery.support.reliableMarginRight = ( parseInt(document.defaultView.getComputedStyle(div, null).marginRight, 10) || 0 ) === 0;
div.appendChild( marginDiv );
support.reliableMarginRight =
( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
} }
// Remove the body element we added body.removeChild( div ).style.display = "none";
testElement.innerHTML = ""; div = tds = null;
testElementParent.removeChild( testElement ); });
// Technique from Juriy Zaytsev // Technique from Juriy Zaytsev
// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
var eventSupported = function( eventName ) {
var el = document.createElement("div");
eventName = "on" + eventName;
// We only care about the case where non-standard event systems // We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to // are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP // avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) { if ( !el.attachEvent ) {
for( i in { return true;
submit: 1, }
change: 1,
focusin: 1 var isSupported = (eventName in el);
} ) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) { if ( !isSupported ) {
div.setAttribute( eventName, "return;" ); el.setAttribute(eventName, "return;");
isSupported = ( typeof div[ eventName ] === "function" ); isSupported = typeof el[eventName] === "function";
}
support[ i + "Bubbles" ] = isSupported;
}
} }
return isSupported;
};
// Null connected elements to avoid leaks in IE jQuery.support.submitBubbles = eventSupported("submit");
testElement = fragment = select = opt = body = marginDiv = div = input = null; jQuery.support.changeBubbles = eventSupported("change");
return support; // release memory in IE
div = all = a = null;
})(); })();
// Keep track of boxModel
jQuery.boxModel = jQuery.support.boxModel;
})( jQuery ); })( jQuery );

View file

@ -17,30 +17,17 @@ var runtil = /Until$/,
jQuery.fn.extend({ jQuery.fn.extend({
find: function( selector ) { find: function( selector ) {
var self = this,
i, l;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
var ret = this.pushStack( "", "find", selector ), var ret = this.pushStack( "", "find", selector ),
length, n, r; length = 0;
for ( i = 0, l = this.length; i < l; i++ ) { for ( var i = 0, l = this.length; i < l; i++ ) {
length = ret.length; length = ret.length;
jQuery.find( selector, this[i], ret ); jQuery.find( selector, this[i], ret );
if ( i > 0 ) { if ( i > 0 ) {
// Make sure that the results are unique // Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) { for ( var n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) { for ( var r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) { if ( ret[r] === ret[n] ) {
ret.splice(n--, 1); ret.splice(n--, 1);
break; break;
@ -73,15 +60,12 @@ jQuery.fn.extend({
}, },
is: function( selector ) { is: function( selector ) {
return !!selector && ( typeof selector === "string" ? return !!selector && jQuery.filter( selector, this ).length > 0;
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
}, },
closest: function( selectors, context ) { closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0]; var ret = [], i, l, cur = this[0];
// Array
if ( jQuery.isArray( selectors ) ) { if ( jQuery.isArray( selectors ) ) {
var match, selector, var match, selector,
matches = {}, matches = {},
@ -91,8 +75,8 @@ jQuery.fn.extend({
for ( i = 0, l = selectors.length; i < l; i++ ) { for ( i = 0, l = selectors.length; i < l; i++ ) {
selector = selectors[i]; selector = selectors[i];
if ( !matches[ selector ] ) { if ( !matches[selector] ) {
matches[ selector ] = POS.test( selector ) ? matches[selector] = jQuery.expr.match.POS.test( selector ) ?
jQuery( selector, context || this.context ) : jQuery( selector, context || this.context ) :
selector; selector;
} }
@ -100,9 +84,9 @@ jQuery.fn.extend({
while ( cur && cur.ownerDocument && cur !== context ) { while ( cur && cur.ownerDocument && cur !== context ) {
for ( selector in matches ) { for ( selector in matches ) {
match = matches[ selector ]; match = matches[selector];
if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) { if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) {
ret.push({ selector: selector, elem: cur, level: level }); ret.push({ selector: selector, elem: cur, level: level });
} }
} }
@ -115,10 +99,8 @@ jQuery.fn.extend({
return ret; return ret;
} }
// String var pos = POS.test( selectors ) ?
var pos = POS.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : null;
jQuery( selectors, context || this.context ) :
0;
for ( i = 0, l = this.length; i < l; i++ ) { for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i]; cur = this[i];
@ -130,14 +112,14 @@ jQuery.fn.extend({
} else { } else {
cur = cur.parentNode; cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { if ( !cur || !cur.ownerDocument || cur === context ) {
break; break;
} }
} }
} }
} }
ret = ret.length > 1 ? jQuery.unique( ret ) : ret; ret = ret.length > 1 ? jQuery.unique(ret) : ret;
return this.pushStack( ret, "closest", selectors ); return this.pushStack( ret, "closest", selectors );
}, },
@ -160,7 +142,7 @@ jQuery.fn.extend({
add: function( selector, context ) { add: function( selector, context ) {
var set = typeof selector === "string" ? var set = typeof selector === "string" ?
jQuery( selector, context ) : jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), jQuery.makeArray( selector ),
all = jQuery.merge( this.get(), set ); all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
@ -298,11 +280,6 @@ jQuery.extend({
// Implement the identical functionality for filter and not // Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) { function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) { if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) { return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem ); var retVal = !!qualifier.call( elem, i, elem );

View file

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<dashboard> <dashboard>
<locations class="foo"> <locations class="foo">
<location for="bar" checked="different"> <location for="bar">
<infowindowtab> <infowindowtab>
<tab title="Location"><![CDATA[blabla]]></tab> <tab title="Location"><![CDATA[blabla]]></tab>
<tab title="Users"><![CDATA[blublu]]></tab> <tab title="Users"><![CDATA[blublu]]></tab>

View file

@ -1,14 +1,14 @@
// Simple script loader that uses jQuery.readyWait via jQuery.holdReady() // Simple script loader that uses jQuery.readyWait
//Hold on jQuery! //Hold on jQuery!
jQuery.holdReady(true); jQuery.readyWait++;
var readyRegExp = /^(complete|loaded)$/; var readyRegExp = /^(complete|loaded)$/;
function assetLoaded( evt ){ function assetLoaded( evt ){
var node = evt.currentTarget || evt.srcElement; var node = evt.currentTarget || evt.srcElement;
if ( evt.type === "load" || readyRegExp.test(node.readyState) ) { if ( evt.type === "load" || readyRegExp.test(node.readyState) ) {
jQuery.holdReady(false); jQuery.ready(true);
} }
} }

View file

@ -1,37 +0,0 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr" id="html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
body {
background: #000000;
}
</style>
</head>
<body>
<div>
<script src="../../../src/core.js"></script>
<script src="../../../src/deferred.js"></script>
<script src="../../../src/support.js"></script>
<script src="../../../src/data.js"></script>
<script src="../../../src/queue.js"></script>
<script src="../../../src/attributes.js"></script>
<script src="../../../src/event.js"></script>
<script src="../../../src/sizzle/sizzle.js"></script>
<script src="../../../src/sizzle-jquery.js"></script>
<script src="../../../src/traversing.js"></script>
<script src="../../../src/manipulation.js"></script>
<script src="../../../src/css.js"></script>
<script src="../../../src/ajax.js"></script>
<script src="../../../src/ajax/jsonp.js"></script>
<script src="../../../src/ajax/script.js"></script>
<script src="../../../src/ajax/xhr.js"></script>
<script src="../../../src/effects.js"></script>
<script src="../../../src/offset.js"></script>
<script src="../../../src/dimensions.js"></script>
</div>
<script>
window.top.supportCallback( jQuery( "body" ).css( "backgroundColor" ), jQuery.support );
</script>
</body>
</html>

View file

@ -1,27 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<script src="../../../src/core.js"></script>
<script src="../../../src/deferred.js"></script>
<script src="../../../src/support.js"></script>
<script src="../../../src/data.js"></script>
<script src="../../../src/queue.js"></script>
<script src="../../../src/attributes.js"></script>
<script src="../../../src/event.js"></script>
<script src="../../../src/sizzle/sizzle.js"></script>
<script src="../../../src/sizzle-jquery.js"></script>
<script src="../../../src/traversing.js"></script>
<script src="../../../src/manipulation.js"></script>
<script src="../../../src/css.js"></script>
<script src="../../../src/ajax.js"></script>
<script src="../../../src/ajax/jsonp.js"></script>
<script src="../../../src/ajax/script.js"></script>
<script src="../../../src/ajax/xhr.js"></script>
<script src="../../../src/effects.js"></script>
<script src="../../../src/offset.js"></script>
<script src="../../../src/dimensions.js"></script>
<script>
window.top.supportCallback( document.compatMode, jQuery.support.boxModel );
</script>
</body>
</html>

View file

@ -1,25 +0,0 @@
<html>
<head>
<script src="../../../src/core.js"></script>
<script src="../../../src/deferred.js"></script>
<script src="../../../src/support.js"></script>
<script src="../../../src/data.js"></script>
<script src="../../../src/queue.js"></script>
<script src="../../../src/attributes.js"></script>
<script src="../../../src/event.js"></script>
<script src="../../../src/sizzle/sizzle.js"></script>
<script src="../../../src/sizzle-jquery.js"></script>
<script src="../../../src/traversing.js"></script>
<script src="../../../src/manipulation.js"></script>
<script src="../../../src/css.js"></script>
<script src="../../../src/ajax.js"></script>
<script src="../../../src/ajax/jsonp.js"></script>
<script src="../../../src/ajax/script.js"></script>
<script src="../../../src/ajax/xhr.js"></script>
<script src="../../../src/effects.js"></script>
<script src="../../../src/offset.js"></script>
<script src="../../../src/dimensions.js"></script>
</head>
<body>
</body>
</html>

View file

@ -2,9 +2,8 @@ jQuery.noConflict(); // Allow the test to run with other libs or jQuery's.
// jQuery-specific QUnit.reset // jQuery-specific QUnit.reset
(function() { (function() {
var reset = QUnit.reset, var reset = QUnit.reset;
ajaxSettings = jQuery.ajaxSettings; var ajaxSettings = jQuery.ajaxSettings
QUnit.reset = function() { QUnit.reset = function() {
reset.apply(this, arguments); reset.apply(this, arguments);
jQuery.event.global = {}; jQuery.event.global = {};
@ -25,9 +24,3 @@ jQuery.noConflict(); // Allow the test to run with other libs or jQuery's.
document.write("<scr" + "ipt src='http://swarm.jquery.org/js/inject.js?" + (new Date).getTime() + "'></scr" + "ipt>"); document.write("<scr" + "ipt src='http://swarm.jquery.org/js/inject.js?" + (new Date).getTime() + "'></scr" + "ipt>");
})(); })();
// QUnit Aliases
(function() {
window.equals = window.equal;
window.same = window.deepEqual;
})();

View file

@ -1,5 +1,5 @@
/* for testing opacity set in styles in IE */ /* for testing opacity set in styles in IE */
ol#empty { opacity: 0; filter:Alpha(opacity=0) progid:DXImageTransform.Microsoft.gradient(startColorStr='#ffff0000', EndColorStr='#ffffffff'); } ol#empty { opacity: 0; filter:Alpha(opacity=0); }
div#fx-tests h4 { div#fx-tests h4 {
background: red; background: red;
@ -109,15 +109,3 @@ div#show-tests * { display: none; }
#nothiddendiv { font-size: 16px; } #nothiddendiv { font-size: 16px; }
#nothiddendivchild.em { font-size: 2em; } #nothiddendivchild.em { font-size: 2em; }
#nothiddendivchild.prct { font-size: 150%; } #nothiddendivchild.prct { font-size: 150%; }
/* For testing type on vml in IE #7071 */
v\:oval { behavior:url(#default#VML); display:inline-block; }
/* 8099 changes to default styles are read correctly */
tt { display: none; }
sup { display: none; }
dfn { display: none; }
/* #9239 Attach a background to the body( avoid crashes in removing the test element in support ) */
body, div { background: url(http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif) no-repeat -1000px 0; }

View file

@ -1,8 +0,0 @@
// Run minified source from dist (do make first)
// Should be loaded before QUnit but after src
(function() {
if ( /jquery\=min/.test( window.location.search ) ) {
jQuery.noConflict( true );
document.write(unescape("%3Cscript%20src%3D%27../dist/jquery.min.js%27%3E%3C/script%3E"));
}
})();

View file

@ -184,16 +184,6 @@
</tr> </tr>
</table> </table>
<h1>Mouseleave Tests</h1>
<div class="out" style="margin:20px; border:1px solid #000; background: red;">
<p>Count mouse leave event</p>
<div class="in" style="background: green; margin: 10px auto; width: 50%;">
<p>mouse over here should not trigger the counter.</p>
</div>
<p>0</p>
</div>
<ul id="log"></ul> <ul id="log"></ul>
<script type='text/javascript'> <script type='text/javascript'>
@ -280,10 +270,6 @@
jQuery("#boundSubmit").blink(); jQuery("#boundSubmit").blink();
}); });
var n = 0;
$("div.out").live("mouseleave", function() {
$("p:last", this).text(++n);
});
</script> </script>
</body> </body>
</html> </html>

View file

@ -28,13 +28,10 @@
<script src="../src/offset.js"></script> <script src="../src/offset.js"></script>
<script src="../src/dimensions.js"></script> <script src="../src/dimensions.js"></script>
<script src="data/versioncheck.js"></script>
<script src="qunit/qunit/qunit.js"></script> <script src="qunit/qunit/qunit.js"></script>
<script src="data/testrunner.js"></script> <script src="data/testrunner.js"></script>
<script src="unit/core.js"></script> <script src="unit/core.js"></script>
<script src="unit/support.js"></script>
<script src="unit/deferred.js"></script> <script src="unit/deferred.js"></script>
<script src="unit/data.js"></script> <script src="unit/data.js"></script>
<script src="unit/queue.js"></script> <script src="unit/queue.js"></script>
@ -51,9 +48,7 @@
</head> </head>
<body id="body"> <body id="body">
<h1 id="qunit-header"><a href="/jquery/test/index.html">jQuery Test Suite</a> <h1 id="qunit-header">jQuery Test Suite</h1>
<a href="?jquery=min">(minified)</a>
</h1>
<h2 id="qunit-banner"></h2> <h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div> <div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2> <h2 id="qunit-userAgent"></h2>
@ -63,10 +58,10 @@
<div id="nothiddendiv" style="height:1px;background:white;" class="nothiddendiv"> <div id="nothiddendiv" style="height:1px;background:white;" class="nothiddendiv">
<div id="nothiddendivchild"></div> <div id="nothiddendivchild"></div>
</div> </div>
<!-- this iframe is outside the #qunit-fixture so it won't reload constantly wasting time, but it means the tests must be "safe" and clean up after themselves --> <!-- this iframe is outside the #main so it won't reload constantly wasting time, but it means the tests must be "safe" and clean up after themselves -->
<iframe id="loadediframe" name="loadediframe" style="display:none;" src="data/iframe.html"></iframe> <iframe id="loadediframe" name="loadediframe" style="display:none;" src="data/iframe.html"></iframe>
<dl id="dl" style="position:absolute;top:-32767px;left:-32767px;width:1px"> <dl id="dl" style="position:absolute;top:-32767px;left:-32767px;">
<div id="qunit-fixture"> <div id="main">
<p id="firstp">See <a id="simon1" href="http://simon.incutio.com/archive/2003/03/25/#getElementsBySelector" rel="bookmark">this blog entry</a> for more information.</p> <p id="firstp">See <a id="simon1" href="http://simon.incutio.com/archive/2003/03/25/#getElementsBySelector" rel="bookmark">this blog entry</a> for more information.</p>
<p id="ap"> <p id="ap">
Here are some links in a normal paragraph: <a id="google" href="http://www.google.com/" title="Google!">Google</a>, Here are some links in a normal paragraph: <a id="google" href="http://www.google.com/" title="Google!">Google</a>,
@ -208,10 +203,6 @@ Z</textarea>
<select name="D4" disabled="disabled"> <select name="D4" disabled="disabled">
<option selected="selected" value="NO">NO</option> <option selected="selected" value="NO">NO</option>
</select> </select>
<input id="list-test" type="text" />
<datalist id="datalist">
<option value="option"></option>
</datalist>
</form> </form>
<div id="moretests"> <div id="moretests">
<form> <form>

@ -1 +1 @@
Subproject commit d4f23f8a882d13b71768503e2db9fa33ef169ba0 Subproject commit d404faf8f587fcbe6b8907943022e6318dd51e0c

View file

@ -1,13 +1,13 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<!-- <!--
Test for jQuery.holdReady. Needs to be a Test for jQuery.readyWait. Needs to be a
standalone test since it deals with DOM standalone test since it deals with DOM
ready. ready.
--> -->
<head> <head>
<title> <title>
jQuery.holdReady Test jQuery.readyWait Test
</title> </title>
<style> <style>
div { margin-top: 10px; } div { margin-top: 10px; }
@ -52,17 +52,15 @@
</head> </head>
<body> <body>
<h1> <h1>
jQuery.holdReady Test jQuery.readyWait Test
</h1> </h1>
<p> <p>
This is a test page for jQuery.readyWait and jQuery.holdReady, This is a test page for jQuery.readyWait, that was
see added due to this ticket
<a href="http://bugs.jquery.com/ticket/6781">#6781</a> <a href="http://bugs.jquery.com/ticket/6781">#6781</a>.
and
<a href="http://bugs.jquery.com/ticket/8803">#8803</a>.
</p> </p>
<p> <p>
Test for jQuery.holdReady, which can be used Test for jQuery.readyWait, which can be used
by plugins and other scripts to indicate something by plugins and other scripts to indicate something
important to the page is still loading and needs important to the page is still loading and needs
to block the DOM ready callbacks that are registered to block the DOM ready callbacks that are registered
@ -70,7 +68,7 @@
</p> </p>
<p> <p>
Script loaders are the most likely kind of script Script loaders are the most likely kind of script
to use jQuery.holdReady, but it could be used by to use jQuery.readyWait, but it could be used by
other things like a script that loads a CSS file other things like a script that loads a CSS file
and wants to pause the DOM ready callbacks. and wants to pause the DOM ready callbacks.
</p> </p>

View file

@ -14,7 +14,7 @@ test("jQuery.ajax() - success callbacks", function() {
stop(); stop();
jQuery("#foo").ajaxStart(function(){ jQuery('#foo').ajaxStart(function(){
ok( true, "ajaxStart" ); ok( true, "ajaxStart" );
}).ajaxStop(function(){ }).ajaxStop(function(){
ok( true, "ajaxStop" ); ok( true, "ajaxStop" );
@ -46,7 +46,7 @@ test("jQuery.ajax() - success callbacks - (url, options) syntax", function() {
stop(); stop();
setTimeout(function(){ setTimeout(function(){
jQuery("#foo").ajaxStart(function(){ jQuery('#foo').ajaxStart(function(){
ok( true, "ajaxStart" ); ok( true, "ajaxStart" );
}).ajaxStop(function(){ }).ajaxStop(function(){
ok( true, "ajaxStop" ); ok( true, "ajaxStop" );
@ -78,7 +78,7 @@ test("jQuery.ajax() - success callbacks (late binding)", function() {
stop(); stop();
setTimeout(function(){ setTimeout(function(){
jQuery("#foo").ajaxStart(function(){ jQuery('#foo').ajaxStart(function(){
ok( true, "ajaxStart" ); ok( true, "ajaxStart" );
}).ajaxStop(function(){ }).ajaxStop(function(){
ok( true, "ajaxStop" ); ok( true, "ajaxStop" );
@ -111,7 +111,7 @@ test("jQuery.ajax() - success callbacks (oncomplete binding)", function() {
stop(); stop();
setTimeout(function(){ setTimeout(function(){
jQuery("#foo").ajaxStart(function(){ jQuery('#foo').ajaxStart(function(){
ok( true, "ajaxStart" ); ok( true, "ajaxStart" );
}).ajaxStop(function(){ }).ajaxStop(function(){
ok( true, "ajaxStop" ); ok( true, "ajaxStop" );
@ -147,7 +147,7 @@ test("jQuery.ajax() - success callbacks (very late binding)", function() {
stop(); stop();
setTimeout(function(){ setTimeout(function(){
jQuery("#foo").ajaxStart(function(){ jQuery('#foo').ajaxStart(function(){
ok( true, "ajaxStart" ); ok( true, "ajaxStart" );
}).ajaxStop(function(){ }).ajaxStop(function(){
ok( true, "ajaxStop" ); ok( true, "ajaxStop" );
@ -214,7 +214,7 @@ test("jQuery.ajax() - error callbacks", function() {
expect( 8 ); expect( 8 );
stop(); stop();
jQuery("#foo").ajaxStart(function(){ jQuery('#foo').ajaxStart(function(){
ok( true, "ajaxStart" ); ok( true, "ajaxStart" );
}).ajaxStop(function(){ }).ajaxStop(function(){
ok( true, "ajaxStop" ); ok( true, "ajaxStop" );
@ -247,10 +247,10 @@ test( "jQuery.ajax - multiple method signatures introduced in 1.5 ( #8107)", fun
stop(); stop();
jQuery.when( jQuery.when(
jQuery.ajax().success(function() { ok( true, "With no arguments" ); }), jQuery.ajax().success(function() { ok( true, 'With no arguments' ); }),
jQuery.ajax("data/name.html").success(function() { ok( true, "With only string URL argument" ); }), jQuery.ajax('data/name.html').success(function() { ok( true, 'With only string URL argument' ); }),
jQuery.ajax("data/name.html", {} ).success(function() { ok( true, "With string URL param and map" ); }), jQuery.ajax('data/name.html', {} ).success(function() { ok( true, 'With string URL param and map' ); }),
jQuery.ajax({ url: "data/name.html"} ).success(function() { ok( true, "With only map" ); }) jQuery.ajax({ url: 'data/name.html'} ).success(function() { ok( true, 'With only map' ); })
).then( start, start ); ).then( start, start );
}); });
@ -321,40 +321,25 @@ test("jQuery.ajax() - responseText on error", function() {
test(".ajax() - retry with jQuery.ajax( this )", function() { test(".ajax() - retry with jQuery.ajax( this )", function() {
expect( 2 ); expect( 1 );
stop(); stop();
var firstTime = true, var firstTime = 1;
previousUrl;
jQuery.ajax({ jQuery.ajax({
url: url("data/errorWithText.php"), url: url("data/errorWithText.php"),
error: function() { error: function() {
if ( firstTime ) { if ( firstTime ) {
firstTime = false; firstTime = 0;
jQuery.ajax( this ); jQuery.ajax( this );
} else { } else {
ok( true , "Test retrying with jQuery.ajax(this) works" ); ok( true , "Test retrying with jQuery.ajax(this) works" );
jQuery.ajax({
url: url("data/errorWithText.php"),
data: { x: 1 },
beforeSend: function() {
if ( !previousUrl ) {
previousUrl = this.url;
} else {
strictEqual( this.url , previousUrl, "url parameters are not re-appended" );
start(); start();
return false;
}
},
error: function() {
jQuery.ajax( this );
}
});
} }
} }
}); });
}); });
test(".ajax() - headers" , function() { test(".ajax() - headers" , function() {
@ -363,7 +348,7 @@ test(".ajax() - headers" , function() {
stop(); stop();
jQuery("#foo").ajaxSend(function( evt, xhr ) { jQuery('#foo').ajaxSend(function( evt, xhr ) {
xhr.setRequestHeader( "ajax-send", "test" ); xhr.setRequestHeader( "ajax-send", "test" );
}); });
@ -524,7 +509,7 @@ test("jQuery ajax - cross-domain detection", function() {
jQuery.ajax({ jQuery.ajax({
dataType: "jsonp", dataType: "jsonp",
url: "app:/path", url: 'app:/path',
beforeSend: function( _ , s ) { beforeSend: function( _ , s ) {
ok( s.crossDomain , "Adobe AIR app:/ URL detected as cross-domain" ); ok( s.crossDomain , "Adobe AIR app:/ URL detected as cross-domain" );
return false; return false;
@ -533,7 +518,7 @@ test("jQuery ajax - cross-domain detection", function() {
jQuery.ajax({ jQuery.ajax({
dataType: "jsonp", dataType: "jsonp",
url: loc.protocol + "//somewebsitethatdoesnotexist-656329477541.com:" + ( loc.port || 80 ), url: loc.protocol + '//somewebsitethatdoesnotexist-656329477541.com:' + ( loc.port || 80 ),
beforeSend: function( _ , s ) { beforeSend: function( _ , s ) {
ok( s.crossDomain , "Test different hostnames are detected as cross-domain" ); ok( s.crossDomain , "Test different hostnames are detected as cross-domain" );
return false; return false;
@ -574,7 +559,7 @@ test(".load() - 404 error callbacks", function() {
expect( 6 ); expect( 6 );
stop(); stop();
jQuery("#foo").ajaxStart(function(){ jQuery('#foo').ajaxStart(function(){
ok( true, "ajaxStart" ); ok( true, "ajaxStart" );
}).ajaxStop(function(){ }).ajaxStop(function(){
ok( true, "ajaxStop" ); ok( true, "ajaxStop" );
@ -598,7 +583,7 @@ test("jQuery.ajax() - abort", function() {
expect( 8 ); expect( 8 );
stop(); stop();
jQuery("#foo").ajaxStart(function(){ jQuery('#foo').ajaxStart(function(){
ok( true, "ajaxStart" ); ok( true, "ajaxStart" );
}).ajaxStop(function(){ }).ajaxStop(function(){
ok( true, "ajaxStop" ); ok( true, "ajaxStop" );
@ -643,7 +628,7 @@ test("Ajax events with context", function() {
}; };
} }
jQuery("#foo").add(context) jQuery('#foo').add(context)
.ajaxSend(event) .ajaxSend(event)
.ajaxComplete(event) .ajaxComplete(event)
.ajaxError(event) .ajaxError(event)
@ -665,7 +650,7 @@ test("Ajax events with context", function() {
complete: function(){ complete: function(){
callback("complete").call(this); callback("complete").call(this);
jQuery("#foo").add(context).unbind(); jQuery('#foo').add(context).unbind();
jQuery.ajax({ jQuery.ajax({
url: url("data/404.html"), url: url("data/404.html"),
@ -749,7 +734,7 @@ test("jQuery.ajax() - disabled globals", function() {
expect( 3 ); expect( 3 );
stop(); stop();
jQuery("#foo").ajaxStart(function(){ jQuery('#foo').ajaxStart(function(){
ok( false, "ajaxStart" ); ok( false, "ajaxStart" );
}).ajaxStop(function(){ }).ajaxStop(function(){
ok( false, "ajaxStop" ); ok( false, "ajaxStop" );
@ -783,9 +768,9 @@ test("jQuery.ajax - xml: non-namespace elements inside namespaced elements", fun
url: url("data/with_fries.xml"), url: url("data/with_fries.xml"),
dataType: "xml", dataType: "xml",
success: function(resp) { success: function(resp) {
equals( jQuery("properties", resp).length, 1, "properties in responseXML" ); equals( jQuery("properties", resp).length, 1, 'properties in responseXML' );
equals( jQuery("jsconf", resp).length, 1, "jsconf in responseXML" ); equals( jQuery("jsconf", resp).length, 1, 'jsconf in responseXML' );
equals( jQuery("thing", resp).length, 2, "things in responseXML" ); equals( jQuery("thing", resp).length, 2, 'things in responseXML' );
start(); start();
} }
}); });
@ -798,9 +783,9 @@ test("jQuery.ajax - xml: non-namespace elements inside namespaced elements (over
url: url("data/with_fries_over_jsonp.php"), url: url("data/with_fries_over_jsonp.php"),
dataType: "jsonp xml", dataType: "jsonp xml",
success: function(resp) { success: function(resp) {
equals( jQuery("properties", resp).length, 1, "properties in responseXML" ); equals( jQuery("properties", resp).length, 1, 'properties in responseXML' );
equals( jQuery("jsconf", resp).length, 1, "jsconf in responseXML" ); equals( jQuery("jsconf", resp).length, 1, 'jsconf in responseXML' );
equals( jQuery("thing", resp).length, 2, "things in responseXML" ); equals( jQuery("thing", resp).length, 2, 'things in responseXML' );
start(); start();
}, },
error: function(_1,_2,error) { error: function(_1,_2,error) {
@ -819,7 +804,7 @@ test("jQuery.ajax - HEAD requests", function() {
type: "HEAD", type: "HEAD",
success: function(data, status, xhr){ success: function(data, status, xhr){
var h = xhr.getAllResponseHeaders(); var h = xhr.getAllResponseHeaders();
ok( /Date/i.test(h), "No Date in HEAD response" ); ok( /Date/i.test(h), 'No Date in HEAD response' );
jQuery.ajax({ jQuery.ajax({
url: url("data/name.html"), url: url("data/name.html"),
@ -827,7 +812,7 @@ test("jQuery.ajax - HEAD requests", function() {
type: "HEAD", type: "HEAD",
success: function(data, status, xhr){ success: function(data, status, xhr){
var h = xhr.getAllResponseHeaders(); var h = xhr.getAllResponseHeaders();
ok( /Date/i.test(h), "No Date in HEAD response with data" ); ok( /Date/i.test(h), 'No Date in HEAD response with data' );
start(); start();
} }
}); });
@ -906,8 +891,8 @@ test("jQuery.ajax - dataType html", function() {
stop(); stop();
var verifyEvaluation = function() { var verifyEvaluation = function() {
equals( testFoo, "foo", "Check if script was evaluated for datatype html" ); equals( testFoo, "foo", 'Check if script was evaluated for datatype html' );
equals( foobar, "bar", "Check if script src was evaluated for datatype html" ); equals( foobar, "bar", 'Check if script src was evaluated for datatype html' );
start(); start();
}; };
@ -917,7 +902,7 @@ test("jQuery.ajax - dataType html", function() {
url: url("data/test.html"), url: url("data/test.html"),
success: function(data) { success: function(data) {
jQuery("#ap").html(data); jQuery("#ap").html(data);
ok( data.match(/^html text/), "Check content for datatype html" ); ok( data.match(/^html text/), 'Check content for datatype html' );
setTimeout(verifyEvaluation, 600); setTimeout(verifyEvaluation, 600);
} }
}); });
@ -928,40 +913,40 @@ test("serialize()", function() {
// Add html5 elements only for serialize because selector can't yet find them on non-html5 browsers // Add html5 elements only for serialize because selector can't yet find them on non-html5 browsers
jQuery("#search").after( jQuery("#search").after(
"<input type='email' id='html5email' name='email' value='dave@jquery.com' />"+ '<input type="email" id="html5email" name="email" value="dave@jquery.com" />'+
"<input type='number' id='html5number' name='number' value='43' />" '<input type="number" id="html5number" name="number" value="43" />'
); );
equals( jQuery("#form").serialize(), equals( jQuery('#form').serialize(),
"action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&search=search&email=dave%40jquery.com&number=43&select1=&select2=3&select3=1&select3=2&select5=3", "action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&search=search&email=dave%40jquery.com&number=43&select1=&select2=3&select3=1&select3=2&select5=3",
"Check form serialization as query string"); 'Check form serialization as query string');
equals( jQuery("#form :input").serialize(), equals( jQuery('#form :input').serialize(),
"action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&search=search&email=dave%40jquery.com&number=43&select1=&select2=3&select3=1&select3=2&select5=3", "action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&search=search&email=dave%40jquery.com&number=43&select1=&select2=3&select3=1&select3=2&select5=3",
"Check input serialization as query string"); 'Check input serialization as query string');
equals( jQuery("#testForm").serialize(), equals( jQuery('#testForm').serialize(),
"T3=%3F%0D%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=", 'T3=%3F%0D%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=',
"Check form serialization as query string"); 'Check form serialization as query string');
equals( jQuery("#testForm :input").serialize(), equals( jQuery('#testForm :input').serialize(),
"T3=%3F%0D%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=", 'T3=%3F%0D%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=',
"Check input serialization as query string"); 'Check input serialization as query string');
equals( jQuery("#form, #testForm").serialize(), equals( jQuery('#form, #testForm').serialize(),
"action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&search=search&email=dave%40jquery.com&number=43&select1=&select2=3&select3=1&select3=2&select5=3&T3=%3F%0D%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=", "action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&search=search&email=dave%40jquery.com&number=43&select1=&select2=3&select3=1&select3=2&select5=3&T3=%3F%0D%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=",
"Multiple form serialization as query string"); 'Multiple form serialization as query string');
/* Temporarily disabled. Opera 10 has problems with form serialization. /* Temporarily disabled. Opera 10 has problems with form serialization.
equals( jQuery("#form, #testForm :input").serialize(), equals( jQuery('#form, #testForm :input').serialize(),
"action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&search=search&email=dave%40jquery.com&number=43&select1=&select2=3&select3=1&select3=2&T3=%3F%0D%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=", "action=Test&radio2=on&check=on&hidden=&foo%5Bbar%5D=&name=name&search=search&email=dave%40jquery.com&number=43&select1=&select2=3&select3=1&select3=2&T3=%3F%0D%0AZ&H1=x&H2=&PWD=&T1=&T2=YES&My+Name=me&S1=abc&S3=YES&S4=",
"Mixed form/input serialization as query string"); 'Mixed form/input serialization as query string');
*/ */
jQuery("#html5email, #html5number").remove(); jQuery("#html5email, #html5number").remove();
}); });
test("jQuery.param()", function() { test("jQuery.param()", function() {
expect(21); expect(24);
equals( !jQuery.ajaxSettings.traditional, true, "traditional flag, falsy by default" ); equals( !jQuery.ajaxSettings.traditional, true, "traditional flag, falsy by default" );
@ -971,13 +956,13 @@ test("jQuery.param()", function() {
params = {someName: [1, 2, 3], regularThing: "blah" }; params = {someName: [1, 2, 3], regularThing: "blah" };
equals( jQuery.param(params), "someName%5B%5D=1&someName%5B%5D=2&someName%5B%5D=3&regularThing=blah", "with array" ); equals( jQuery.param(params), "someName%5B%5D=1&someName%5B%5D=2&someName%5B%5D=3&regularThing=blah", "with array" );
params = {foo: ["a", "b", "c"]}; params = {foo: ['a', 'b', 'c']};
equals( jQuery.param(params), "foo%5B%5D=a&foo%5B%5D=b&foo%5B%5D=c", "with array of strings" ); equals( jQuery.param(params), "foo%5B%5D=a&foo%5B%5D=b&foo%5B%5D=c", "with array of strings" );
params = {foo: ["baz", 42, "All your base are belong to us"] }; params = {foo: ["baz", 42, "All your base are belong to us"] };
equals( jQuery.param(params), "foo%5B%5D=baz&foo%5B%5D=42&foo%5B%5D=All+your+base+are+belong+to+us", "more array" ); equals( jQuery.param(params), "foo%5B%5D=baz&foo%5B%5D=42&foo%5B%5D=All+your+base+are+belong+to+us", "more array" );
params = {foo: { bar: "baz", beep: 42, quux: "All your base are belong to us" } }; params = {foo: { bar: 'baz', beep: 42, quux: 'All your base are belong to us' } };
equals( jQuery.param(params), "foo%5Bbar%5D=baz&foo%5Bbeep%5D=42&foo%5Bquux%5D=All+your+base+are+belong+to+us", "even more arrays" ); equals( jQuery.param(params), "foo%5Bbar%5D=baz&foo%5Bbeep%5D=42&foo%5Bquux%5D=All+your+base+are+belong+to+us", "even more arrays" );
params = { a:[1,2], b:{ c:3, d:[4,5], e:{ x:[6], y:7, z:[8,9] }, f:true, g:false, h:undefined }, i:[10,11], j:true, k:false, l:[undefined,0], m:"cowboy hat?" }; params = { a:[1,2], b:{ c:3, d:[4,5], e:{ x:[6], y:7, z:[8,9] }, f:true, g:false, h:undefined }, i:[10,11], j:true, k:false, l:[undefined,0], m:"cowboy hat?" };
@ -989,7 +974,12 @@ test("jQuery.param()", function() {
params = { a:[1,2], b:{ c:3, d:[4,5], e:{ x:[6], y:7, z:[8,9] }, f:true, g:false, h:undefined }, i:[10,11], j:true, k:false, l:[undefined,0], m:"cowboy hat?" }; params = { a:[1,2], b:{ c:3, d:[4,5], e:{ x:[6], y:7, z:[8,9] }, f:true, g:false, h:undefined }, i:[10,11], j:true, k:false, l:[undefined,0], m:"cowboy hat?" };
equals( jQuery.param(params,true), "a=1&a=2&b=%5Bobject+Object%5D&i=10&i=11&j=true&k=false&l=undefined&l=0&m=cowboy+hat%3F", "huge structure, forced traditional" ); equals( jQuery.param(params,true), "a=1&a=2&b=%5Bobject+Object%5D&i=10&i=11&j=true&k=false&l=undefined&l=0&m=cowboy+hat%3F", "huge structure, forced traditional" );
equals( decodeURIComponent( jQuery.param({ a: [1,2,3], "b[]": [4,5,6], "c[d]": [7,8,9], e: { f: [10], g: [11,12], h: 13 } }) ), "a[]=1&a[]=2&a[]=3&b[]=4&b[]=5&b[]=6&c[d][]=7&c[d][]=8&c[d][]=9&e[f][]=10&e[g][]=11&e[g][]=12&e[h]=13", "Make sure params are not double-encoded." ); equals( decodeURIComponent( jQuery.param({ a: [1,2,3], 'b[]': [4,5,6], 'c[d]': [7,8,9], e: { f: [10], g: [11,12], h: 13 } }) ), "a[]=1&a[]=2&a[]=3&b[]=4&b[]=5&b[]=6&c[d][]=7&c[d][]=8&c[d][]=9&e[f][]=10&e[g][]=11&e[g][]=12&e[h]=13", "Make sure params are not double-encoded." );
// Make sure empty arrays and objects are handled #6481
equals( jQuery.param({"foo": {"bar": []} }), "foo%5Bbar%5D=", "Empty array param" );
equals( jQuery.param({"foo": {"bar": [], foo: 1} }), "foo%5Bbar%5D=&foo%5Bfoo%5D=1", "Empty array param" );
equals( jQuery.param({"foo": {"bar": {}} }), "foo%5Bbar%5D=", "Empty object param" );
// #7945 // #7945
equals( jQuery.param({"jquery": "1.4.2"}), "jquery=1.4.2", "Check that object with a jQuery property get serialized correctly" ); equals( jQuery.param({"jquery": "1.4.2"}), "jquery=1.4.2", "Check that object with a jQuery property get serialized correctly" );
@ -1002,7 +992,7 @@ test("jQuery.param()", function() {
params = {someName: [1, 2, 3], regularThing: "blah" }; params = {someName: [1, 2, 3], regularThing: "blah" };
equals( jQuery.param(params), "someName=1&someName=2&someName=3&regularThing=blah", "with array" ); equals( jQuery.param(params), "someName=1&someName=2&someName=3&regularThing=blah", "with array" );
params = {foo: ["a", "b", "c"]}; params = {foo: ['a', 'b', 'c']};
equals( jQuery.param(params), "foo=a&foo=b&foo=c", "with array of strings" ); equals( jQuery.param(params), "foo=a&foo=b&foo=c", "with array of strings" );
params = {"foo[]":["baz", 42, "All your base are belong to us"]}; params = {"foo[]":["baz", 42, "All your base are belong to us"]};
@ -1023,7 +1013,7 @@ test("jQuery.param()", function() {
params = { param1: null }; params = { param1: null };
equals( jQuery.param(params,false), "param1=null", "Make sure that null params aren't traversed." ); equals( jQuery.param(params,false), "param1=null", "Make sure that null params aren't traversed." );
params = {"test": {"length": 3, "foo": "bar"} }; params = {'test': {'length': 3, 'foo': 'bar'} };
equals( jQuery.param( params, false ), "test%5Blength%5D=3&test%5Bfoo%5D=bar", "Sub-object with a length property" ); equals( jQuery.param( params, false ), "test%5Blength%5D=3&test%5Bfoo%5D=bar", "Sub-object with a length property" );
}); });
@ -1054,10 +1044,10 @@ test("pass-through request object", function() {
errorCount++; errorCount++;
errorEx += ": " + xml.status; errorEx += ": " + xml.status;
}); });
jQuery("#foo").one("ajaxStop", function () { jQuery("#foo").one('ajaxStop', function () {
equals(successCount, 5, "Check all ajax calls successful"); equals(successCount, 5, "Check all ajax calls successful");
equals(errorCount, 0, "Check no ajax errors (status" + errorEx + ")"); equals(errorCount, 0, "Check no ajax errors (status" + errorEx + ")");
jQuery("#foo").unbind("ajaxError"); jQuery("#foo").unbind('ajaxError');
start(); start();
}); });
@ -1111,17 +1101,17 @@ test("global ajaxSettings", function() {
var orig = { url: "data/with_fries.xml" }; var orig = { url: "data/with_fries.xml" };
var t; var t;
jQuery.ajaxSetup({ data: {foo: "bar", bar: "BAR"} }); jQuery.ajaxSetup({ data: {foo: 'bar', bar: 'BAR'} });
t = jQuery.extend({}, orig); t = jQuery.extend({}, orig);
t.data = {}; t.data = {};
jQuery.ajax(t); jQuery.ajax(t);
ok( t.url.indexOf("foo") > -1 && t.url.indexOf("bar") > -1, "Check extending {}" ); ok( t.url.indexOf('foo') > -1 && t.url.indexOf('bar') > -1, "Check extending {}" );
t = jQuery.extend({}, orig); t = jQuery.extend({}, orig);
t.data = { zoo: "a", ping: "b" }; t.data = { zoo: 'a', ping: 'b' };
jQuery.ajax(t); jQuery.ajax(t);
ok( t.url.indexOf("ping") > -1 && t.url.indexOf("zoo") > -1 && t.url.indexOf("foo") > -1 && t.url.indexOf("bar") > -1, "Check extending { zoo: "a", ping: "b" }" ); ok( t.url.indexOf('ping') > -1 && t.url.indexOf('zoo') > -1 && t.url.indexOf('foo') > -1 && t.url.indexOf('bar') > -1, "Check extending { zoo: 'a', ping: 'b' }" );
jQuery.ajaxSettings = tmp; jQuery.ajaxSettings = tmp;
}); });
@ -1130,13 +1120,13 @@ test("global ajaxSettings", function() {
test("load(String)", function() { test("load(String)", function() {
expect(1); expect(1);
stop(); // check if load can be called with only url stop(); // check if load can be called with only url
jQuery("#first").load("data/name.html", start); jQuery('#first').load("data/name.html", start);
}); });
test("load('url selector')", function() { test("load('url selector')", function() {
expect(1); expect(1);
stop(); // check if load can be called with only url stop(); // check if load can be called with only url
jQuery("#first").load("data/test3.html div.user", function(){ jQuery('#first').load("data/test3.html div.user", function(){
equals( jQuery(this).children("div").length, 2, "Verify that specific elements were injected" ); equals( jQuery(this).children("div").length, 2, "Verify that specific elements were injected" );
start(); start();
}); });
@ -1152,14 +1142,14 @@ test("load(String, Function) with ajaxSetup on dataType json, see #2046", functi
jQuery.ajaxSetup({ dataType: "" }); jQuery.ajaxSetup({ dataType: "" });
start(); start();
}); });
jQuery("#first").load("data/test3.html"); jQuery('#first').load("data/test3.html");
}); });
test("load(String, Function) - simple: inject text into DOM", function() { test("load(String, Function) - simple: inject text into DOM", function() {
expect(2); expect(2);
stop(); stop();
jQuery("#first").load(url("data/name.html"), function() { jQuery('#first').load(url("data/name.html"), function() {
ok( /^ERROR/.test(jQuery("#first").text()), "Check if content was injected into the DOM" ); ok( /^ERROR/.test(jQuery('#first').text()), 'Check if content was injected into the DOM' );
start(); start();
}); });
}); });
@ -1169,15 +1159,15 @@ test("load(String, Function) - check scripts", function() {
stop(); stop();
var verifyEvaluation = function() { var verifyEvaluation = function() {
equals( foobar, "bar", "Check if script src was evaluated after load" ); equals( foobar, "bar", 'Check if script src was evaluated after load' );
equals( jQuery("#ap").html(), "bar", "Check if script evaluation has modified DOM"); equals( jQuery('#ap').html(), 'bar', 'Check if script evaluation has modified DOM');
start(); start();
}; };
jQuery("#first").load(url("data/test.html"), function() { jQuery('#first').load(url('data/test.html'), function() {
ok( jQuery("#first").html().match(/^html text/), "Check content after loading html" ); ok( jQuery('#first').html().match(/^html text/), 'Check content after loading html' );
equals( jQuery("#foo").html(), "foo", "Check if script evaluation has modified DOM"); equals( jQuery('#foo').html(), 'foo', 'Check if script evaluation has modified DOM');
equals( testFoo, "foo", "Check if script was evaluated after load" ); equals( testFoo, "foo", 'Check if script was evaluated after load' );
setTimeout(verifyEvaluation, 600); setTimeout(verifyEvaluation, 600);
}); });
}); });
@ -1186,9 +1176,9 @@ test("load(String, Function) - check file with only a script tag", function() {
expect(3); expect(3);
stop(); stop();
jQuery("#first").load(url("data/test2.html"), function() { jQuery('#first').load(url('data/test2.html'), function() {
equals( jQuery("#foo").html(), "foo", "Check if script evaluation has modified DOM"); equals( jQuery('#foo').html(), 'foo', 'Check if script evaluation has modified DOM');
equals( testFoo, "foo", "Check if script was evaluated after load" ); equals( testFoo, "foo", 'Check if script was evaluated after load' );
start(); start();
}); });
@ -1210,10 +1200,10 @@ test("load(String, Object, Function)", function() {
expect(2); expect(2);
stop(); stop();
jQuery("<div />").load(url("data/params_html.php"), { foo: 3, bar: "ok" }, function() { jQuery('<div />').load(url('data/params_html.php'), { foo:3, bar:'ok' }, function() {
var $post = jQuery(this).find("#post"); var $post = jQuery(this).find('#post');
equals( $post.find("#foo").text(), "3", "Check if a hash of data is passed correctly"); equals( $post.find('#foo').text(), '3', 'Check if a hash of data is passed correctly');
equals( $post.find("#bar").text(), "ok", "Check if a hash of data is passed correctly"); equals( $post.find('#bar').text(), 'ok', 'Check if a hash of data is passed correctly');
start(); start();
}); });
}); });
@ -1222,10 +1212,10 @@ test("load(String, String, Function)", function() {
expect(2); expect(2);
stop(); stop();
jQuery("<div />").load(url("data/params_html.php"), "foo=3&bar=ok", function() { jQuery('<div />').load(url('data/params_html.php'), 'foo=3&bar=ok', function() {
var $get = jQuery(this).find("#get"); var $get = jQuery(this).find('#get');
equals( $get.find("#foo").text(), "3", "Check if a string of data is passed correctly"); equals( $get.find('#foo').text(), '3', 'Check if a string of data is passed correctly');
equals( $get.find("#bar").text(), "ok", "Check if a of data is passed correctly"); equals( $get.find('#bar').text(), 'ok', 'Check if a of data is passed correctly');
start(); start();
}); });
}); });
@ -1236,8 +1226,8 @@ test("jQuery.get(String, Function) - data in ajaxSettings (#8277)", function() {
jQuery.ajaxSetup({ jQuery.ajaxSetup({
data: "helloworld" data: "helloworld"
}); });
jQuery.get(url("data/echoQuery.php"), function(data) { jQuery.get(url('data/echoQuery.php'), function(data) {
ok( /helloworld$/.test( data ), "Data from ajaxSettings was used"); ok( /helloworld$/.test( data ), 'Data from ajaxSettings was used');
jQuery.ajaxSetup({ jQuery.ajaxSetup({
data: null data: null
}); });
@ -1248,13 +1238,13 @@ test("jQuery.get(String, Function) - data in ajaxSettings (#8277)", function() {
test("jQuery.get(String, Hash, Function) - parse xml and use text() on nodes", function() { test("jQuery.get(String, Hash, Function) - parse xml and use text() on nodes", function() {
expect(2); expect(2);
stop(); stop();
jQuery.get(url("data/dashboard.xml"), function(xml) { jQuery.get(url('data/dashboard.xml'), function(xml) {
var content = []; var content = [];
jQuery("tab", xml).each(function() { jQuery('tab', xml).each(function() {
content.push(jQuery(this).text()); content.push(jQuery(this).text());
}); });
equals( content[0], "blabla", "Check first tab"); equals( content[0], 'blabla', 'Check first tab');
equals( content[1], "blublu", "Check second tab"); equals( content[1], 'blublu', 'Check second tab');
start(); start();
}); });
}); });
@ -1263,7 +1253,7 @@ test("jQuery.getScript(String, Function) - with callback", function() {
expect(3); expect(3);
stop(); stop();
jQuery.getScript(url("data/test.js"), function( data, _, jqXHR ) { jQuery.getScript(url("data/test.js"), function( data, _, jqXHR ) {
equals( foobar, "bar", "Check if script was evaluated" ); equals( foobar, "bar", 'Check if script was evaluated' );
strictEqual( data, jqXHR.responseText, "Same-domain script requests returns the source of the script (#8082)" ); strictEqual( data, jqXHR.responseText, "Same-domain script requests returns the source of the script (#8082)" );
setTimeout(start, 100); setTimeout(start, 100);
}); });
@ -1610,7 +1600,7 @@ test("jQuery.ajax() - malformed JSON", function() {
}, },
error: function(xhr, msg, detailedMsg) { error: function(xhr, msg, detailedMsg) {
equals( "parsererror", msg, "A parse error occurred." ); equals( "parsererror", msg, "A parse error occurred." );
ok( /^(Invalid|SyntaxError|exception)/i.test(detailedMsg), "Detailed parsererror message provided" ); ok( /^Invalid JSON/.test(detailedMsg), "Detailed parsererror message provided" );
start(); start();
} }
}); });
@ -1646,10 +1636,10 @@ test("jQuery.ajax() - json by content-type", function() {
data: { header: "json", json: "array" }, data: { header: "json", json: "array" },
success: function( json ) { success: function( json ) {
ok( json.length >= 2, "Check length"); ok( json.length >= 2, "Check length");
equals( json[0].name, "John", "Check JSON: first, name" ); equals( json[0].name, 'John', 'Check JSON: first, name' );
equals( json[0].age, 21, "Check JSON: first, age" ); equals( json[0].age, 21, 'Check JSON: first, age' );
equals( json[1].name, "Peter", "Check JSON: second, name" ); equals( json[1].name, 'Peter', 'Check JSON: second, name' );
equals( json[1].age, 25, "Check JSON: second, age" ); equals( json[1].age, 25, 'Check JSON: second, age' );
start(); start();
} }
}); });
@ -1670,10 +1660,10 @@ test("jQuery.ajax() - json by content-type disabled with options", function() {
equals( typeof text , "string" , "json wasn't auto-determined" ); equals( typeof text , "string" , "json wasn't auto-determined" );
var json = jQuery.parseJSON( text ); var json = jQuery.parseJSON( text );
ok( json.length >= 2, "Check length"); ok( json.length >= 2, "Check length");
equals( json[0].name, "John", "Check JSON: first, name" ); equals( json[0].name, 'John', 'Check JSON: first, name' );
equals( json[0].age, 21, "Check JSON: first, age" ); equals( json[0].age, 21, 'Check JSON: first, age' );
equals( json[1].name, "Peter", "Check JSON: second, name" ); equals( json[1].name, 'Peter', 'Check JSON: second, name' );
equals( json[1].age, 25, "Check JSON: second, age" ); equals( json[1].age, 25, 'Check JSON: second, age' );
start(); start();
} }
}); });
@ -1684,10 +1674,10 @@ test("jQuery.getJSON(String, Hash, Function) - JSON array", function() {
stop(); stop();
jQuery.getJSON(url("data/json.php"), {json: "array"}, function(json) { jQuery.getJSON(url("data/json.php"), {json: "array"}, function(json) {
ok( json.length >= 2, "Check length"); ok( json.length >= 2, "Check length");
equals( json[0].name, "John", "Check JSON: first, name" ); equals( json[0].name, 'John', 'Check JSON: first, name' );
equals( json[0].age, 21, "Check JSON: first, age" ); equals( json[0].age, 21, 'Check JSON: first, age' );
equals( json[1].name, "Peter", "Check JSON: second, name" ); equals( json[1].name, 'Peter', 'Check JSON: second, name' );
equals( json[1].age, 25, "Check JSON: second, age" ); equals( json[1].age, 25, 'Check JSON: second, age' );
start(); start();
}); });
}); });
@ -1697,8 +1687,8 @@ test("jQuery.getJSON(String, Function) - JSON object", function() {
stop(); stop();
jQuery.getJSON(url("data/json.php"), function(json) { jQuery.getJSON(url("data/json.php"), function(json) {
if (json && json.data) { if (json && json.data) {
equals( json.data.lang, "en", "Check JSON: lang" ); equals( json.data.lang, 'en', 'Check JSON: lang' );
equals( json.data.length, 25, "Check JSON: length" ); equals( json.data.length, 25, 'Check JSON: length' );
} }
start(); start();
}); });
@ -1730,8 +1720,8 @@ test("jQuery.getJSON(String, Function) - JSON object with absolute url to local
stop(); stop();
jQuery.getJSON(url(base + "data/json.php"), function(json) { jQuery.getJSON(url(base + "data/json.php"), function(json) {
equals( json.data.lang, "en", "Check JSON: lang" ); equals( json.data.lang, 'en', 'Check JSON: lang' );
equals( json.data.length, 25, "Check JSON: length" ); equals( json.data.length, 25, 'Check JSON: length' );
start(); start();
}); });
}); });
@ -1741,23 +1731,23 @@ test("jQuery.post - data", 3, function() {
jQuery.when( jQuery.when(
jQuery.post( url( "data/name.php" ), { xml: "5-2", length: 3 }, function( xml ) { jQuery.post( url( "data/name.php" ), { xml: "5-2", length: 3 }, function( xml ) {
jQuery( "math", xml ).each( function() { jQuery( 'math', xml ).each( function() {
equals( jQuery( "calculation", this ).text(), "5-2", "Check for XML" ); equals( jQuery( 'calculation', this ).text(), '5-2', 'Check for XML' );
equals( jQuery( "result", this ).text(), "3", "Check for XML" ); equals( jQuery( 'result', this ).text(), '3', 'Check for XML' );
}); });
}), }),
jQuery.ajax({ jQuery.ajax({
url: url("data/echoData.php"), url: url('data/echoData.php'),
type: "POST", type: "POST",
data: { data: {
"test": { 'test': {
"length": 7, 'length': 7,
"foo": "bar" 'foo': 'bar'
} }
}, },
success: function( data ) { success: function( data ) {
strictEqual( data, "test%5Blength%5D=7&test%5Bfoo%5D=bar", "Check if a sub-object with a length param is serialized correctly"); strictEqual( data, 'test%5Blength%5D=7&test%5Bfoo%5D=bar', 'Check if a sub-object with a length param is serialized correctly');
} }
}) })
).then( start, start ); ).then( start, start );
@ -1770,17 +1760,17 @@ test("jQuery.post(String, Hash, Function) - simple with xml", function() {
var done = 0; var done = 0;
jQuery.post(url("data/name.php"), {xml: "5-2"}, function(xml){ jQuery.post(url("data/name.php"), {xml: "5-2"}, function(xml){
jQuery("math", xml).each(function() { jQuery('math', xml).each(function() {
equals( jQuery("calculation", this).text(), "5-2", "Check for XML" ); equals( jQuery('calculation', this).text(), '5-2', 'Check for XML' );
equals( jQuery("result", this).text(), "3", "Check for XML" ); equals( jQuery('result', this).text(), '3', 'Check for XML' );
}); });
if ( ++done === 2 ) start(); if ( ++done === 2 ) start();
}); });
jQuery.post(url("data/name.php?xml=5-2"), {}, function(xml){ jQuery.post(url("data/name.php?xml=5-2"), {}, function(xml){
jQuery("math", xml).each(function() { jQuery('math', xml).each(function() {
equals( jQuery("calculation", this).text(), "5-2", "Check for XML" ); equals( jQuery('calculation', this).text(), '5-2', 'Check for XML' );
equals( jQuery("result", this).text(), "3", "Check for XML" ); equals( jQuery('result', this).text(), '3', 'Check for XML' );
}); });
if ( ++done === 2 ) start(); if ( ++done === 2 ) start();
}); });
@ -1796,18 +1786,18 @@ test("jQuery.ajaxSetup({timeout: Number}) - with global timeout", function() {
var pass = function() { var pass = function() {
passed++; passed++;
if ( passed == 2 ) { if ( passed == 2 ) {
ok( true, "Check local and global callbacks after timeout" ); ok( true, 'Check local and global callbacks after timeout' );
jQuery("#qunit-fixture").unbind("ajaxError"); jQuery('#main').unbind("ajaxError");
start(); start();
} }
}; };
var fail = function(a,b,c) { var fail = function(a,b,c) {
ok( false, "Check for timeout failed " + a + " " + b ); ok( false, 'Check for timeout failed ' + a + ' ' + b );
start(); start();
}; };
jQuery("#qunit-fixture").ajaxError(pass); jQuery('#main').ajaxError(pass);
jQuery.ajax({ jQuery.ajax({
type: "GET", type: "GET",
@ -1829,11 +1819,11 @@ test("jQuery.ajaxSetup({timeout: Number}) with localtimeout", function() {
timeout: 15000, timeout: 15000,
url: url("data/name.php?wait=1"), url: url("data/name.php?wait=1"),
error: function() { error: function() {
ok( false, "Check for local timeout failed" ); ok( false, 'Check for local timeout failed' );
start(); start();
}, },
success: function() { success: function() {
ok( true, "Check for local timeout" ); ok( true, 'Check for local timeout' );
start(); start();
} }
}); });
@ -1849,7 +1839,7 @@ test("jQuery.ajax - simple get", function() {
type: "GET", type: "GET",
url: url("data/name.php?name=foo"), url: url("data/name.php?name=foo"),
success: function(msg){ success: function(msg){
equals( msg, "bar", "Check for GET" ); equals( msg, 'bar', 'Check for GET' );
start(); start();
} }
}); });
@ -1863,7 +1853,7 @@ test("jQuery.ajax - simple post", function() {
url: url("data/name.php"), url: url("data/name.php"),
data: "name=peter", data: "name=peter",
success: function(msg){ success: function(msg){
equals( msg, "pan", "Check for POST" ); equals( msg, 'pan', 'Check for POST' );
start(); start();
} }
}); });
@ -1875,7 +1865,7 @@ test("ajaxSetup()", function() {
jQuery.ajaxSetup({ jQuery.ajaxSetup({
url: url("data/name.php?name=foo"), url: url("data/name.php?name=foo"),
success: function(msg){ success: function(msg){
equals( msg, "bar", "Check for GET" ); equals( msg, 'bar', 'Check for GET' );
start(); start();
} }
}); });
@ -2037,14 +2027,14 @@ test("jQuery ajax - failing cross-domain", function() {
var i = 2; var i = 2;
jQuery.ajax({ jQuery.ajax({
url: "http://somewebsitethatdoesnotexist-67864863574657654.com", url: 'http://somewebsitethatdoesnotexist-67864863574657654.com',
success: function(){ ok( false , "success" ); }, success: function(){ ok( false , "success" ); },
error: function(xhr,_,e){ ok( true , "file not found: " + xhr.status + " => " + e ); }, error: function(xhr,_,e){ ok( true , "file not found: " + xhr.status + " => " + e ); },
complete: function() { if ( ! --i ) start(); } complete: function() { if ( ! --i ) start(); }
}); });
jQuery.ajax({ jQuery.ajax({
url: "http://www.google.com", url: 'http://www.google.com',
success: function(){ ok( false , "success" ); }, success: function(){ ok( false , "success" ); },
error: function(xhr,_,e){ ok( true , "access denied: " + xhr.status + " => " + e ); }, error: function(xhr,_,e){ ok( true , "access denied: " + xhr.status + " => " + e ); },
complete: function() { if ( ! --i ) start(); } complete: function() { if ( ! --i ) start(); }
@ -2057,7 +2047,7 @@ test("jQuery ajax - atom+xml", function() {
stop(); stop();
jQuery.ajax({ jQuery.ajax({
url: url( "data/atom+xml.php" ), url: url( 'data/atom+xml.php' ),
success: function(){ ok( true , "success" ); }, success: function(){ ok( true , "success" ); },
error: function(){ ok( false , "error" ); }, error: function(){ ok( false , "error" ); },
complete: function() { start(); } complete: function() { start(); }

File diff suppressed because it is too large Load diff

View file

@ -12,7 +12,7 @@ test("Basic requirements", function() {
}); });
test("jQuery()", function() { test("jQuery()", function() {
expect(29); expect(24);
// Basic constructor's behavior // Basic constructor's behavior
@ -20,7 +20,6 @@ test("jQuery()", function() {
equals( jQuery(undefined).length, 0, "jQuery(undefined) === jQuery([])" ); equals( jQuery(undefined).length, 0, "jQuery(undefined) === jQuery([])" );
equals( jQuery(null).length, 0, "jQuery(null) === jQuery([])" ); equals( jQuery(null).length, 0, "jQuery(null) === jQuery([])" );
equals( jQuery("").length, 0, "jQuery('') === jQuery([])" ); equals( jQuery("").length, 0, "jQuery('') === jQuery([])" );
equals( jQuery("#").length, 0, "jQuery('#') === jQuery([])" );
var obj = jQuery("div"); var obj = jQuery("div");
equals( jQuery(obj).selector, "div", "jQuery(jQueryObj) == jQueryObj" ); equals( jQuery(obj).selector, "div", "jQuery(jQueryObj) == jQueryObj" );
@ -29,7 +28,7 @@ test("jQuery()", function() {
equals( jQuery(window).length, 1, "Correct number of elements generated for jQuery(window)" ); equals( jQuery(window).length, 1, "Correct number of elements generated for jQuery(window)" );
var main = jQuery("#qunit-fixture"); var main = jQuery("#main");
same( jQuery("div p", main).get(), q("sndp", "en", "sap"), "Basic selector with jQuery object as context" ); same( jQuery("div p", main).get(), q("sndp", "en", "sap"), "Basic selector with jQuery object as context" );
/* /*
@ -62,7 +61,7 @@ test("jQuery()", function() {
equals( jQuery([1,2,3]).get(1), 2, "Test passing an array to the factory" ); equals( jQuery([1,2,3]).get(1), 2, "Test passing an array to the factory" );
equals( jQuery(document.body).get(0), jQuery("body").get(0), "Test passing an html node to the factory" ); equals( jQuery(document.body).get(0), jQuery('body').get(0), "Test passing an html node to the factory" );
var exec = false; var exec = false;
@ -75,13 +74,13 @@ test("jQuery()", function() {
id: "test3" id: "test3"
}); });
equals( elem[0].style.width, "10px", "jQuery() quick setter width"); equals( elem[0].style.width, '10px', 'jQuery() quick setter width');
equals( elem[0].style.paddingLeft, "1px", "jQuery quick setter css"); equals( elem[0].style.paddingLeft, '1px', 'jQuery quick setter css');
equals( elem[0].style.paddingRight, "1px", "jQuery quick setter css"); equals( elem[0].style.paddingRight, '1px', 'jQuery quick setter css');
equals( elem[0].childNodes.length, 1, "jQuery quick setter text"); equals( elem[0].childNodes.length, 1, 'jQuery quick setter text');
equals( elem[0].firstChild.nodeValue, "test", "jQuery quick setter text"); equals( elem[0].firstChild.nodeValue, "test", 'jQuery quick setter text');
equals( elem[0].className, "test2", "jQuery() quick setter class"); equals( elem[0].className, "test2", 'jQuery() quick setter class');
equals( elem[0].id, "test3", "jQuery() quick setter id"); equals( elem[0].id, "test3", 'jQuery() quick setter id');
exec = true; exec = true;
elem.click(); elem.click();
@ -96,17 +95,6 @@ test("jQuery()", function() {
// manually clean up detached elements // manually clean up detached elements
elem.remove(); elem.remove();
equals( jQuery(" <div/> ").length, 1, "Make sure whitespace is trimmed." );
equals( jQuery(" a<div/>b ").length, 1, "Make sure whitespace and other characters are trimmed." );
var long = "";
for ( var i = 0; i < 128; i++ ) {
long += "12345678";
}
equals( jQuery(" <div>" + long + "</div> ").length, 1, "Make sure whitespace is trimmed on long strings." );
equals( jQuery(" a<div>" + long + "</div>b ").length, 1, "Make sure whitespace and other characters are trimmed on long strings." );
}); });
test("selector state", function() { test("selector state", function() {
@ -126,54 +114,54 @@ test("selector state", function() {
equals( test.selector, "", "Body Selector" ); equals( test.selector, "", "Body Selector" );
equals( test.context, document.body, "Body Context" ); equals( test.context, document.body, "Body Context" );
test = jQuery("#qunit-fixture"); test = jQuery("#main");
equals( test.selector, "#qunit-fixture", "#qunit-fixture Selector" ); equals( test.selector, "#main", "#main Selector" );
equals( test.context, document, "#qunit-fixture Context" ); equals( test.context, document, "#main Context" );
test = jQuery("#notfoundnono"); test = jQuery("#notfoundnono");
equals( test.selector, "#notfoundnono", "#notfoundnono Selector" ); equals( test.selector, "#notfoundnono", "#notfoundnono Selector" );
equals( test.context, document, "#notfoundnono Context" ); equals( test.context, document, "#notfoundnono Context" );
test = jQuery("#qunit-fixture", document); test = jQuery("#main", document);
equals( test.selector, "#qunit-fixture", "#qunit-fixture Selector" ); equals( test.selector, "#main", "#main Selector" );
equals( test.context, document, "#qunit-fixture Context" ); equals( test.context, document, "#main Context" );
test = jQuery("#qunit-fixture", document.body); test = jQuery("#main", document.body);
equals( test.selector, "#qunit-fixture", "#qunit-fixture Selector" ); equals( test.selector, "#main", "#main Selector" );
equals( test.context, document.body, "#qunit-fixture Context" ); equals( test.context, document.body, "#main Context" );
// Test cloning // Test cloning
test = jQuery(test); test = jQuery(test);
equals( test.selector, "#qunit-fixture", "#qunit-fixture Selector" ); equals( test.selector, "#main", "#main Selector" );
equals( test.context, document.body, "#qunit-fixture Context" ); equals( test.context, document.body, "#main Context" );
test = jQuery(document.body).find("#qunit-fixture"); test = jQuery(document.body).find("#main");
equals( test.selector, "#qunit-fixture", "#qunit-fixture find Selector" ); equals( test.selector, "#main", "#main find Selector" );
equals( test.context, document.body, "#qunit-fixture find Context" ); equals( test.context, document.body, "#main find Context" );
test = jQuery("#qunit-fixture").filter("div"); test = jQuery("#main").filter("div");
equals( test.selector, "#qunit-fixture.filter(div)", "#qunit-fixture filter Selector" ); equals( test.selector, "#main.filter(div)", "#main filter Selector" );
equals( test.context, document, "#qunit-fixture filter Context" ); equals( test.context, document, "#main filter Context" );
test = jQuery("#qunit-fixture").not("div"); test = jQuery("#main").not("div");
equals( test.selector, "#qunit-fixture.not(div)", "#qunit-fixture not Selector" ); equals( test.selector, "#main.not(div)", "#main not Selector" );
equals( test.context, document, "#qunit-fixture not Context" ); equals( test.context, document, "#main not Context" );
test = jQuery("#qunit-fixture").filter("div").not("div"); test = jQuery("#main").filter("div").not("div");
equals( test.selector, "#qunit-fixture.filter(div).not(div)", "#qunit-fixture filter, not Selector" ); equals( test.selector, "#main.filter(div).not(div)", "#main filter, not Selector" );
equals( test.context, document, "#qunit-fixture filter, not Context" ); equals( test.context, document, "#main filter, not Context" );
test = jQuery("#qunit-fixture").filter("div").not("div").end(); test = jQuery("#main").filter("div").not("div").end();
equals( test.selector, "#qunit-fixture.filter(div)", "#qunit-fixture filter, not, end Selector" ); equals( test.selector, "#main.filter(div)", "#main filter, not, end Selector" );
equals( test.context, document, "#qunit-fixture filter, not, end Context" ); equals( test.context, document, "#main filter, not, end Context" );
test = jQuery("#qunit-fixture").parent("body"); test = jQuery("#main").parent("body");
equals( test.selector, "#qunit-fixture.parent(body)", "#qunit-fixture parent Selector" ); equals( test.selector, "#main.parent(body)", "#main parent Selector" );
equals( test.context, document, "#qunit-fixture parent Context" ); equals( test.context, document, "#main parent Context" );
test = jQuery("#qunit-fixture").eq(0); test = jQuery("#main").eq(0);
equals( test.selector, "#qunit-fixture.slice(0,1)", "#qunit-fixture eq Selector" ); equals( test.selector, "#main.slice(0,1)", "#main eq Selector" );
equals( test.context, document, "#qunit-fixture eq Context" ); equals( test.context, document, "#main eq Context" );
var d = "<div />"; var d = "<div />";
equals( equals(
@ -183,26 +171,6 @@ test("selector state", function() {
); );
}); });
test( "globalEval", function() {
expect( 3 );
jQuery.globalEval( "var globalEvalTest = true;" );
ok( window.globalEvalTest, "Test variable declarations are global" );
window.globalEvalTest = false;
jQuery.globalEval( "globalEvalTest = true;" );
ok( window.globalEvalTest, "Test variable assignments are global" );
window.globalEvalTest = false;
jQuery.globalEval( "this.globalEvalTest = true;" );
ok( window.globalEvalTest, "Test context (this) is the window object" );
window.globalEvalTest = undefined;
});
if ( !isLocal ) { if ( !isLocal ) {
test("browser", function() { test("browser", function() {
stop(); stop();
@ -239,7 +207,7 @@ test("noConflict", function() {
equals( jQuery.noConflict(true), $$, "noConflict returned the jQuery object" ); equals( jQuery.noConflict(true), $$, "noConflict returned the jQuery object" );
equals( jQuery, originaljQuery, "Make sure jQuery was reverted." ); equals( jQuery, originaljQuery, "Make sure jQuery was reverted." );
equals( $, original$, "Make sure $ was reverted." ); equals( $, original$, "Make sure $ was reverted." );
ok( $$("#qunit-fixture").html("test"), "Make sure that jQuery still works." ); ok( $$("#main").html("test"), "Make sure that jQuery still works." );
jQuery = $$; jQuery = $$;
}); });
@ -471,7 +439,7 @@ if ( !isLocal ) {
test("isXMLDoc - XML", function() { test("isXMLDoc - XML", function() {
expect(3); expect(3);
stop(); stop();
jQuery.get("data/dashboard.xml", function(xml) { jQuery.get('data/dashboard.xml', function(xml) {
ok( jQuery.isXMLDoc( xml ), "XML document" ); ok( jQuery.isXMLDoc( xml ), "XML document" );
ok( jQuery.isXMLDoc( xml.documentElement ), "XML documentElement" ); ok( jQuery.isXMLDoc( xml.documentElement ), "XML documentElement" );
ok( jQuery.isXMLDoc( jQuery("tab", xml)[0] ), "XML Tab Element" ); ok( jQuery.isXMLDoc( jQuery("tab", xml)[0] ), "XML Tab Element" );
@ -500,7 +468,7 @@ test("isWindow", function() {
}); });
test("jQuery('html')", function() { test("jQuery('html')", function() {
expect(18); expect(15);
QUnit.reset(); QUnit.reset();
jQuery.foo = false; jQuery.foo = false;
@ -532,19 +500,6 @@ test("jQuery('html')", function() {
ok( jQuery("<div></div>")[0], "Create a div with closing tag." ); ok( jQuery("<div></div>")[0], "Create a div with closing tag." );
ok( jQuery("<table></table>")[0], "Create a table with closing tag." ); ok( jQuery("<table></table>")[0], "Create a table with closing tag." );
// Test very large html string #7990
var i;
var li = "<li>very large html string</li>";
var html = ["<ul>"];
for ( i = 0; i < 50000; i += 1 ) {
html.push(li);
}
html.push("</ul>");
html = jQuery(html.join(""))[0];
equals( html.nodeName.toUpperCase(), "UL");
equals( html.firstChild.nodeName.toUpperCase(), "LI");
equals( html.childNodes.length, 50000 );
}); });
test("jQuery('html', context)", function() { test("jQuery('html', context)", function() {
@ -559,7 +514,7 @@ if ( !isLocal ) {
test("jQuery(selector, xml).text(str) - Loaded via XML document", function() { test("jQuery(selector, xml).text(str) - Loaded via XML document", function() {
expect(2); expect(2);
stop(); stop();
jQuery.get("data/dashboard.xml", function(xml) { jQuery.get('data/dashboard.xml', function(xml) {
// tests for #1419 where IE was a problem // tests for #1419 where IE was a problem
var tab = jQuery("tab", xml).eq(0); var tab = jQuery("tab", xml).eq(0);
equals( tab.text(), "blabla", "Verify initial text correct" ); equals( tab.text(), "blabla", "Verify initial text correct" );
@ -572,39 +527,39 @@ test("jQuery(selector, xml).text(str) - Loaded via XML document", function() {
test("end()", function() { test("end()", function() {
expect(3); expect(3);
equals( "Yahoo", jQuery("#yahoo").parent().end().text(), "Check for end" ); equals( 'Yahoo', jQuery('#yahoo').parent().end().text(), 'Check for end' );
ok( jQuery("#yahoo").end(), "Check for end with nothing to end" ); ok( jQuery('#yahoo').end(), 'Check for end with nothing to end' );
var x = jQuery("#yahoo"); var x = jQuery('#yahoo');
x.parent(); x.parent();
equals( "Yahoo", jQuery("#yahoo").text(), "Check for non-destructive behaviour" ); equals( 'Yahoo', jQuery('#yahoo').text(), 'Check for non-destructive behaviour' );
}); });
test("length", function() { test("length", function() {
expect(1); expect(1);
equals( jQuery("#qunit-fixture p").length, 6, "Get Number of Elements Found" ); equals( jQuery("#main p").length, 6, "Get Number of Elements Found" );
}); });
test("size()", function() { test("size()", function() {
expect(1); expect(1);
equals( jQuery("#qunit-fixture p").size(), 6, "Get Number of Elements Found" ); equals( jQuery("#main p").size(), 6, "Get Number of Elements Found" );
}); });
test("get()", function() { test("get()", function() {
expect(1); expect(1);
same( jQuery("#qunit-fixture p").get(), q("firstp","ap","sndp","en","sap","first"), "Get All Elements" ); same( jQuery("#main p").get(), q("firstp","ap","sndp","en","sap","first"), "Get All Elements" );
}); });
test("toArray()", function() { test("toArray()", function() {
expect(1); expect(1);
same( jQuery("#qunit-fixture p").toArray(), same( jQuery("#main p").toArray(),
q("firstp","ap","sndp","en","sap","first"), q("firstp","ap","sndp","en","sap","first"),
"Convert jQuery object to an Array" ) "Convert jQuery object to an Array" )
}) })
test("get(Number)", function() { test("get(Number)", function() {
expect(2); expect(2);
equals( jQuery("#qunit-fixture p").get(0), document.getElementById("firstp"), "Get A Single Element" ); equals( jQuery("#main p").get(0), document.getElementById("firstp"), "Get A Single Element" );
strictEqual( jQuery("#firstp").get(1), undefined, "Try get with index larger elements count" ); strictEqual( jQuery("#firstp").get(1), undefined, "Try get with index larger elements count" );
}); });
@ -617,7 +572,7 @@ test("get(-Number)",function() {
test("each(Function)", function() { test("each(Function)", function() {
expect(1); expect(1);
var div = jQuery("div"); var div = jQuery("div");
div.each(function(){this.foo = "zoo";}); div.each(function(){this.foo = 'zoo';});
var pass = true; var pass = true;
for ( var i = 0; i < div.size(); i++ ) { for ( var i = 0; i < div.size(); i++ ) {
if ( div.get(i).foo != "zoo" ) pass = false; if ( div.get(i).foo != "zoo" ) pass = false;
@ -636,7 +591,7 @@ test("slice()", function() {
same( $links.slice(-1).get(), q("mark"), "slice(-1)" ); same( $links.slice(-1).get(), q("mark"), "slice(-1)" );
same( $links.eq(1).get(), q("groups"), "eq(1)" ); same( $links.eq(1).get(), q("groups"), "eq(1)" );
same( $links.eq("2").get(), q("anchor1"), "eq('2')" ); same( $links.eq('2').get(), q("anchor1"), "eq('2')" );
same( $links.eq(-1).get(), q("mark"), "eq(-1)" ); same( $links.eq(-1).get(), q("mark"), "eq(-1)" );
}); });
@ -653,7 +608,7 @@ test("first()/last()", function() {
}); });
test("map()", function() { test("map()", function() {
expect(8); expect(2);//expect(6);
same( same(
jQuery("#ap").map(function(){ jQuery("#ap").map(function(){
@ -671,38 +626,32 @@ test("map()", function() {
"Single Map" "Single Map"
); );
return;//these haven't been accepted yet
//for #2616 //for #2616
var keys = jQuery.map( {a:1,b:2}, function( v, k ){ var keys = jQuery.map( {a:1,b:2}, function( v, k ){
return k; return k;
}); }, [ ] );
equals( keys.join(""), "ab", "Map the keys from a hash to an array" ); equals( keys.join(""), "ab", "Map the keys from a hash to an array" );
var values = jQuery.map( {a:1,b:2}, function( v, k ){ var values = jQuery.map( {a:1,b:2}, function( v, k ){
return v; return v;
}); }, [ ] );
equals( values.join(""), "12", "Map the values from a hash to an array" );
// object with length prop equals( values.join(""), "12", "Map the values from a hash to an array" );
var values = jQuery.map( {a:1,b:2, length:3}, function( v, k ){
return v;
});
equals( values.join(""), "123", "Map the values from a hash with a length property to an array" );
var scripts = document.getElementsByTagName("script"); var scripts = document.getElementsByTagName("script");
var mapped = jQuery.map( scripts, function( v, k ){ var mapped = jQuery.map( scripts, function( v, k ){
return v; return v;
}); }, {length:0} );
equals( mapped.length, scripts.length, "Map an array(-like) to a hash" );
var nonsense = document.getElementsByTagName("asdf"); equals( mapped.length, scripts.length, "Map an array(-like) to a hash" );
var mapped = jQuery.map( nonsense, function( v, k ){
return v;
});
equals( mapped.length, nonsense.length, "Map an empty array(-like) to a hash" );
var flat = jQuery.map( Array(4), function( v, k ){ var flat = jQuery.map( Array(4), function( v, k ){
return k % 2 ? k : [k,k,k];//try mixing array and regular returns return k % 2 ? k : [k,k,k];//try mixing array and regular returns
}); });
equals( flat.join(""), "00012223", "try the new flatten technique(#2616)" ); equals( flat.join(""), "00012223", "try the new flatten technique(#2616)" );
}); });
@ -809,7 +758,7 @@ test("jQuery.extend(Object, Object)", function() {
ok( typeof ret.foo != "string", "Check to make sure values equal with coersion (but not actually equal) overwrite correctly" ); ok( typeof ret.foo != "string", "Check to make sure values equal with coersion (but not actually equal) overwrite correctly" );
var ret = jQuery.extend(true, { foo:"bar" }, { foo:null } ); var ret = jQuery.extend(true, { foo:"bar" }, { foo:null } );
ok( typeof ret.foo !== "undefined", "Make sure a null value doesn't crash with deep extend, for #1908" ); ok( typeof ret.foo !== 'undefined', "Make sure a null value doesn't crash with deep extend, for #1908" );
var obj = { foo:null }; var obj = { foo:null };
jQuery.extend(true, obj, { foo:"notnull" } ); jQuery.extend(true, obj, { foo:"notnull" } );
@ -835,7 +784,7 @@ test("jQuery.extend(Object, Object)", function() {
}); });
test("jQuery.each(Object,Function)", function() { test("jQuery.each(Object,Function)", function() {
expect(14); expect(13);
jQuery.each( [0,1,2], function(i, n){ jQuery.each( [0,1,2], function(i, n){
equals( i, n, "Check array iteration" ); equals( i, n, "Check array iteration" );
}); });
@ -862,24 +811,17 @@ test("jQuery.each(Object,Function)", function() {
equals( total, 3, "Looping over an object, with break" ); equals( total, 3, "Looping over an object, with break" );
var f = function(){}; var f = function(){};
f.foo = "bar"; f.foo = 'bar';
jQuery.each(f, function(i){ jQuery.each(f, function(i){
f[i] = "baz"; f[i] = 'baz';
}); });
equals( "baz", f.foo, "Loop over a function" ); equals( "baz", f.foo, "Loop over a function" );
var stylesheet_count = 0;
jQuery.each(document.styleSheets, function(i){
stylesheet_count++;
});
equals(stylesheet_count, 2, "should not throw an error in IE while looping over document.styleSheets and return proper amount");
}); });
test("jQuery.makeArray", function(){ test("jQuery.makeArray", function(){
expect(17); expect(17);
equals( jQuery.makeArray(jQuery("html>*"))[0].nodeName.toUpperCase(), "HEAD", "Pass makeArray a jQuery object" ); equals( jQuery.makeArray(jQuery('html>*'))[0].nodeName.toUpperCase(), "HEAD", "Pass makeArray a jQuery object" );
equals( jQuery.makeArray(document.getElementsByName("PWD")).slice(0,1)[0].name, "PWD", "Pass makeArray a nodelist" ); equals( jQuery.makeArray(document.getElementsByName("PWD")).slice(0,1)[0].name, "PWD", "Pass makeArray a nodelist" );
@ -909,11 +851,11 @@ test("jQuery.makeArray", function(){
equals( jQuery.makeArray(/a/)[0].constructor, RegExp, "Pass makeArray a regex" ); equals( jQuery.makeArray(/a/)[0].constructor, RegExp, "Pass makeArray a regex" );
ok( jQuery.makeArray(document.getElementById("form")).length >= 13, "Pass makeArray a form (treat as elements)" ); ok( jQuery.makeArray(document.getElementById('form')).length >= 13, "Pass makeArray a form (treat as elements)" );
// For #5610 // For #5610
same( jQuery.makeArray({length: "0"}), [], "Make sure object is coerced properly."); same( jQuery.makeArray({'length': '0'}), [], "Make sure object is coerced properly.");
same( jQuery.makeArray({length: "5"}), [], "Make sure object is coerced properly."); same( jQuery.makeArray({'length': '5'}), [], "Make sure object is coerced properly.");
}); });
test("jQuery.isEmptyObject", function(){ test("jQuery.isEmptyObject", function(){
@ -927,7 +869,7 @@ test("jQuery.isEmptyObject", function(){
}); });
test("jQuery.proxy", function(){ test("jQuery.proxy", function(){
expect(7); expect(4);
var test = function(){ equals( this, thisObject, "Make sure that scope is set properly." ); }; var test = function(){ equals( this, thisObject, "Make sure that scope is set properly." ); };
var thisObject = { foo: "bar", method: test }; var thisObject = { foo: "bar", method: test };
@ -938,23 +880,11 @@ test("jQuery.proxy", function(){
// Basic scoping // Basic scoping
jQuery.proxy( test, thisObject )(); jQuery.proxy( test, thisObject )();
// Another take on it
jQuery.proxy( thisObject, "method" )();
// Make sure it doesn't freak out // Make sure it doesn't freak out
equals( jQuery.proxy( null, thisObject ), undefined, "Make sure no function was returned." ); equals( jQuery.proxy( null, thisObject ), undefined, "Make sure no function was returned." );
// Partial application // Use the string shortcut
var test2 = function( a ){ equals( a, "pre-applied", "Ensure arguments can be pre-applied." ); }; jQuery.proxy( thisObject, "method" )();
jQuery.proxy( test2, null, "pre-applied" )();
// Partial application w/ normal arguments
var test3 = function( a, b ){ equals( b, "normal", "Ensure arguments can be pre-applied and passed as usual." ); };
jQuery.proxy( test3, null, "pre-applied" )( "normal" );
// Test old syntax
var test4 = { meth: function( a ){ equals( a, "boom", "Ensure old syntax works." ); } };
jQuery.proxy( test4, "meth" )( "boom" );
}); });
test("jQuery.parseJSON", function(){ test("jQuery.parseJSON", function(){
@ -965,9 +895,9 @@ test("jQuery.parseJSON", function(){
equals( jQuery.parseJSON( "" ), null, "Nothing in, null out." ); equals( jQuery.parseJSON( "" ), null, "Nothing in, null out." );
same( jQuery.parseJSON("{}"), {}, "Plain object parsing." ); same( jQuery.parseJSON("{}"), {}, "Plain object parsing." );
same( jQuery.parseJSON("{\"test\":1}"), {"test":1}, "Plain object parsing." ); same( jQuery.parseJSON('{"test":1}'), {"test":1}, "Plain object parsing." );
same( jQuery.parseJSON("\n{\"test\":1}"), {"test":1}, "Make sure leading whitespaces are handled." ); same( jQuery.parseJSON('\n{"test":1}'), {"test":1}, "Make sure leading whitespaces are handled." );
try { try {
jQuery.parseJSON("{a:1}"); jQuery.parseJSON("{a:1}");
@ -991,7 +921,7 @@ test("jQuery.sub() - Static Methods", function(){
topLevelMethod: function() {return this.debug;}, topLevelMethod: function() {return this.debug;},
debug: false, debug: false,
config: { config: {
locale: "en_US" locale: 'en_US'
}, },
setup: function(config) { setup: function(config) {
this.extend(true, this.config, config); this.extend(true, this.config, config);
@ -1000,37 +930,37 @@ test("jQuery.sub() - Static Methods", function(){
Subclass.fn.extend({subClassMethod: function() { return this;}}); Subclass.fn.extend({subClassMethod: function() { return this;}});
//Test Simple Subclass //Test Simple Subclass
ok(Subclass.topLevelMethod() === false, "Subclass.topLevelMethod thought debug was true"); ok(Subclass.topLevelMethod() === false, 'Subclass.topLevelMethod thought debug was true');
ok(Subclass.config.locale == "en_US", Subclass.config.locale + " is wrong!"); ok(Subclass.config.locale == 'en_US', Subclass.config.locale + ' is wrong!');
same(Subclass.config.test, undefined, "Subclass.config.test is set incorrectly"); same(Subclass.config.test, undefined, 'Subclass.config.test is set incorrectly');
equal(jQuery.ajax, Subclass.ajax, "The subclass failed to get all top level methods"); equal(jQuery.ajax, Subclass.ajax, 'The subclass failed to get all top level methods');
//Create a SubSubclass //Create a SubSubclass
var SubSubclass = Subclass.sub(); var SubSubclass = Subclass.sub();
//Make Sure the SubSubclass inherited properly //Make Sure the SubSubclass inherited properly
ok(SubSubclass.topLevelMethod() === false, "SubSubclass.topLevelMethod thought debug was true"); ok(SubSubclass.topLevelMethod() === false, 'SubSubclass.topLevelMethod thought debug was true');
ok(SubSubclass.config.locale == "en_US", SubSubclass.config.locale + " is wrong!"); ok(SubSubclass.config.locale == 'en_US', SubSubclass.config.locale + ' is wrong!');
same(SubSubclass.config.test, undefined, "SubSubclass.config.test is set incorrectly"); same(SubSubclass.config.test, undefined, 'SubSubclass.config.test is set incorrectly');
equal(jQuery.ajax, SubSubclass.ajax, "The subsubclass failed to get all top level methods"); equal(jQuery.ajax, SubSubclass.ajax, 'The subsubclass failed to get all top level methods');
//Modify The Subclass and test the Modifications //Modify The Subclass and test the Modifications
SubSubclass.fn.extend({subSubClassMethod: function() { return this;}}); SubSubclass.fn.extend({subSubClassMethod: function() { return this;}});
SubSubclass.setup({locale: "es_MX", test: "worked"}); SubSubclass.setup({locale: 'es_MX', test: 'worked'});
SubSubclass.debug = true; SubSubclass.debug = true;
SubSubclass.ajax = function() {return false;}; SubSubclass.ajax = function() {return false;};
ok(SubSubclass.topLevelMethod(), "SubSubclass.topLevelMethod thought debug was false"); ok(SubSubclass.topLevelMethod(), 'SubSubclass.topLevelMethod thought debug was false');
same(SubSubclass(document).subClassMethod, Subclass.fn.subClassMethod, "Methods Differ!"); same(SubSubclass(document).subClassMethod, Subclass.fn.subClassMethod, 'Methods Differ!');
ok(SubSubclass.config.locale == "es_MX", SubSubclass.config.locale + " is wrong!"); ok(SubSubclass.config.locale == 'es_MX', SubSubclass.config.locale + ' is wrong!');
ok(SubSubclass.config.test == "worked", "SubSubclass.config.test is set incorrectly"); ok(SubSubclass.config.test == 'worked', 'SubSubclass.config.test is set incorrectly');
notEqual(jQuery.ajax, SubSubclass.ajax, "The subsubclass failed to get all top level methods"); notEqual(jQuery.ajax, SubSubclass.ajax, 'The subsubclass failed to get all top level methods');
//This shows that the modifications to the SubSubClass did not bubble back up to it's superclass //This shows that the modifications to the SubSubClass did not bubble back up to it's superclass
ok(Subclass.topLevelMethod() === false, "Subclass.topLevelMethod thought debug was true"); ok(Subclass.topLevelMethod() === false, 'Subclass.topLevelMethod thought debug was true');
ok(Subclass.config.locale == "en_US", Subclass.config.locale + " is wrong!"); ok(Subclass.config.locale == 'en_US', Subclass.config.locale + ' is wrong!');
same(Subclass.config.test, undefined, "Subclass.config.test is set incorrectly"); same(Subclass.config.test, undefined, 'Subclass.config.test is set incorrectly');
same(Subclass(document).subSubClassMethod, undefined, "subSubClassMethod set incorrectly"); same(Subclass(document).subSubClassMethod, undefined, 'subSubClassMethod set incorrectly');
equal(jQuery.ajax, Subclass.ajax, "The subclass failed to get all top level methods"); equal(jQuery.ajax, Subclass.ajax, 'The subclass failed to get all top level methods');
}); });
test("jQuery.sub() - .fn Methods", function(){ test("jQuery.sub() - .fn Methods", function(){
@ -1041,25 +971,25 @@ test("jQuery.sub() - .fn Methods", function(){
jQueryDocument = jQuery(document), jQueryDocument = jQuery(document),
selectors, contexts, methods, method, arg, description; selectors, contexts, methods, method, arg, description;
jQueryDocument.toString = function(){ return "jQueryDocument"; }; jQueryDocument.toString = function(){ return 'jQueryDocument'; };
Subclass.fn.subclassMethod = function(){}; Subclass.fn.subclassMethod = function(){};
SubclassSubclass.fn.subclassSubclassMethod = function(){}; SubclassSubclass.fn.subclassSubclassMethod = function(){};
selectors = [ selectors = [
"body", 'body',
"html, body", 'html, body',
"<div></div>" '<div></div>'
]; ];
methods = [ // all methods that return a new jQuery instance methods = [ // all methods that return a new jQuery instance
["eq", 1], ['eq', 1],
["add", document], ['add', document],
["end"], ['end'],
["has"], ['has'],
["closest", "div"], ['closest', 'div'],
["filter", document], ['filter', document],
["find", "div"] ['find', 'div']
]; ];
contexts = [undefined, document, jQueryDocument]; contexts = [undefined, document, jQueryDocument];
@ -1072,31 +1002,31 @@ test("jQuery.sub() - .fn Methods", function(){
jQuery.each(contexts, function(i, context){ jQuery.each(contexts, function(i, context){
description = "(\""+selector+"\", "+context+")."+method+"("+(arg||"")+")"; description = '("'+selector+'", '+context+').'+method+'('+(arg||'')+')';
same( same(
jQuery(selector, context)[method](arg).subclassMethod, undefined, jQuery(selector, context)[method](arg).subclassMethod, undefined,
"jQuery"+description+" doesn't have Subclass methods" 'jQuery'+description+' doesnt have Subclass methods'
); );
same( same(
jQuery(selector, context)[method](arg).subclassSubclassMethod, undefined, jQuery(selector, context)[method](arg).subclassSubclassMethod, undefined,
"jQuery"+description+" doesn't have SubclassSubclass methods" 'jQuery'+description+' doesnt have SubclassSubclass methods'
); );
same( same(
Subclass(selector, context)[method](arg).subclassMethod, Subclass.fn.subclassMethod, Subclass(selector, context)[method](arg).subclassMethod, Subclass.fn.subclassMethod,
"Subclass"+description+" has Subclass methods" 'Subclass'+description+' has Subclass methods'
); );
same( same(
Subclass(selector, context)[method](arg).subclassSubclassMethod, undefined, Subclass(selector, context)[method](arg).subclassSubclassMethod, undefined,
"Subclass"+description+" doesn't have SubclassSubclass methods" 'Subclass'+description+' doesnt have SubclassSubclass methods'
); );
same( same(
SubclassSubclass(selector, context)[method](arg).subclassMethod, Subclass.fn.subclassMethod, SubclassSubclass(selector, context)[method](arg).subclassMethod, Subclass.fn.subclassMethod,
"SubclassSubclass"+description+" has Subclass methods" 'SubclassSubclass'+description+' has Subclass methods'
); );
same( same(
SubclassSubclass(selector, context)[method](arg).subclassSubclassMethod, SubclassSubclass.fn.subclassSubclassMethod, SubclassSubclass(selector, context)[method](arg).subclassSubclassMethod, SubclassSubclass.fn.subclassSubclassMethod,
"SubclassSubclass"+description+" has SubclassSubclass methods" 'SubclassSubclass'+description+' has SubclassSubclass methods'
); );
}); });
@ -1104,17 +1034,3 @@ test("jQuery.sub() - .fn Methods", function(){
}); });
}); });
test("jQuery.camelCase()", function() {
var tests = {
"foo-bar": "fooBar",
"foo-bar-baz": "fooBarBaz"
};
expect(2);
jQuery.each( tests, function( key, val ) {
equal( jQuery.camelCase( key ), val, "Converts: " + key + " => " + val );
});
});

View file

@ -1,15 +1,15 @@
module("css", { teardown: moduleTeardown }); module("css", { teardown: moduleTeardown });
test("css(String|Hash)", function() { test("css(String|Hash)", function() {
expect( 42 ); expect(41);
equals( jQuery("#qunit-fixture").css("display"), "block", "Check for css property \"display\""); equals( jQuery('#main').css("display"), 'block', 'Check for css property "display"');
ok( jQuery("#nothiddendiv").is(":visible"), "Modifying CSS display: Assert element is visible"); ok( jQuery('#nothiddendiv').is(':visible'), 'Modifying CSS display: Assert element is visible');
jQuery("#nothiddendiv").css({display: "none"}); jQuery('#nothiddendiv').css({display: 'none'});
ok( !jQuery("#nothiddendiv").is(":visible"), "Modified CSS display: Assert element is hidden"); ok( !jQuery('#nothiddendiv').is(':visible'), 'Modified CSS display: Assert element is hidden');
jQuery("#nothiddendiv").css({display: "block"}); jQuery('#nothiddendiv').css({display: 'block'});
ok( jQuery("#nothiddendiv").is(":visible"), "Modified CSS display: Assert element is visible"); ok( jQuery('#nothiddendiv').is(':visible'), 'Modified CSS display: Assert element is visible');
var div = jQuery( "<div>" ); var div = jQuery( "<div>" );
@ -32,37 +32,34 @@ test("css(String|Hash)", function() {
div2.remove(); div2.remove();
// handle negative numbers by ignoring #1599, #4216 // handle negative numbers by ignoring #1599, #4216
jQuery("#nothiddendiv").css( {width: 1, height: 1} ); jQuery('#nothiddendiv').css({ 'width': 1, 'height': 1 });
var width = parseFloat(jQuery("#nothiddendiv").css("width")), height = parseFloat(jQuery("#nothiddendiv").css("height")); var width = parseFloat(jQuery('#nothiddendiv').css('width')), height = parseFloat(jQuery('#nothiddendiv').css('height'));
jQuery("#nothiddendiv").css({ width: -1, height: -1 }); jQuery('#nothiddendiv').css({ width: -1, height: -1 });
equals( parseFloat(jQuery("#nothiddendiv").css("width")), width, "Test negative width ignored") equals( parseFloat(jQuery('#nothiddendiv').css('width')), width, 'Test negative width ignored')
equals( parseFloat(jQuery("#nothiddendiv").css("height")), height, "Test negative height ignored") equals( parseFloat(jQuery('#nothiddendiv').css('height')), height, 'Test negative height ignored')
equals( jQuery("<div style='display: none;'>").css("display"), "none", "Styles on disconnected nodes"); equals( jQuery('<div style="display: none;">').css('display'), 'none', 'Styles on disconnected nodes');
jQuery("#floatTest").css({"float": "right"}); jQuery('#floatTest').css({'float': 'right'});
equals( jQuery("#floatTest").css("float"), "right", "Modified CSS float using \"float\": Assert float is right"); equals( jQuery('#floatTest').css('float'), 'right', 'Modified CSS float using "float": Assert float is right');
jQuery("#floatTest").css({"font-size": "30px"}); jQuery('#floatTest').css({'font-size': '30px'});
equals( jQuery("#floatTest").css("font-size"), "30px", "Modified CSS font-size: Assert font-size is 30px"); equals( jQuery('#floatTest').css('font-size'), '30px', 'Modified CSS font-size: Assert font-size is 30px');
jQuery.each("0,0.25,0.5,0.75,1".split(","), function(i, n) {
jQuery("#foo").css({opacity: n});
equals( jQuery("#foo").css("opacity"), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a String" ); jQuery.each("0,0.25,0.5,0.75,1".split(','), function(i, n) {
jQuery("#foo").css({opacity: parseFloat(n)}); jQuery('#foo').css({opacity: n});
equals( jQuery("#foo").css("opacity"), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a Number" ); equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a String" );
jQuery('#foo').css({opacity: parseFloat(n)});
equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a Number" );
}); });
jQuery("#foo").css({opacity: ""}); jQuery('#foo').css({opacity: ''});
equals( jQuery("#foo").css("opacity"), "1", "Assert opacity is 1 when set to an empty String" ); equals( jQuery('#foo').css('opacity'), '1', "Assert opacity is 1 when set to an empty String" );
equals( jQuery("#empty").css("opacity"), "0", "Assert opacity is accessible via filter property set in stylesheet in IE" ); equals( jQuery('#empty').css('opacity'), '0', "Assert opacity is accessible via filter property set in stylesheet in IE" );
jQuery("#empty").css({ opacity: "1" }); jQuery('#empty').css({ opacity: '1' });
equals( jQuery("#empty").css("opacity"), "1", "Assert opacity is taken from style attribute when set vs stylesheet in IE with filters" ); equals( jQuery('#empty').css('opacity'), '1', "Assert opacity is taken from style attribute when set vs stylesheet in IE with filters" );
jQuery.support.opacity ?
ok(true, "Requires the same number of tests"):
ok( ~jQuery("#empty")[0].currentStyle.filter.indexOf("gradient"), "Assert setting opacity doesn't overwrite other filters of the stylesheet in IE" );
var div = jQuery("#nothiddendiv"), child = jQuery("#nothiddendivchild"); var div = jQuery('#nothiddendiv'), child = jQuery('#nothiddendivchild');
equals( parseInt(div.css("fontSize")), 16, "Verify fontSize px set." ); equals( parseInt(div.css("fontSize")), 16, "Verify fontSize px set." );
equals( parseInt(div.css("font-size")), 16, "Verify fontSize px set." ); equals( parseInt(div.css("font-size")), 16, "Verify fontSize px set." );
@ -108,113 +105,31 @@ test("css(String|Hash)", function() {
equals( child[0].style.fontSize, old, "Make sure font-size isn't changed on null." ); equals( child[0].style.fontSize, old, "Make sure font-size isn't changed on null." );
}); });
test("css() explicit and relative values", function() {
expect(27);
var $elem = jQuery("#nothiddendiv");
$elem.css({ width: 1, height: 1, paddingLeft: "1px", opacity: 1 });
equals( $elem.width(), 1, "Initial css set or width/height works (hash)" );
equals( $elem.css("paddingLeft"), "1px", "Initial css set of paddingLeft works (hash)" );
equals( $elem.css("opacity"), "1", "Initial css set of opacity works (hash)" );
$elem.css({ width: "+=9" });
equals( $elem.width(), 10, "'+=9' on width (hash)" );
$elem.css({ width: "-=9" });
equals( $elem.width(), 1, "'-=9' on width (hash)" );
$elem.css({ width: "+=9px" });
equals( $elem.width(), 10, "'+=9px' on width (hash)" );
$elem.css({ width: "-=9px" });
equals( $elem.width(), 1, "'-=9px' on width (hash)" );
$elem.css( "width", "+=9" );
equals( $elem.width(), 10, "'+=9' on width (params)" );
$elem.css( "width", "-=9" ) ;
equals( $elem.width(), 1, "'-=9' on width (params)" );
$elem.css( "width", "+=9px" );
equals( $elem.width(), 10, "'+=9px' on width (params)" );
$elem.css( "width", "-=9px" );
equals( $elem.width(), 1, "'-=9px' on width (params)" );
$elem.css({ paddingLeft: "+=4" });
equals( $elem.css("paddingLeft"), "5px", "'+=4' on paddingLeft (hash)" );
$elem.css({ paddingLeft: "-=4" });
equals( $elem.css("paddingLeft"), "1px", "'-=4' on paddingLeft (hash)" );
$elem.css({ paddingLeft: "+=4px" });
equals( $elem.css("paddingLeft"), "5px", "'+=4px' on paddingLeft (hash)" );
$elem.css({ paddingLeft: "-=4px" });
equals( $elem.css("paddingLeft"), "1px", "'-=4px' on paddingLeft (hash)" );
$elem.css({ "padding-left": "+=4" });
equals( $elem.css("paddingLeft"), "5px", "'+=4' on padding-left (hash)" );
$elem.css({ "padding-left": "-=4" });
equals( $elem.css("paddingLeft"), "1px", "'-=4' on padding-left (hash)" );
$elem.css({ "padding-left": "+=4px" });
equals( $elem.css("paddingLeft"), "5px", "'+=4px' on padding-left (hash)" );
$elem.css({ "padding-left": "-=4px" });
equals( $elem.css("paddingLeft"), "1px", "'-=4px' on padding-left (hash)" );
$elem.css( "paddingLeft", "+=4" );
equals( $elem.css("paddingLeft"), "5px", "'+=4' on paddingLeft (params)" );
$elem.css( "paddingLeft", "-=4" );
equals( $elem.css("paddingLeft"), "1px", "'-=4' on paddingLeft (params)" );
$elem.css( "padding-left", "+=4px" );
equals( $elem.css("paddingLeft"), "5px", "'+=4px' on padding-left (params)" );
$elem.css( "padding-left", "-=4px" );
equals( $elem.css("paddingLeft"), "1px", "'-=4px' on padding-left (params)" );
$elem.css({ opacity: "-=0.5" });
equals( $elem.css("opacity"), "0.5", "'-=0.5' on opacity (hash)" );
$elem.css({ opacity: "+=0.5" });
equals( $elem.css("opacity"), "1", "'+=0.5' on opacity (hash)" );
$elem.css( "opacity", "-=0.5" );
equals( $elem.css("opacity"), "0.5", "'-=0.5' on opacity (params)" );
$elem.css( "opacity", "+=0.5" );
equals( $elem.css("opacity"), "1", "'+=0.5' on opacity (params)" );
});
test("css(String, Object)", function() { test("css(String, Object)", function() {
expect(22); expect(22);
ok( jQuery("#nothiddendiv").is(":visible"), "Modifying CSS display: Assert element is visible"); ok( jQuery('#nothiddendiv').is(':visible'), 'Modifying CSS display: Assert element is visible');
jQuery("#nothiddendiv").css("display", "none"); jQuery('#nothiddendiv').css("display", 'none');
ok( !jQuery("#nothiddendiv").is(":visible"), "Modified CSS display: Assert element is hidden"); ok( !jQuery('#nothiddendiv').is(':visible'), 'Modified CSS display: Assert element is hidden');
jQuery("#nothiddendiv").css("display", "block"); jQuery('#nothiddendiv').css("display", 'block');
ok( jQuery("#nothiddendiv").is(":visible"), "Modified CSS display: Assert element is visible"); ok( jQuery('#nothiddendiv').is(':visible'), 'Modified CSS display: Assert element is visible');
jQuery("#nothiddendiv").css("top", "-1em"); jQuery("#nothiddendiv").css("top", "-1em");
ok( jQuery("#nothiddendiv").css("top"), -16, "Check negative number in EMs." ); ok( jQuery("#nothiddendiv").css("top"), -16, "Check negative number in EMs." );
jQuery("#floatTest").css("float", "left"); jQuery('#floatTest').css('float', 'left');
equals( jQuery("#floatTest").css("float"), "left", "Modified CSS float using \"float\": Assert float is left"); equals( jQuery('#floatTest').css('float'), 'left', 'Modified CSS float using "float": Assert float is left');
jQuery("#floatTest").css("font-size", "20px"); jQuery('#floatTest').css('font-size', '20px');
equals( jQuery("#floatTest").css("font-size"), "20px", "Modified CSS font-size: Assert font-size is 20px"); equals( jQuery('#floatTest').css('font-size'), '20px', 'Modified CSS font-size: Assert font-size is 20px');
jQuery.each("0,0.25,0.5,0.75,1".split(","), function(i, n) { jQuery.each("0,0.25,0.5,0.75,1".split(','), function(i, n) {
jQuery("#foo").css("opacity", n); jQuery('#foo').css('opacity', n);
equals( jQuery("#foo").css("opacity"), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a String" ); equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a String" );
jQuery("#foo").css("opacity", parseFloat(n)); jQuery('#foo').css('opacity', parseFloat(n));
equals( jQuery("#foo").css("opacity"), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a Number" ); equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a Number" );
}); });
jQuery("#foo").css("opacity", ""); jQuery('#foo').css('opacity', '');
equals( jQuery("#foo").css("opacity"), "1", "Assert opacity is 1 when set to an empty String" ); equals( jQuery('#foo').css('opacity'), '1', "Assert opacity is 1 when set to an empty String" );
// using contents will get comments regular, text, and comment nodes // using contents will get comments regular, text, and comment nodes
var j = jQuery("#nonnodes").contents(); var j = jQuery("#nonnodes").contents();
@ -234,7 +149,7 @@ test("css(String, Object)", function() {
// Test for Bug #5509 // Test for Bug #5509
var success = true; var success = true;
try { try {
jQuery("#foo").css("backgroundColor", "rgba(0, 0, 0, 0.1)"); jQuery('#foo').css("backgroundColor", "rgba(0, 0, 0, 0.1)");
} }
catch (e) { catch (e) {
success = false; success = false;
@ -245,19 +160,19 @@ test("css(String, Object)", function() {
if ( !jQuery.support.opacity ) { if ( !jQuery.support.opacity ) {
test("css(String, Object) for MSIE", function() { test("css(String, Object) for MSIE", function() {
// for #1438, IE throws JS error when filter exists but doesn't have opacity in it // for #1438, IE throws JS error when filter exists but doesn't have opacity in it
jQuery("#foo").css("filter", "progid:DXImageTransform.Microsoft.Chroma(color='red');"); jQuery('#foo').css("filter", "progid:DXImageTransform.Microsoft.Chroma(color='red');");
equals( jQuery("#foo").css("opacity"), "1", "Assert opacity is 1 when a different filter is set in IE, #1438" ); equals( jQuery('#foo').css('opacity'), '1', "Assert opacity is 1 when a different filter is set in IE, #1438" );
var filterVal = "progid:DXImageTransform.Microsoft.Alpha(opacity=30) progid:DXImageTransform.Microsoft.Blur(pixelradius=5)"; var filterVal = "progid:DXImageTransform.Microsoft.Alpha(opacity=30) progid:DXImageTransform.Microsoft.Blur(pixelradius=5)";
var filterVal2 = "progid:DXImageTransform.Microsoft.alpha(opacity=100) progid:DXImageTransform.Microsoft.Blur(pixelradius=5)"; var filterVal2 = "progid:DXImageTransform.Microsoft.alpha(opacity=100) progid:DXImageTransform.Microsoft.Blur(pixelradius=5)";
var filterVal3 = "progid:DXImageTransform.Microsoft.Blur(pixelradius=5)"; var filterVal3 = "progid:DXImageTransform.Microsoft.Blur(pixelradius=5)";
jQuery("#foo").css("filter", filterVal); jQuery('#foo').css("filter", filterVal);
equals( jQuery("#foo").css("filter"), filterVal, "css('filter', val) works" ); equals( jQuery('#foo').css("filter"), filterVal, "css('filter', val) works" );
jQuery("#foo").css("opacity", 1); jQuery('#foo').css("opacity", 1);
equals( jQuery("#foo").css("filter"), filterVal2, "Setting opacity in IE doesn't duplicate opacity filter" ); equals( jQuery('#foo').css("filter"), filterVal2, "Setting opacity in IE doesn't duplicate opacity filter" );
equals( jQuery("#foo").css("opacity"), 1, "Setting opacity in IE with other filters works" ); equals( jQuery('#foo').css("opacity"), 1, "Setting opacity in IE with other filters works" );
jQuery("#foo").css("filter", filterVal3).css("opacity", 1); jQuery('#foo').css("filter", filterVal3).css("opacity", 1);
ok( jQuery("#foo").css("filter").indexOf(filterVal3) !== -1, "Setting opacity in IE doesn't clobber other filters" ); ok( jQuery('#foo').css("filter").indexOf(filterVal3) !== -1, "Setting opacity in IE doesn't clobber other filters" );
}); });
} }
@ -396,14 +311,14 @@ test("jQuery.css(elem, 'height') doesn't clear radio buttons (bug #1095)", funct
test(":visible selector works properly on table elements (bug #4512)", function () { test(":visible selector works properly on table elements (bug #4512)", function () {
expect(1); expect(1);
jQuery("#table").html("<tr><td style='display:none'>cell</td><td>cell</td></tr>"); jQuery('#table').html('<tr><td style="display:none">cell</td><td>cell</td></tr>');
equals(jQuery("#table td:visible").length, 1, "hidden cell is not perceived as visible"); equals(jQuery('#table td:visible').length, 1, "hidden cell is not perceived as visible");
}); });
test(":visible selector works properly on children with a hidden parent (bug #4512)", function () { test(":visible selector works properly on children with a hidden parent (bug #4512)", function () {
expect(1); expect(1);
jQuery("#table").css("display", "none").html("<tr><td>cell</td><td>cell</td></tr>"); jQuery('#table').css('display', 'none').html('<tr><td>cell</td><td>cell</td></tr>');
equals(jQuery("#table td:visible").length, 0, "hidden cell children not perceived as visible"); equals(jQuery('#table td:visible').length, 0, "hidden cell children not perceived as visible");
}); });
test("internal ref to elem.runtimeStyle (bug #7608)", function () { test("internal ref to elem.runtimeStyle (bug #7608)", function () {
@ -428,60 +343,5 @@ test("marginRight computed style (bug #3333)", function() {
marginRight: 0 marginRight: 0
}); });
equals($div.css("marginRight"), "0px", "marginRight correctly calculated with a width and display block"); equals($div.css("marginRight"), "0px");
});
test("jQuery.cssProps behavior, (bug #8402)", function() {
var div = jQuery( "<div>" ).appendTo(document.body).css({
position: "absolute",
top: 0,
left: 10
});
jQuery.cssProps.top = "left";
equal( div.css("top"), "10px", "the fixed property is used when accessing the computed style");
div.css("top", "100px");
equal( div[0].style.left, "100px", "the fixed property is used when setting the style");
// cleanup jQuery.cssProps
jQuery.cssProps.top = undefined;
});
test("widows & orphans #8936", function () {
var $p = jQuery("<p>").appendTo("#qunit-fixture");
if ( "widows" in $p[0].style ) {
expect(4);
$p.css({
widows: 0,
orphans: 0
});
equal( $p.css("widows") || jQuery.style( $p[0], "widows" ), 0, "widows correctly start with value 0");
equal( $p.css("orphans") || jQuery.style( $p[0], "orphans" ), 0, "orphans correctly start with value 0");
$p.css({
widows: 3,
orphans: 3
});
equal( $p.css("widows") || jQuery.style( $p[0], "widows" ), 3, "widows correctly set to 3");
equal( $p.css("orphans") || jQuery.style( $p[0], "orphans" ), 3, "orphans correctly set to 3");
} else {
expect(1);
ok( true, "jQuery does not attempt to test for style props that definitely don't exist in older versions of IE");
}
$p.remove();
});
test("Do not append px to 'fill-opacity' #9548", 1, function() {
var $div = jQuery("<div>").appendTo("#qunit-fixture");
$div.css("fill-opacity", 0).animate({ "fill-opacity": 1.0 }, 0, function () {
equal( jQuery(this).css("fill-opacity"), 1, "Do not append px to 'fill-opacity'");
});
}); });

View file

@ -283,11 +283,11 @@ test(".data(String) and .data(String, Object)", function() {
// #3748 // #3748
var $elem = jQuery({exists:true}); var $elem = jQuery({exists:true});
equals( $elem.data("nothing"), undefined, "Non-existent data returns undefined"); equals( $elem.data('nothing'), undefined, "Non-existent data returns undefined");
equals( $elem.data("null", null).data("null"), null, "null's are preserved"); equals( $elem.data('null',null).data('null'), null, "null's are preserved");
equals( $elem.data("emptyString", "").data("emptyString"), "", "Empty strings are preserved"); equals( $elem.data('emptyString','').data('emptyString'), '', "Empty strings are preserved");
equals( $elem.data("false", false).data("false"), false, "false's are preserved"); equals( $elem.data('false',false).data('false'), false, "false's are preserved");
equals( $elem.data("exists"), undefined, "Existing data is not returned" ); equals( $elem.data('exists'), undefined, "Existing data is not returned" );
// Clean up // Clean up
$elem.removeData(); $elem.removeData();
@ -316,7 +316,7 @@ test("data-* attributes", function() {
div.remove(); div.remove();
child.appendTo("#qunit-fixture"); child.appendTo('#main');
equals( child.data("myobj"), "old data", "Value accessed from data-* attribute"); equals( child.data("myobj"), "old data", "Value accessed from data-* attribute");
child.data("myobj", "replaced"); child.data("myobj", "replaced");
@ -365,19 +365,19 @@ test("data-* attributes", function() {
.attr("data-null", "null") .attr("data-null", "null")
.attr("data-string", "test"); .attr("data-string", "test");
strictEqual( child.data("true"), true, "Primitive true read from attribute"); strictEqual( child.data('true'), true, "Primitive true read from attribute");
strictEqual( child.data("false"), false, "Primitive false read from attribute"); strictEqual( child.data('false'), false, "Primitive false read from attribute");
strictEqual( child.data("five"), 5, "Primitive number read from attribute"); strictEqual( child.data('five'), 5, "Primitive number read from attribute");
strictEqual( child.data("point"), 5.5, "Primitive number read from attribute"); strictEqual( child.data('point'), 5.5, "Primitive number read from attribute");
strictEqual( child.data("pointe"), 5500, "Primitive number read from attribute"); strictEqual( child.data('pointe'), 5500, "Primitive number read from attribute");
strictEqual( child.data("pointbad"), "5..5", "Bad number read from attribute"); strictEqual( child.data('pointbad'), "5..5", "Bad number read from attribute");
strictEqual( child.data("pointbad2"), "-.", "Bad number read from attribute"); strictEqual( child.data('pointbad2'), "-.", "Bad number read from attribute");
strictEqual( child.data("badjson"), "{123}", "Bad number read from attribute"); strictEqual( child.data('badjson'), "{123}", "Bad number read from attribute");
strictEqual( child.data("badjson2"), "[abc]", "Bad number read from attribute"); strictEqual( child.data('badjson2'), "[abc]", "Bad number read from attribute");
strictEqual( child.data("empty"), "", "Empty string read from attribute"); strictEqual( child.data('empty'), "", "Empty string read from attribute");
strictEqual( child.data("space"), " ", "Empty string read from attribute"); strictEqual( child.data('space'), " ", "Empty string read from attribute");
strictEqual( child.data("null"), null, "Primitive null read from attribute"); strictEqual( child.data('null'), null, "Primitive null read from attribute");
strictEqual( child.data("string"), "test", "Typical string read from attribute"); strictEqual( child.data('string'), "test", "Typical string read from attribute");
child.remove(); child.remove();
@ -401,12 +401,12 @@ test("data-* attributes", function() {
same(jQuery(elem).data("stuff"), [2,8], "Check stuff property"); same(jQuery(elem).data("stuff"), [2,8], "Check stuff property");
break; break;
default: default:
ok(false, ["Assertion failed on index ", index, ", with data ", data].join("")); ok(false, ["Assertion failed on index ", index, ", with data ", data].join(''));
} }
} }
var metadata = "<ol><li class='test test2' data-foo='bar' data-bar='baz' data-arr='[1,2]'>Some stuff</li><li class='test test2' data-test='bar' data-bar='baz'>Some stuff</li><li class='test test2' data-zoooo='bar' data-bar='{\"test\":\"baz\"}'>Some stuff</li><li class='test test2' data-number=true data-stuff='[2,8]'>Some stuff</li></ol>", var metadata = '<ol><li class="test test2" data-foo="bar" data-bar="baz" data-arr="[1,2]">Some stuff</li><li class="test test2" data-test="bar" data-bar="baz">Some stuff</li><li class="test test2" data-zoooo="bar" data-bar=\'{"test":"baz"}\'>Some stuff</li><li class="test test2" data-number=true data-stuff="[2,8]">Some stuff</li></ol>',
elem = jQuery(metadata).appendTo("#qunit-fixture"); elem = jQuery(metadata).appendTo('#main');
elem.find("li").each(testData); elem.find("li").each(testData);
elem.remove(); elem.remove();
@ -483,45 +483,6 @@ if (window.JSON && window.JSON.stringify) {
var obj = { foo: "bar" }; var obj = { foo: "bar" };
jQuery.data(obj, "hidden", true); jQuery.data(obj, "hidden", true);
equals( JSON.stringify(obj), "{\"foo\":\"bar\"}", "Expando is hidden from JSON.stringify" ); equals( JSON.stringify(obj), '{"foo":"bar"}', "Expando is hidden from JSON.stringify" );
}); });
} }
test("jQuery.data should follow html5 specification regarding camel casing", function() {
expect(8);
var div = jQuery("<div id='myObject' data-foo='a' data-foo-bar='b' data-foo-bar-baz='c'></div>")
.prependTo("body");
equals(div.data().foo, "a", "Verify single word data-* key");
equals(div.data().fooBar, "b", "Verify multiple word data-* key");
equals(div.data().fooBarBaz, "c", "Verify multiple word data-* key");
equals(div.data("foo"), "a", "Verify single word data-* key");
equals(div.data("fooBar"), "b", "Verify multiple word data-* key");
equals(div.data("fooBarBaz"), "c", "Verify multiple word data-* key");
div.data("foo-bar", "d");
equals(div.data("fooBar"), "d", "Verify updated data-* key");
equals(div.data("foo-bar"), "d", "Verify updated data-* key");
div.remove();
});
test("jQuery.data should not miss data with preset hyphenated property names", function() {
expect(2);
var div = jQuery("<div/>", { id: "hyphened" }).appendTo("#qunit-fixture"),
test = {
"camelBar": "camelBar",
"hyphen-foo": "hyphen-foo"
};
div.data( test );
jQuery.each( test , function(i, k) {
equal( div.data(k), k, "data with property '"+k+"' was correctly found");
});
});

View file

@ -1,12 +1,6 @@
module("deferred", { teardown: moduleTeardown }); module("deferred", { teardown: moduleTeardown });
jQuery.each( [ "", " - new operator" ], function( _, withNew ) { test("jQuery._Deferred()", function() {
function createDeferred() {
return withNew ? new jQuery._Deferred() : jQuery._Deferred();
}
test("jQuery._Deferred" + withNew, function() {
expect( 11 ); expect( 11 );
@ -14,7 +8,7 @@ jQuery.each( [ "", " - new operator" ], function( _, withNew ) {
object, object,
test; test;
deferred = createDeferred(); deferred = jQuery._Deferred();
test = false; test = false;
@ -47,7 +41,7 @@ jQuery.each( [ "", " - new operator" ], function( _, withNew ) {
ok( test , "Test cancel" ); ok( test , "Test cancel" );
deferred = createDeferred().resolve(); deferred = jQuery._Deferred().resolve();
try { try {
deferred.done( function() { deferred.done( function() {
@ -61,7 +55,7 @@ jQuery.each( [ "", " - new operator" ], function( _, withNew ) {
} }
test = ""; test = "";
deferred = createDeferred().done( function() { deferred = jQuery._Deferred().done( function() {
test += "A"; test += "A";
@ -92,217 +86,68 @@ jQuery.each( [ "", " - new operator" ], function( _, withNew ) {
strictEqual( test , "ABC" , "Test done callbacks order" ); strictEqual( test , "ABC" , "Test done callbacks order" );
deferred = createDeferred(); deferred = jQuery._Deferred();
deferred.resolveWith( jQuery , [ document ] ).done( function( doc ) { deferred.resolveWith( jQuery , [ document ] ).done( function( doc ) {
ok( this === jQuery && arguments.length === 1 && doc === document , "Test fire context & args" ); ok( this === jQuery && arguments.length === 1 && doc === document , "Test fire context & args" );
}); });
// #8421 // #8421
deferred = createDeferred(); deferred = jQuery._Deferred();
deferred.resolveWith().done(function() { deferred.resolveWith().done(function() {
ok( true, "Test resolveWith can be called with no argument" ); ok( true, "Test resolveWith can be called with no argument" );
}); });
}); });
} );
jQuery.each( [ "", " - new operator" ], function( _, withNew ) { test("jQuery.Deferred()", function() {
function createDeferred( fn ) { expect( 10 );
return withNew ? new jQuery.Deferred( fn ) : jQuery.Deferred( fn );
}
test("jQuery.Deferred" + withNew, function() { jQuery.Deferred( function( defer ) {
strictEqual( this , defer , "Defer passed as this & first argument" );
expect( 8 );
createDeferred().resolve().then( function() {
ok( true , "Success on resolve" );
ok( this.isResolved(), "Deferred is resolved" );
}, function() {
ok( false , "Error on resolve" );
}).always( function() {
ok( true , "Always callback on resolve" );
});
createDeferred().reject().then( function() {
ok( false , "Success on reject" );
}, function() {
ok( true , "Error on reject" );
ok( this.isRejected(), "Deferred is rejected" );
}).always( function() {
ok( true , "Always callback on reject" );
});
createDeferred( function( defer ) {
ok( this === defer , "Defer passed as this & first argument" );
this.resolve( "done" ); this.resolve( "done" );
}).then( function( value ) { }).then( function( value ) {
strictEqual( value , "done" , "Passed function executed" ); strictEqual( value , "done" , "Passed function executed" );
}); });
});
} );
test( "jQuery.Deferred.pipe - filtering (done)", function() { jQuery.Deferred().resolve().then( function() {
ok( true , "Success on resolve" );
expect(4); }, function() {
ok( false , "Error on resolve" );
var defer = jQuery.Deferred(),
piped = defer.pipe(function( a, b ) {
return a * b;
}),
value1,
value2,
value3;
piped.done(function( result ) {
value3 = result;
}); });
defer.done(function( a, b ) { jQuery.Deferred().reject().then( function() {
value1 = a; ok( false , "Success on reject" );
value2 = b; }, function() {
ok( true , "Error on reject" );
}); });
defer.resolve( 2, 3 ); ( new jQuery.Deferred( function( defer ) {
strictEqual( this , defer , "Defer passed as this & first argument (new)" );
strictEqual( value1, 2, "first resolve value ok" ); this.resolve( "done" );
strictEqual( value2, 3, "second resolve value ok" ); }) ).then( function( value ) {
strictEqual( value3, 6, "result of filter ok" ); strictEqual( value , "done" , "Passed function executed (new)" );
jQuery.Deferred().reject().pipe(function() {
ok( false, "pipe should not be called on reject" );
}); });
jQuery.Deferred().resolve().pipe( jQuery.noop ).done(function( value ) { ( new jQuery.Deferred() ).resolve().then( function() {
strictEqual( value, undefined, "pipe done callback can return undefined/null" ); ok( true , "Success on resolve (new)" );
}, function() {
ok( false , "Error on resolve (new)" );
}); });
( new jQuery.Deferred() ).reject().then( function() {
ok( false , "Success on reject (new)" );
}, function() {
ok( true , "Error on reject (new)" );
});
var tmp = jQuery.Deferred();
strictEqual( tmp.promise() , tmp.promise() , "Test deferred always return same promise" );
strictEqual( tmp.promise() , tmp.promise().promise() , "Test deferred's promise always return same promise as deferred" );
}); });
test( "jQuery.Deferred.pipe - filtering (fail)", function() { test("jQuery.when()", function() {
expect(4);
var defer = jQuery.Deferred(),
piped = defer.pipe( null, function( a, b ) {
return a * b;
} ),
value1,
value2,
value3;
piped.fail(function( result ) {
value3 = result;
});
defer.fail(function( a, b ) {
value1 = a;
value2 = b;
});
defer.reject( 2, 3 );
strictEqual( value1, 2, "first reject value ok" );
strictEqual( value2, 3, "second reject value ok" );
strictEqual( value3, 6, "result of filter ok" );
jQuery.Deferred().resolve().pipe( null, function() {
ok( false, "pipe should not be called on resolve" );
} );
jQuery.Deferred().reject().pipe( null, jQuery.noop ).fail(function( value ) {
strictEqual( value, undefined, "pipe fail callback can return undefined/null" );
});
});
test( "jQuery.Deferred.pipe - deferred (done)", function() {
expect(3);
var defer = jQuery.Deferred(),
piped = defer.pipe(function( a, b ) {
return jQuery.Deferred(function( defer ) {
defer.reject( a * b );
});
}),
value1,
value2,
value3;
piped.fail(function( result ) {
value3 = result;
});
defer.done(function( a, b ) {
value1 = a;
value2 = b;
});
defer.resolve( 2, 3 );
strictEqual( value1, 2, "first resolve value ok" );
strictEqual( value2, 3, "second resolve value ok" );
strictEqual( value3, 6, "result of filter ok" );
});
test( "jQuery.Deferred.pipe - deferred (fail)", function() {
expect(3);
var defer = jQuery.Deferred(),
piped = defer.pipe( null, function( a, b ) {
return jQuery.Deferred(function( defer ) {
defer.resolve( a * b );
});
} ),
value1,
value2,
value3;
piped.done(function( result ) {
value3 = result;
});
defer.fail(function( a, b ) {
value1 = a;
value2 = b;
});
defer.reject( 2, 3 );
strictEqual( value1, 2, "first reject value ok" );
strictEqual( value2, 3, "second reject value ok" );
strictEqual( value3, 6, "result of filter ok" );
});
test( "jQuery.Deferred.pipe - context", function() {
expect(4);
var context = {};
jQuery.Deferred().resolveWith( context, [ 2 ] ).pipe(function( value ) {
return value * 3;
}).done(function( value ) {
strictEqual( this, context, "custom context correctly propagated" );
strictEqual( value, 6, "proper value received" );
});
var defer = jQuery.Deferred(),
piped = defer.pipe(function( value ) {
return value * 3;
});
defer.resolve( 2 );
piped.done(function( value ) {
strictEqual( this.promise(), piped, "default context gets updated to latest defer in the chain" );
strictEqual( value, 6, "proper value received" );
});
});
test( "jQuery.when" , function() {
expect( 23 ); expect( 23 );
@ -321,63 +166,57 @@ test( "jQuery.when" , function() {
} , function( message , value ) { } , function( message , value ) {
ok( jQuery.isFunction( jQuery.when( value ).done(function( resolveValue ) { ok( jQuery.isFunction( jQuery.when( value ).then( function( resolveValue ) {
strictEqual( resolveValue , value , "Test the promise was resolved with " + message ); strictEqual( resolveValue , value , "Test the promise was resolved with " + message );
}).promise ) , "Test " + message + " triggers the creation of a new Promise" ); } ).promise ) , "Test " + message + " triggers the creation of a new Promise" );
} ); } );
ok( jQuery.isFunction( jQuery.when().done(function( resolveValue ) { ok( jQuery.isFunction( jQuery.when().then( function( resolveValue ) {
strictEqual( resolveValue , undefined , "Test the promise was resolved with no parameter" ); strictEqual( resolveValue , undefined , "Test the promise was resolved with no parameter" );
}).promise ) , "Test calling when with no parameter triggers the creation of a new Promise" ); } ).promise ) , "Test calling when with no parameter triggers the creation of a new Promise" );
var cache, i; var cache, i;
for( i = 1 ; i < 4 ; i++ ) { for( i = 1 ; i < 4 ; i++ ) {
jQuery.when( cache || jQuery.Deferred( function() { jQuery.when( cache || jQuery.Deferred( function() {
this.resolve( i ); this.resolve( i );
}) ).done(function( value ) { }) ).then( function( value ) {
strictEqual( value , 1 , "Function executed" + ( i > 1 ? " only once" : "" ) ); strictEqual( value , 1 , "Function executed" + ( i > 1 ? " only once" : "" ) );
cache = value; cache = value;
}, function() {
ok( false , "Fail called" );
}); });
} }
}); });
test("jQuery.when - joined", function() { test("jQuery.when() - joined", function() {
expect(25); expect(8);
var deferreds = { jQuery.when( 1, 2, 3 ).done( function( a, b, c ) {
value: 1, strictEqual( a , 1 , "Test first param is first resolved value - non-observables" );
success: jQuery.Deferred().resolve( 1 ), strictEqual( b , 2 , "Test second param is second resolved value - non-observables" );
error: jQuery.Deferred().reject( 0 ), strictEqual( c , 3 , "Test third param is third resolved value - non-observables" );
futureSuccess: jQuery.Deferred(), }).fail( function() {
futureError: jQuery.Deferred() ok( false , "Test the created deferred was resolved - non-observables");
}, });
willSucceed = {
value: true, var successDeferred = jQuery.Deferred().resolve( 1 , 2 , 3 ),
success: true, errorDeferred = jQuery.Deferred().reject( "error" , "errorParam" );
error: false,
futureSuccess: true, jQuery.when( 1 , successDeferred , 3 ).done( function( a, b, c ) {
futureError: false strictEqual( a , 1 , "Test first param is first resolved value - resolved observable" );
}; same( b , [ 1 , 2 , 3 ] , "Test second param is second resolved value - resolved observable" );
strictEqual( c , 3 , "Test third param is third resolved value - resolved observable" );
jQuery.each( deferreds, function( id1, defer1 ) { }).fail( function() {
jQuery.each( deferreds, function( id2, defer2 ) { ok( false , "Test the created deferred was resolved - resolved observable");
var shouldResolve = willSucceed[ id1 ] && willSucceed[ id2 ], });
expected = shouldResolve ? [ 1, 1 ] : [ 0, undefined ],
code = id1 + "/" + id2; jQuery.when( 1 , errorDeferred , 3 ).done( function() {
jQuery.when( defer1, defer2 ).done(function( a, b ) { ok( false , "Test the created deferred was rejected - rejected observable");
if ( shouldResolve ) { }).fail( function( error , errorParam ) {
same( [ a, b ], expected, code + " => resolve" ); strictEqual( error , "error" , "Test first param is first rejected value - rejected observable" );
} strictEqual( errorParam , "errorParam" , "Test second param is second rejected value - rejected observable" );
}).fail(function( a, b ) {
if ( !shouldResolve ) {
same( [ a, b ], expected, code + " => resolve" );
}
}); });
} );
} );
deferreds.futureSuccess.resolve( 1 );
deferreds.futureError.reject( 0 );
}); });

View file

@ -34,7 +34,7 @@ function testWidth( val ) {
equals( blah.width( val(10) ), blah, "Make sure that setting a width on an empty set returns the set." ); equals( blah.width( val(10) ), blah, "Make sure that setting a width on an empty set returns the set." );
equals( blah.width(), null, "Make sure 'null' is returned on an empty set"); equals( blah.width(), null, "Make sure 'null' is returned on an empty set");
jQuery.removeData($div[0], "olddisplay", true); jQuery.removeData($div[0], 'olddisplay', true);
} }
test("width()", function() { test("width()", function() {
@ -83,7 +83,7 @@ function testHeight( val ) {
equals( blah.height( val(10) ), blah, "Make sure that setting a height on an empty set returns the set." ); equals( blah.height( val(10) ), blah, "Make sure that setting a height on an empty set returns the set." );
equals( blah.height(), null, "Make sure 'null' is returned on an empty set"); equals( blah.height(), null, "Make sure 'null' is returned on an empty set");
jQuery.removeData($div[0], "olddisplay", true); jQuery.removeData($div[0], 'olddisplay', true);
} }
test("height()", function() { test("height()", function() {
@ -107,13 +107,7 @@ test("height() with function args", function() {
}); });
test("innerWidth()", function() { test("innerWidth()", function() {
expect(8); expect(4);
equals(jQuery(window).innerWidth(), null, "Test on window without margin option");
equals(jQuery(window).innerWidth(true), null, "Test on window with margin option");
equals(jQuery(document).innerWidth(), null, "Test on document without margin option");
equals(jQuery(document).innerWidth(true), null, "Test on document with margin option");
var $div = jQuery("#nothiddendiv"); var $div = jQuery("#nothiddendiv");
// set styles // set styles
@ -138,17 +132,11 @@ test("innerWidth()", function() {
equals( div.innerWidth(), 0, "Make sure that disconnected nodes are handled." ); equals( div.innerWidth(), 0, "Make sure that disconnected nodes are handled." );
div.remove(); div.remove();
jQuery.removeData($div[0], "olddisplay", true); jQuery.removeData($div[0], 'olddisplay', true);
}); });
test("innerHeight()", function() { test("innerHeight()", function() {
expect(8); expect(4);
equals(jQuery(window).innerHeight(), null, "Test on window without margin option");
equals(jQuery(window).innerHeight(true), null, "Test on window with margin option");
equals(jQuery(document).innerHeight(), null, "Test on document without margin option");
equals(jQuery(document).innerHeight(true), null, "Test on document with margin option");
var $div = jQuery("#nothiddendiv"); var $div = jQuery("#nothiddendiv");
// set styles // set styles
@ -173,16 +161,11 @@ test("innerHeight()", function() {
equals( div.innerHeight(), 0, "Make sure that disconnected nodes are handled." ); equals( div.innerHeight(), 0, "Make sure that disconnected nodes are handled." );
div.remove(); div.remove();
jQuery.removeData($div[0], "olddisplay", true); jQuery.removeData($div[0], 'olddisplay', true);
}); });
test("outerWidth()", function() { test("outerWidth()", function() {
expect(11); expect(7);
equal( jQuery( window ).outerWidth(), null, "Test on window without margin option" );
equal( jQuery( window ).outerWidth( true ), null, "Test on window with margin option" );
equal( jQuery( document ).outerWidth(), null, "Test on document without margin option" );
equal( jQuery( document ).outerWidth( true ), null, "Test on document with margin option" );
var $div = jQuery("#nothiddendiv"); var $div = jQuery("#nothiddendiv");
$div.css("width", 30); $div.css("width", 30);
@ -208,41 +191,11 @@ test("outerWidth()", function() {
equals( div.outerWidth(), 0, "Make sure that disconnected nodes are handled." ); equals( div.outerWidth(), 0, "Make sure that disconnected nodes are handled." );
div.remove(); div.remove();
jQuery.removeData($div[0], "olddisplay", true); jQuery.removeData($div[0], 'olddisplay', true);
});
test("child of a hidden elem has accurate inner/outer/Width()/Height() see #9441 #9300", function() {
expect(8);
// setup html
var $divNormal = jQuery("<div>").css({ width: "100px", height: "100px", border: "10px solid white", padding: "2px", margin: "3px" }),
$divChild = $divNormal.clone(),
$divHiddenParent = jQuery("<div>").css( "display", "none" ).append( $divChild ).appendTo("body");
$divNormal.appendTo("body");
// tests that child div of a hidden div works the same as a normal div
equals( $divChild.width(), $divNormal.width(), "child of a hidden element width() is wrong see #9441" );
equals( $divChild.innerWidth(), $divNormal.innerWidth(), "child of a hidden element innerWidth() is wrong see #9441" );
equals( $divChild.outerWidth(), $divNormal.outerWidth(), "child of a hidden element outerWidth() is wrong see #9441" );
equals( $divChild.outerWidth(true), $divNormal.outerWidth( true ), "child of a hidden element outerWidth( true ) is wrong see #9300" );
equals( $divChild.height(), $divNormal.height(), "child of a hidden element height() is wrong see #9441" );
equals( $divChild.innerHeight(), $divNormal.innerHeight(), "child of a hidden element innerHeight() is wrong see #9441" );
equals( $divChild.outerHeight(), $divNormal.outerHeight(), "child of a hidden element outerHeight() is wrong see #9441" );
equals( $divChild.outerHeight(true), $divNormal.outerHeight( true ), "child of a hidden element outerHeight( true ) is wrong see #9300" );
// teardown html
$divHiddenParent.remove();
$divNormal.remove();
}); });
test("outerHeight()", function() { test("outerHeight()", function() {
expect(11); expect(7);
equal( jQuery( window ).outerHeight(), null, "Test on window without margin option" );
equal( jQuery( window ).outerHeight( true ), null, "Test on window with margin option" );
equal( jQuery( document ).outerHeight(), null, "Test on document without margin option" );
equal( jQuery( document ).outerHeight( true ), null, "Test on document with margin option" );
var $div = jQuery("#nothiddendiv"); var $div = jQuery("#nothiddendiv");
$div.css("height", 30); $div.css("height", 30);
@ -267,5 +220,5 @@ test("outerHeight()", function() {
equals( div.outerHeight(), 0, "Make sure that disconnected nodes are handled." ); equals( div.outerHeight(), 0, "Make sure that disconnected nodes are handled." );
div.remove(); div.remove();
jQuery.removeData($div[0], "olddisplay", true); jQuery.removeData($div[0], 'olddisplay', true);
}); });

257
test/unit/effects.js vendored
View file

@ -2,7 +2,7 @@ module("effects", { teardown: moduleTeardown });
test("sanity check", function() { test("sanity check", function() {
expect(1); expect(1);
ok( jQuery("#dl:visible, #qunit-fixture:visible, #foo:visible").length === 3, "QUnit state is correct for testing effects" ); ok( jQuery("#dl:visible, #main:visible, #foo:visible").length === 3, "QUnit state is correct for testing effects" );
}); });
test("show()", function() { test("show()", function() {
@ -14,7 +14,7 @@ test("show()", function() {
equals( hiddendiv.css("display"), "block", "Make sure a pre-hidden div is visible." ); equals( hiddendiv.css("display"), "block", "Make sure a pre-hidden div is visible." );
var div = jQuery("<div>").hide().appendTo("#qunit-fixture").show(); var div = jQuery("<div>").hide().appendTo("#main").show();
equal( div.css("display"), "block", "Make sure pre-hidden divs show" ); equal( div.css("display"), "block", "Make sure pre-hidden divs show" );
@ -32,8 +32,7 @@ test("show()", function() {
hiddendiv.css("display",""); hiddendiv.css("display","");
var pass = true; var pass = true, div = jQuery("#main div");
div = jQuery("#qunit-fixture div");
div.show().each(function(){ div.show().each(function(){
if ( this.style.display == "none" ) pass = false; if ( this.style.display == "none" ) pass = false;
}); });
@ -63,7 +62,7 @@ test("show()", function() {
}); });
// #show-tests * is set display: none in CSS // #show-tests * is set display: none in CSS
jQuery("#qunit-fixture").append("<div id='show-tests'><div><p><a href='#'></a></p><code></code><pre></pre><span></span></div><table><thead><tr><th></th></tr></thead><tbody><tr><td></td></tr></tbody></table><ul><li></li></ul></div><table id='test-table'></table>"); jQuery("#main").append('<div id="show-tests"><div><p><a href="#"></a></p><code></code><pre></pre><span></span></div><table><thead><tr><th></th></tr></thead><tbody><tr><td></td></tr></tbody></table><ul><li></li></ul></div><table id="test-table"></table>');
var old = jQuery("#test-table").show().css("display") !== "table"; var old = jQuery("#test-table").show().css("display") !== "table";
jQuery("#test-table").remove(); jQuery("#test-table").remove();
@ -89,10 +88,6 @@ test("show()", function() {
var elem = jQuery(selector, "#show-tests").show(); var elem = jQuery(selector, "#show-tests").show();
equals( elem.css("display"), expected, "Show using correct display type for " + selector ); equals( elem.css("display"), expected, "Show using correct display type for " + selector );
}); });
// Make sure that showing or hiding a text node doesn't cause an error
jQuery("<div>test</div> text <span>test</span>").show().remove();
jQuery("<div>test</div> text <span>test</span>").hide().remove();
}); });
test("show(Number) - other displays", function() { test("show(Number) - other displays", function() {
@ -101,7 +96,7 @@ test("show(Number) - other displays", function() {
stop(); stop();
// #show-tests * is set display: none in CSS // #show-tests * is set display: none in CSS
jQuery("#qunit-fixture").append("<div id='show-tests'><div><p><a href='#'></a></p><code></code><pre></pre><span></span></div><table><thead><tr><th></th></tr></thead><tbody><tr><td></td></tr></tbody></table><ul><li></li></ul></div><table id='test-table'></table>"); jQuery("#main").append('<div id="show-tests"><div><p><a href="#"></a></p><code></code><pre></pre><span></span></div><table><thead><tr><th></th></tr></thead><tbody><tr><td></td></tr></tbody></table><ul><li></li></ul></div><table id="test-table"></table>');
var old = jQuery("#test-table").show().css("display") !== "table", var old = jQuery("#test-table").show().css("display") !== "table",
num = 0; num = 0;
@ -143,11 +138,11 @@ test("Persist correct display value", function() {
stop(); stop();
// #show-tests * is set display: none in CSS // #show-tests * is set display: none in CSS
jQuery("#qunit-fixture").append("<div id='show-tests'><span style='position:absolute;'>foo</span></div>"); jQuery("#main").append('<div id="show-tests"><span style="position:absolute;">foo</span></div>');
var $span = jQuery("#show-tests span"), var $span = jQuery("#show-tests span"),
displayNone = $span.css("display"), displayNone = $span.css("display"),
display = "", num = 0; display = '', num = 0;
$span.show(); $span.show();
@ -167,35 +162,13 @@ test("Persist correct display value", function() {
}); });
}); });
test("show() resolves correct default display #8099", function() {
expect(7);
var tt8099 = jQuery("<tt/>").appendTo("body"),
dfn8099 = jQuery("<dfn/>", { html: "foo"}).appendTo("body");
equals( tt8099.css("display"), "none", "default display override for all tt" );
equals( tt8099.show().css("display"), "inline", "Correctly resolves display:inline" );
equals( jQuery("#foo").hide().show().css("display"), "block", "Correctly resolves display:block after hide/show" );
equals( tt8099.hide().css("display"), "none", "default display override for all tt" );
equals( tt8099.show().css("display"), "inline", "Correctly resolves display:inline" );
equals( dfn8099.css("display"), "none", "default display override for all dfn" );
equals( dfn8099.show().css("display"), "inline", "Correctly resolves display:inline" );
tt8099.remove();
dfn8099.remove();
});
test("animate(Hash, Object, Function)", function() { test("animate(Hash, Object, Function)", function() {
expect(1); expect(1);
stop(); stop();
var hash = {opacity: "show"}; var hash = {opacity: 'show'};
var hashCopy = jQuery.extend({}, hash); var hashCopy = jQuery.extend({}, hash);
jQuery("#foo").animate(hash, 0, function() { jQuery('#foo').animate(hash, 0, function() {
equals( hash.opacity, hashCopy.opacity, "Check if animate changed the hash parameter" ); equals( hash.opacity, hashCopy.opacity, 'Check if animate changed the hash parameter' );
start(); start();
}); });
}); });
@ -220,7 +193,7 @@ test("animate block as inline width/height", function() {
if ( jQuery.support.inlineBlockNeedsLayout || expected === "inline-block" ) { if ( jQuery.support.inlineBlockNeedsLayout || expected === "inline-block" ) {
stop(); stop();
jQuery("#foo").css({ display: "inline", width: "", height: "" }).animate({ width: 42, height: 42 }, 100, function() { jQuery("#foo").css({ display: "inline", width: '', height: '' }).animate({ width: 42, height: 42 }, 100, function() {
equals( jQuery(this).css("display"), jQuery.support.inlineBlockNeedsLayout ? "inline" : "inline-block", "inline-block was set on non-floated inline element when animating width/height" ); equals( jQuery(this).css("display"), jQuery.support.inlineBlockNeedsLayout ? "inline" : "inline-block", "inline-block was set on non-floated inline element when animating width/height" );
equals( this.offsetWidth, 42, "width was animated" ); equals( this.offsetWidth, 42, "width was animated" );
equals( this.offsetHeight, 42, "height was animated" ); equals( this.offsetHeight, 42, "height was animated" );
@ -245,9 +218,9 @@ test("animate native inline width/height", function() {
if ( jQuery.support.inlineBlockNeedsLayout || expected === "inline-block" ) { if ( jQuery.support.inlineBlockNeedsLayout || expected === "inline-block" ) {
stop(); stop();
jQuery("#foo").css({ display: "", width: "", height: "" }) jQuery("#foo").css({ display: "", width: '', height: '' })
.append("<span>text</span>") .append('<span>text</span>')
.children("span") .children('span')
.animate({ width: 42, height: 42 }, 100, function() { .animate({ width: 42, height: 42 }, 100, function() {
equals( jQuery(this).css("display"), "inline-block", "inline-block was set on non-floated inline element when animating width/height" ); equals( jQuery(this).css("display"), "inline-block", "inline-block was set on non-floated inline element when animating width/height" );
equals( this.offsetWidth, 42, "width was animated" ); equals( this.offsetWidth, 42, "width was animated" );
@ -344,13 +317,13 @@ test("animate option (queue === false)", function () {
var order = []; var order = [];
var $foo = jQuery("#foo"); var $foo = jQuery("#foo");
$foo.animate({width:"100px"}, 3000, function () { $foo.animate({width:'100px'}, 3000, function () {
// should finish after unqueued animation so second // should finish after unqueued animation so second
order.push(2); order.push(2);
same( order, [ 1, 2 ], "Animations finished in the correct order" ); same( order, [ 1, 2 ], "Animations finished in the correct order" );
start(); start();
}); });
$foo.animate({fontSize:"2em"}, {queue:false, duration:10, complete:function () { $foo.animate({fontSize:'2em'}, {queue:false, duration:10, complete:function () {
// short duration and out of queue so should finish first // short duration and out of queue so should finish first
order.push(1); order.push(1);
}}); }});
@ -460,7 +433,7 @@ test("stop()", function() {
var w = 0; var w = 0;
$foo.hide().width(200).width(); $foo.hide().width(200).width();
$foo.animate({ width: "show" }, 1000); $foo.animate({ width:'show' }, 1000);
setTimeout(function(){ setTimeout(function(){
var nw = $foo.width(); var nw = $foo.width();
notEqual( nw, w, "An animation occurred " + nw + "px " + w + "px"); notEqual( nw, w, "An animation occurred " + nw + "px " + w + "px");
@ -485,9 +458,9 @@ test("stop() - several in queue", function() {
var w = 0; var w = 0;
$foo.hide().width(200).width(); $foo.hide().width(200).width();
$foo.animate({ width: "show" }, 1000); $foo.animate({ width:'show' }, 1000);
$foo.animate({ width: "hide" }, 1000); $foo.animate({ width:'hide' }, 1000);
$foo.animate({ width: "show" }, 1000); $foo.animate({ width:'show' }, 1000);
setTimeout(function(){ setTimeout(function(){
equals( $foo.queue().length, 3, "All 3 still in the queue" ); equals( $foo.queue().length, 3, "All 3 still in the queue" );
var nw = $foo.width(); var nw = $foo.width();
@ -510,9 +483,9 @@ test("stop(clearQueue)", function() {
var w = 0; var w = 0;
$foo.hide().width(200).width(); $foo.hide().width(200).width();
$foo.animate({ width: "show" }, 1000); $foo.animate({ width:'show' }, 1000);
$foo.animate({ width: "hide" }, 1000); $foo.animate({ width:'hide' }, 1000);
$foo.animate({ width: "show" }, 1000); $foo.animate({ width:'show' }, 1000);
setTimeout(function(){ setTimeout(function(){
var nw = $foo.width(); var nw = $foo.width();
ok( nw != w, "An animation occurred " + nw + "px " + w + "px"); ok( nw != w, "An animation occurred " + nw + "px " + w + "px");
@ -537,10 +510,10 @@ test("stop(clearQueue, gotoEnd)", function() {
var w = 0; var w = 0;
$foo.hide().width(200).width(); $foo.hide().width(200).width();
$foo.animate({ width: "show" }, 1000); $foo.animate({ width:'show' }, 1000);
$foo.animate({ width: "hide" }, 1000); $foo.animate({ width:'hide' }, 1000);
$foo.animate({ width: "show" }, 1000); $foo.animate({ width:'show' }, 1000);
$foo.animate({ width: "hide" }, 1000); $foo.animate({ width:'hide' }, 1000);
setTimeout(function(){ setTimeout(function(){
var nw = $foo.width(); var nw = $foo.width();
ok( nw != w, "An animation occurred " + nw + "px " + w + "px"); ok( nw != w, "An animation occurred " + nw + "px " + w + "px");
@ -583,10 +556,10 @@ jQuery.checkOverflowDisplay = function(){
equals(jQuery.css( this, "display" ), "inline", "Display shouldn't be tampered with."); equals(jQuery.css( this, "display" ), "inline", "Display shouldn't be tampered with.");
start(); start();
}; }
test( "jQuery.fx.prototype.cur()", 6, function() { test( "jQuery.fx.prototype.cur()", 6, function() {
var div = jQuery( "<div></div>" ).appendTo( "#qunit-fixture" ).css({ var div = jQuery( "<div></div>" ).appendTo( "#main" ).css({
color: "#ABC", color: "#ABC",
border: "5px solid black", border: "5px solid black",
left: "auto", left: "auto",
@ -695,8 +668,8 @@ jQuery.each( {
jQuery(elem).css(prop,prop == "opacity" ? 0 : "0px"); jQuery(elem).css(prop,prop == "opacity" ? 0 : "0px");
return 0; return 0;
} }
}, function( fn, f ) { }, function(fn, f){
jQuery.each({ jQuery.each( {
"show": function(elem,prop){ "show": function(elem,prop){
jQuery(elem).hide().addClass("wide"+prop); jQuery(elem).hide().addClass("wide"+prop);
return "show"; return "show";
@ -744,64 +717,59 @@ jQuery.each( {
var anim = { width: t_w, height: t_h, opacity: t_o }; var anim = { width: t_w, height: t_h, opacity: t_o };
elem.animate(anim, 50); elem.animate(anim, 50, function(){
jQuery.when( elem ).done(function( elem ){
elem = elem[ 0 ];
if ( t_w == "show" ) if ( t_w == "show" )
equals( elem.style.display, "block", "Showing, display should block: " + elem.style.display); equals( this.style.display, "block", "Showing, display should block: " + this.style.display);
if ( t_w == "hide"||t_w == "show" ) if ( t_w == "hide"||t_w == "show" )
ok(f_w === "" ? elem.style.width === f_w : elem.style.width.indexOf(f_w) === 0, "Width must be reset to " + f_w + ": " + elem.style.width); ok(f_w === "" ? this.style.width === f_w : this.style.width.indexOf(f_w) === 0, "Width must be reset to " + f_w + ": " + this.style.width);
if ( t_h == "hide"||t_h == "show" ) if ( t_h == "hide"||t_h == "show" )
ok(f_h === "" ? elem.style.height === f_h : elem.style.height.indexOf(f_h) === 0, "Height must be reset to " + f_h + ": " + elem.style.height); ok(f_h === "" ? this.style.height === f_h : this.style.height.indexOf(f_h) === 0, "Height must be reset to " + f_h + ": " + this.style.height);
var cur_o = jQuery.style(elem, "opacity"); var cur_o = jQuery.style(this, "opacity");
if ( t_o == "hide" || t_o == "show" ) if ( t_o == "hide" || t_o == "show" )
equals(cur_o, f_o, "Opacity must be reset to " + f_o + ": " + cur_o); equals(cur_o, f_o, "Opacity must be reset to " + f_o + ": " + cur_o);
if ( t_w == "hide" ) if ( t_w == "hide" )
equals(elem.style.display, "none", "Hiding, display should be none: " + elem.style.display); equals(this.style.display, "none", "Hiding, display should be none: " + this.style.display);
if ( t_o.constructor == Number ) { if ( t_o.constructor == Number ) {
equals(cur_o, t_o, "Final opacity should be " + t_o + ": " + cur_o); equals(cur_o, t_o, "Final opacity should be " + t_o + ": " + cur_o);
ok(jQuery.css(elem, "opacity") != "" || cur_o == t_o, "Opacity should be explicitly set to " + t_o + ", is instead: " + cur_o); ok(jQuery.css(this, "opacity") != "" || cur_o == t_o, "Opacity should be explicitly set to " + t_o + ", is instead: " + cur_o);
} }
if ( t_w.constructor == Number ) { if ( t_w.constructor == Number ) {
equals(elem.style.width, t_w + "px", "Final width should be " + t_w + ": " + elem.style.width); equals(this.style.width, t_w + "px", "Final width should be " + t_w + ": " + this.style.width);
var cur_w = jQuery.css(elem,"width"); var cur_w = jQuery.css(this,"width");
ok(elem.style.width != "" || cur_w == t_w, "Width should be explicitly set to " + t_w + ", is instead: " + cur_w); ok(this.style.width != "" || cur_w == t_w, "Width should be explicitly set to " + t_w + ", is instead: " + cur_w);
} }
if ( t_h.constructor == Number ) { if ( t_h.constructor == Number ) {
equals(elem.style.height, t_h + "px", "Final height should be " + t_h + ": " + elem.style.height); equals(this.style.height, t_h + "px", "Final height should be " + t_h + ": " + this.style.height);
var cur_h = jQuery.css(elem,"height"); var cur_h = jQuery.css(this,"height");
ok(elem.style.height != "" || cur_h == t_h, "Height should be explicitly set to " + t_h + ", is instead: " + cur_w); ok(this.style.height != "" || cur_h == t_h, "Height should be explicitly set to " + t_h + ", is instead: " + cur_w);
} }
if ( t_h == "show" ) { if ( t_h == "show" ) {
var old_h = jQuery.css(elem, "height"); var old_h = jQuery.css(this, "height");
jQuery(elem).append("<br/>Some more text<br/>and some more..."); jQuery(this).append("<br/>Some more text<br/>and some more...");
if ( /Auto/.test( fn ) ) { if ( /Auto/.test( fn ) ) {
notEqual(jQuery.css(elem, "height"), old_h, "Make sure height is auto."); notEqual(jQuery.css(this, "height"), old_h, "Make sure height is auto.");
} else { } else {
equals(jQuery.css(elem, "height"), old_h, "Make sure height is not auto."); equals(jQuery.css(this, "height"), old_h, "Make sure height is not auto.");
} }
} }
// manually remove generated element // manually remove generated element
jQuery(elem).remove(); jQuery(this).remove();
start(); start();
}); });
@ -810,7 +778,7 @@ jQuery.each( {
}); });
jQuery.fn.saveState = function(hiddenOverflow){ jQuery.fn.saveState = function(hiddenOverflow){
var check = ["opacity", "height", "width", "display", "overflow"]; var check = ['opacity','height','width','display','overflow'];
expect(check.length); expect(check.length);
stop(); stop();
@ -831,64 +799,64 @@ jQuery.checkState = function(){
}); });
// manually clean data on modified element // manually clean data on modified element
jQuery.removeData(this, "olddisplay", true); jQuery.removeData(this, 'olddisplay', true);
start(); start();
}; }
// Chaining Tests // Chaining Tests
test("Chain fadeOut fadeIn", function() { test("Chain fadeOut fadeIn", function() {
jQuery("#fadein div").saveState().fadeOut("fast").fadeIn("fast",jQuery.checkState); jQuery('#fadein div').saveState().fadeOut('fast').fadeIn('fast',jQuery.checkState);
}); });
test("Chain fadeIn fadeOut", function() { test("Chain fadeIn fadeOut", function() {
jQuery("#fadeout div").saveState().fadeIn("fast").fadeOut("fast",jQuery.checkState); jQuery('#fadeout div').saveState().fadeIn('fast').fadeOut('fast',jQuery.checkState);
}); });
test("Chain hide show", function() { test("Chain hide show", function() {
jQuery("#show div").saveState(jQuery.support.shrinkWrapBlocks).hide("fast").show("fast",jQuery.checkState); jQuery('#show div').saveState(jQuery.support.shrinkWrapBlocks).hide('fast').show('fast',jQuery.checkState);
}); });
test("Chain show hide", function() { test("Chain show hide", function() {
jQuery("#hide div").saveState(jQuery.support.shrinkWrapBlocks).show("fast").hide("fast",jQuery.checkState); jQuery('#hide div').saveState(jQuery.support.shrinkWrapBlocks).show('fast').hide('fast',jQuery.checkState);
}); });
test("Chain show hide with easing and callback", function() { test("Chain show hide with easing and callback", function() {
jQuery("#hide div").saveState().show("fast").hide("fast","linear",jQuery.checkState); jQuery('#hide div').saveState().show('fast').hide('fast','linear',jQuery.checkState);
}); });
test("Chain toggle in", function() { test("Chain toggle in", function() {
jQuery("#togglein div").saveState(jQuery.support.shrinkWrapBlocks).toggle("fast").toggle("fast",jQuery.checkState); jQuery('#togglein div').saveState(jQuery.support.shrinkWrapBlocks).toggle('fast').toggle('fast',jQuery.checkState);
}); });
test("Chain toggle out", function() { test("Chain toggle out", function() {
jQuery("#toggleout div").saveState(jQuery.support.shrinkWrapBlocks).toggle("fast").toggle("fast",jQuery.checkState); jQuery('#toggleout div').saveState(jQuery.support.shrinkWrapBlocks).toggle('fast').toggle('fast',jQuery.checkState);
}); });
test("Chain toggle out with easing and callback", function() { test("Chain toggle out with easing and callback", function() {
jQuery("#toggleout div").saveState(jQuery.support.shrinkWrapBlocks).toggle("fast").toggle("fast","linear",jQuery.checkState); jQuery('#toggleout div').saveState(jQuery.support.shrinkWrapBlocks).toggle('fast').toggle('fast','linear',jQuery.checkState);
}); });
test("Chain slideDown slideUp", function() { test("Chain slideDown slideUp", function() {
jQuery("#slidedown div").saveState(jQuery.support.shrinkWrapBlocks).slideDown("fast").slideUp("fast",jQuery.checkState); jQuery('#slidedown div').saveState(jQuery.support.shrinkWrapBlocks).slideDown('fast').slideUp('fast',jQuery.checkState);
}); });
test("Chain slideUp slideDown", function() { test("Chain slideUp slideDown", function() {
jQuery("#slideup div").saveState(jQuery.support.shrinkWrapBlocks).slideUp("fast").slideDown("fast",jQuery.checkState); jQuery('#slideup div').saveState(jQuery.support.shrinkWrapBlocks).slideUp('fast').slideDown('fast',jQuery.checkState);
}); });
test("Chain slideUp slideDown with easing and callback", function() { test("Chain slideUp slideDown with easing and callback", function() {
jQuery("#slideup div").saveState(jQuery.support.shrinkWrapBlocks).slideUp("fast").slideDown("fast","linear",jQuery.checkState); jQuery('#slideup div').saveState(jQuery.support.shrinkWrapBlocks).slideUp('fast').slideDown('fast','linear',jQuery.checkState);
}); });
test("Chain slideToggle in", function() { test("Chain slideToggle in", function() {
jQuery("#slidetogglein div").saveState(jQuery.support.shrinkWrapBlocks).slideToggle("fast").slideToggle("fast",jQuery.checkState); jQuery('#slidetogglein div').saveState(jQuery.support.shrinkWrapBlocks).slideToggle('fast').slideToggle('fast',jQuery.checkState);
}); });
test("Chain slideToggle out", function() { test("Chain slideToggle out", function() {
jQuery("#slidetoggleout div").saveState(jQuery.support.shrinkWrapBlocks).slideToggle("fast").slideToggle("fast",jQuery.checkState); jQuery('#slidetoggleout div').saveState(jQuery.support.shrinkWrapBlocks).slideToggle('fast').slideToggle('fast',jQuery.checkState);
}); });
test("Chain fadeToggle in", function() { test("Chain fadeToggle in", function() {
jQuery("#fadetogglein div").saveState().fadeToggle("fast").fadeToggle("fast",jQuery.checkState); jQuery('#fadetogglein div').saveState().fadeToggle('fast').fadeToggle('fast',jQuery.checkState);
}); });
test("Chain fadeToggle out", function() { test("Chain fadeToggle out", function() {
jQuery("#fadetoggleout div").saveState().fadeToggle("fast").fadeToggle("fast",jQuery.checkState); jQuery('#fadetoggleout div').saveState().fadeToggle('fast').fadeToggle('fast',jQuery.checkState);
}); });
test("Chain fadeTo 0.5 1.0 with easing and callback)", function() { test("Chain fadeTo 0.5 1.0 with easing and callback)", function() {
jQuery("#fadeto div").saveState().fadeTo("fast",0.5).fadeTo("fast",1.0,"linear",jQuery.checkState); jQuery('#fadeto div').saveState().fadeTo('fast',0.5).fadeTo('fast',1.0,'linear',jQuery.checkState);
}); });
jQuery.makeTest = function( text ){ jQuery.makeTest = function( text ){
@ -902,7 +870,7 @@ jQuery.makeTest = function( text ){
.after( elem ); .after( elem );
return elem; return elem;
}; }
jQuery.makeTest.id = 1; jQuery.makeTest.id = 1;
@ -923,42 +891,34 @@ test("jQuery.show('fast') doesn't clear radio buttons (bug #1095)", function ()
test("animate with per-property easing", function(){ test("animate with per-property easing", function(){
expect(5); expect(3);
stop(); stop();
var data = { a:0, b:0, c:0 }, var _test1_called = false;
_test1_called = false, var _test2_called = false;
_test2_called = false, var _default_test_called = false;
_default_test_called = false,
props = {
a: [ 100, "_test1" ],
b: [ 100, "_test2" ],
c: 100
};
jQuery.easing["_test1"] = function(p) { jQuery.easing['_test1'] = function() {
_test1_called = true; _test1_called = true;
return p;
}; };
jQuery.easing["_test2"] = function(p) { jQuery.easing['_test2'] = function() {
_test2_called = true; _test2_called = true;
return p;
}; };
jQuery.easing["_default_test"] = function(p) { jQuery.easing['_default_test'] = function() {
_default_test_called = true; _default_test_called = true;
return p;
}; };
jQuery(data).animate( props, 400, "_default_test", function(){ jQuery({a:0,b:0,c:0}).animate({
a: [100, '_test1'],
b: [100, '_test2'],
c: 100
}, 400, '_default_test', function(){
start(); start();
ok(_test1_called, "Easing function (1) called");
ok( _test1_called, "Easing function (_test1) called" ); ok(_test2_called, "Easing function (2) called");
ok( _test2_called, "Easing function (_test2) called" ); ok(_default_test_called, "Easing function (_default) called");
ok( _default_test_called, "Easing function (_default) called" );
equal( props.a[ 1 ], "_test1", "animate does not change original props (per-property easing would be lost)");
equal( props.b[ 1 ], "_test2", "animate does not change original props (per-property easing would be lost)");
}); });
}); });
@ -967,7 +927,7 @@ test("hide hidden elements (bug #7141)", function() {
expect(3); expect(3);
QUnit.reset(); QUnit.reset();
var div = jQuery("<div style='display:none'></div>").appendTo("#qunit-fixture"); var div = jQuery("<div style='display:none'></div>").appendTo("#main");
equals( div.css("display"), "none", "Element is hidden by default" ); equals( div.css("display"), "none", "Element is hidden by default" );
div.hide(); div.hide();
ok( !jQuery._data(div, "olddisplay"), "olddisplay is undefined after hiding an already-hidden element" ); ok( !jQuery._data(div, "olddisplay"), "olddisplay is undefined after hiding an already-hidden element" );
@ -982,7 +942,7 @@ test("hide hidden elements, with animation (bug #7141)", function() {
QUnit.reset(); QUnit.reset();
stop(); stop();
var div = jQuery("<div style='display:none'></div>").appendTo("#qunit-fixture"); var div = jQuery("<div style='display:none'></div>").appendTo("#main");
equals( div.css("display"), "none", "Element is hidden by default" ); equals( div.css("display"), "none", "Element is hidden by default" );
div.hide(1, function () { div.hide(1, function () {
ok( !jQuery._data(div, "olddisplay"), "olddisplay is undefined after hiding an already-hidden element" ); ok( !jQuery._data(div, "olddisplay"), "olddisplay is undefined after hiding an already-hidden element" );
@ -995,53 +955,10 @@ test("hide hidden elements, with animation (bug #7141)", function() {
test("animate unit-less properties (#4966)", 2, function() { test("animate unit-less properties (#4966)", 2, function() {
stop(); stop();
var div = jQuery( "<div style='z-index: 0; position: absolute;'></div>" ).appendTo( "#qunit-fixture" ); var div = jQuery( "<div style='z-index: 0; position: absolute;'></div>" ).appendTo( "#main" );
equal( div.css( "z-index" ), "0", "z-index is 0" ); equal( div.css( "z-index" ), "0", "z-index is 0" );
div.animate({ zIndex: 2 }, function() { div.animate({ zIndex: 2 }, function() {
equal( div.css( "z-index" ), "2", "z-index is 2" ); equal( div.css( "z-index" ), "2", "z-index is 2" );
start(); start();
}); });
}); });
test( "animate properties missing px w/ opacity as last (#9074)", 2, function() {
expect( 6 );
stop();
var div = jQuery( "<div style='position: absolute; margin-left: 0; left: 0px;'></div>" )
.appendTo( "#qunit-fixture" );
function cssInt( prop ) {
return parseInt( div.css( prop ), 10 );
}
equal( cssInt( "marginLeft" ), 0, "Margin left is 0" );
equal( cssInt( "left" ), 0, "Left is 0" );
div.animate({
left: 200,
marginLeft: 200,
opacity: 0
}, 1000);
setTimeout(function() {
var ml = cssInt( "marginLeft" ),
l = cssInt( "left" );
notEqual( ml, 0, "Margin left is not 0 after partial animate" );
notEqual( ml, 200, "Margin left is not 200 after partial animate" );
notEqual( l, 0, "Left is not 0 after partial animate" );
notEqual( l, 200, "Left is not 200 after partial animate" );
div.stop().remove();
start();
}, 100);
});
test("callbacks should fire in correct order (#9100)", function() {
stop();
var a = 1,
cb = 0,
$lis = jQuery("<p data-operation='*2'></p><p data-operation='^2'></p>").appendTo("#qunit-fixture")
// The test will always pass if no properties are animated or if the duration is 0
.animate({fontSize: 12}, 13, function() {
a *= jQuery(this).data("operation") === "*2" ? 2 : a;
cb++;
if ( cb === 2 ) {
equal( a, 4, "test value has been *2 and _then_ ^2");
start();
}
});
});

View file

@ -14,28 +14,8 @@ test("null or undefined handler", function() {
} catch (e) {} } catch (e) {}
}); });
test("bind(),live(),delegate() with non-null,defined data", function() {
expect(3);
var handler = function( event, data ) {
equal( data, 0, "non-null, defined data (zero) is correctly passed" );
};
jQuery("#foo").bind("foo", handler);
jQuery("#foo").live("foo", handler);
jQuery("div").delegate("#foo", "foo", handler);
jQuery("#foo").trigger("foo", 0);
jQuery("#foo").unbind("foo", handler);
jQuery("#foo").die("foo", handler);
jQuery("div").undelegate("#foo", "foo");
});
test("bind(), with data", function() { test("bind(), with data", function() {
expect(4); expect(3);
var handler = function(event) { var handler = function(event) {
ok( event.data, "bind() with data, check passed data exists" ); ok( event.data, "bind() with data, check passed data exists" );
equals( event.data.foo, "bar", "bind() with data, Check value of passed data" ); equals( event.data.foo, "bar", "bind() with data, Check value of passed data" );
@ -43,12 +23,6 @@ test("bind(), with data", function() {
jQuery("#firstp").bind("click", {foo: "bar"}, handler).click().unbind("click", handler); jQuery("#firstp").bind("click", {foo: "bar"}, handler).click().unbind("click", handler);
ok( !jQuery._data(jQuery("#firstp")[0], "events"), "Event handler unbound when using data." ); ok( !jQuery._data(jQuery("#firstp")[0], "events"), "Event handler unbound when using data." );
var test = function(){};
var handler2 = function(event) {
equals( event.data, test, "bind() with function data, Check value of passed data" );
};
jQuery("#firstp").bind("click", test, handler2).click().unbind("click", handler2);
}); });
test("click(), with data", function() { test("click(), with data", function() {
@ -88,22 +62,6 @@ test("bind(), multiple events at once", function() {
equals( mouseoverCounter, 1, "bind() with multiple events at once" ); equals( mouseoverCounter, 1, "bind() with multiple events at once" );
}); });
test("bind(), five events at once", function() {
expect(1);
var count = 0,
handler = function(event) {
count++;
};
jQuery("#firstp").bind("click mouseover foo bar baz", handler)
.trigger("click").trigger("mouseover")
.trigger("foo").trigger("bar")
.trigger("baz");
equals( count, 5, "bind() five events at once" );
});
test("bind(), multiple events at once and namespaces", function() { test("bind(), multiple events at once and namespaces", function() {
expect(7); expect(7);
@ -205,7 +163,7 @@ test("bind(), namespace with special add", function() {
}); });
// Should trigger 2 // Should trigger 2
div.appendTo("#qunit-fixture").remove(); div.appendTo("#main").remove();
delete jQuery.event.special.test; delete jQuery.event.special.test;
}); });
@ -343,11 +301,11 @@ test("live/delegate immediate propagation", function() {
test("bind/delegate bubbling, isDefaultPrevented", function() { test("bind/delegate bubbling, isDefaultPrevented", function() {
expect(2); expect(2);
var $anchor2 = jQuery( "#anchor2" ), var $anchor2 = jQuery( "#anchor2" ),
$main = jQuery( "#qunit-fixture" ), $main = jQuery( "#main" ),
fakeClick = function($jq) { fakeClick = function($jq) {
// Use a native click so we don't get jQuery simulated bubbling // Use a native click so we don't get jQuery simulated bubbling
if ( document.createEvent ) { if ( document.createEvent ) {
var e = document.createEvent( "MouseEvents" ); var e = document.createEvent( 'MouseEvents' );
e.initEvent( "click", true, true ); e.initEvent( "click", true, true );
$jq[0].dispatchEvent(e); $jq[0].dispatchEvent(e);
} }
@ -389,7 +347,7 @@ test("bind(), iframes", function() {
jQuery("div", doc).bind("click", function() { jQuery("div", doc).bind("click", function() {
ok( true, "Binding to element inside iframe" ); ok( true, "Binding to element inside iframe" );
}).click().unbind("click"); }).click().unbind('click');
}); });
test("bind(), trigger change on select", function() { test("bind(), trigger change on select", function() {
@ -399,8 +357,8 @@ test("bind(), trigger change on select", function() {
equals( event.data, counter++, "Event.data is not a global event object" ); equals( event.data, counter++, "Event.data is not a global event object" );
}; };
jQuery("#form select").each(function(i){ jQuery("#form select").each(function(i){
jQuery(this).bind("change", i, selectOnChange); jQuery(this).bind('change', i, selectOnChange);
}).trigger("change"); }).trigger('change');
}); });
test("bind(), namespaced events, cloned events", 18, function() { test("bind(), namespaced events, cloned events", 18, function() {
@ -451,7 +409,7 @@ test("bind(), namespaced events, cloned events", 18, function() {
}).trigger("tester"); }).trigger("tester");
// Make sure events stick with appendTo'd elements (which are cloned) #2027 // Make sure events stick with appendTo'd elements (which are cloned) #2027
jQuery("<a href='#fail' class='test'>test</a>").click(function(){ return false; }).appendTo("#qunit-fixture"); jQuery("<a href='#fail' class='test'>test</a>").click(function(){ return false; }).appendTo("#main");
ok( jQuery("a.test:first").triggerHandler("click") === false, "Handler is bound to appendTo'd elements" ); ok( jQuery("a.test:first").triggerHandler("click") === false, "Handler is bound to appendTo'd elements" );
}); });
@ -574,7 +532,7 @@ test("bind(name, false), unbind(name, false)", function() {
expect(3); expect(3);
var main = 0; var main = 0;
jQuery("#qunit-fixture").bind("click", function(e){ main++; }); jQuery("#main").bind("click", function(e){ main++; });
jQuery("#ap").trigger("click"); jQuery("#ap").trigger("click");
equals( main, 1, "Verify that the trigger happened correctly." ); equals( main, 1, "Verify that the trigger happened correctly." );
@ -589,48 +547,7 @@ test("bind(name, false), unbind(name, false)", function() {
equals( main, 1, "Verify that the trigger happened correctly." ); equals( main, 1, "Verify that the trigger happened correctly." );
// manually clean up events from elements outside the fixture // manually clean up events from elements outside the fixture
jQuery("#qunit-fixture").unbind("click"); jQuery("#main").unbind("click");
});
test("live(name, false), die(name, false)", function() {
expect(3);
var main = 0;
jQuery("#qunit-fixture").live("click", function(e){ main++; });
jQuery("#ap").trigger("click");
equals( main, 1, "Verify that the trigger happened correctly." );
main = 0;
jQuery("#ap").live("click", false);
jQuery("#ap").trigger("click");
equals( main, 0, "Verify that no bubble happened." );
main = 0;
jQuery("#ap").die("click", false);
jQuery("#ap").trigger("click");
equals( main, 1, "Verify that the trigger happened correctly." );
jQuery("#qunit-fixture").die("click");
});
test("delegate(selector, name, false), undelegate(selector, name, false)", function() {
expect(3);
var main = 0;
jQuery("#qunit-fixture").delegate("#ap", "click", function(e){ main++; });
jQuery("#ap").trigger("click");
equals( main, 1, "Verify that the trigger happened correctly." );
main = 0;
jQuery("#ap").delegate("#groups", "click", false);
jQuery("#groups").trigger("click");
equals( main, 0, "Verify that no bubble happened." );
main = 0;
jQuery("#ap").undelegate("#groups", "click", false);
jQuery("#groups").trigger("click");
equals( main, 1, "Verify that the trigger happened correctly." );
jQuery("#qunit-fixture").undelegate("#ap", "click");
}); });
test("bind()/trigger()/unbind() on plain object", function() { test("bind()/trigger()/unbind() on plain object", function() {
@ -688,23 +605,23 @@ test("unbind(type)", function() {
} }
message = "unbind passing function"; message = "unbind passing function";
$elem.bind("error1", error).unbind("error1", error).triggerHandler("error1"); $elem.bind('error1', error).unbind('error1',error).triggerHandler('error1');
message = "unbind all from event"; message = "unbind all from event";
$elem.bind("error1", error).unbind("error1").triggerHandler("error1"); $elem.bind('error1', error).unbind('error1').triggerHandler('error1');
message = "unbind all"; message = "unbind all";
$elem.bind("error1", error).unbind().triggerHandler("error1"); $elem.bind('error1', error).unbind().triggerHandler('error1');
message = "unbind many with function"; message = "unbind many with function";
$elem.bind("error1 error2",error) $elem.bind('error1 error2',error)
.unbind("error1 error2", error ) .unbind('error1 error2', error )
.trigger("error1").triggerHandler("error2"); .trigger('error1').triggerHandler('error2');
message = "unbind many"; // #3538 message = "unbind many"; // #3538
$elem.bind("error1 error2", error) $elem.bind('error1 error2',error)
.unbind("error1 error2") .unbind('error1 error2')
.trigger("error1").triggerHandler("error2"); .trigger('error1').triggerHandler('error2');
message = "unbind without a type or handler"; message = "unbind without a type or handler";
$elem.bind("error1 error2.test",error) $elem.bind("error1 error2.test",error)
@ -720,28 +637,28 @@ test("unbind(eventObject)", function() {
function assert( expected ){ function assert( expected ){
num = 0; num = 0;
$elem.trigger("foo").triggerHandler("bar"); $elem.trigger('foo').triggerHandler('bar');
equals( num, expected, "Check the right handlers are triggered" ); equals( num, expected, "Check the right handlers are triggered" );
} }
$elem $elem
// This handler shouldn't be unbound // This handler shouldn't be unbound
.bind("foo", function(){ .bind('foo', function(){
num += 1; num += 1;
}) })
.bind("foo", function(e){ .bind('foo', function(e){
$elem.unbind( e ) $elem.unbind( e )
num += 2; num += 2;
}) })
// Neither this one // Neither this one
.bind("bar", function(){ .bind('bar', function(){
num += 4; num += 4;
}); });
assert( 7 ); assert( 7 );
assert( 5 ); assert( 5 );
$elem.unbind("bar"); $elem.unbind('bar');
assert( 1 ); assert( 1 );
$elem.unbind(); $elem.unbind();
@ -774,55 +691,18 @@ test("mouseover triggers mouseenter", function() {
elem.mouseenter(function () { elem.mouseenter(function () {
count++; count++;
}); });
elem.trigger("mouseover"); elem.trigger('mouseover');
equals(count, 1, "make sure mouseover triggers a mouseenter" ); equals(count, 1, "make sure mouseover triggers a mouseenter" );
elem.remove(); elem.remove();
}); });
test("withinElement implemented with jQuery.contains()", function() {
expect(1);
jQuery("#qunit-fixture").append('<div id="jc-outer"><div id="jc-inner"></div></div>');
jQuery("#jc-outer").bind("mouseenter mouseleave", function( event ) {
equal( this.id, "jc-outer", this.id + " " + event.type );
}).trigger("mouseenter");
jQuery("#jc-inner").trigger("mousenter");
jQuery("#jc-outer").unbind("mouseenter mouseleave").remove();
jQuery("#jc-inner").remove();
});
test("mouseenter, mouseleave don't catch exceptions", function() {
expect(2);
var elem = jQuery("#firstp").hover(function() { throw "an Exception"; });
try {
elem.mouseenter();
} catch (e) {
equals( e, "an Exception", "mouseenter doesn't catch exceptions" );
}
try {
elem.mouseleave();
} catch (e) {
equals( e, "an Exception", "mouseleave doesn't catch exceptions" );
}
});
test("trigger() shortcuts", function() { test("trigger() shortcuts", function() {
expect(6); expect(6);
var elem = jQuery("<li><a href='#'>Change location</a></li>").prependTo("#firstUL"); var elem = jQuery('<li><a href="#">Change location</a></li>').prependTo('#firstUL');
elem.find("a").bind("click", function() { elem.find('a').bind('click', function() {
var close = jQuery("spanx", this); // same with jQuery(this).find("span"); var close = jQuery('spanx', this); // same with jQuery(this).find('span');
equals( close.length, 0, "Context element does not exist, length must be zero" ); equals( close.length, 0, "Context element does not exist, length must be zero" );
ok( !close[0], "Context element does not exist, direct access to element must return undefined" ); ok( !close[0], "Context element does not exist, direct access to element must return undefined" );
return false; return false;
@ -836,57 +716,48 @@ test("trigger() shortcuts", function() {
}).click(); }).click();
var counter = 0; var counter = 0;
jQuery("#firstp")[0].onclick = function(event) { jQuery('#firstp')[0].onclick = function(event) {
counter++; counter++;
}; };
jQuery("#firstp").click(); jQuery('#firstp').click();
equals( counter, 1, "Check that click, triggers onclick event handler also" ); equals( counter, 1, "Check that click, triggers onclick event handler also" );
var clickCounter = 0; var clickCounter = 0;
jQuery("#simon1")[0].onclick = function(event) { jQuery('#simon1')[0].onclick = function(event) {
clickCounter++; clickCounter++;
}; };
jQuery("#simon1").click(); jQuery('#simon1').click();
equals( clickCounter, 1, "Check that click, triggers onclick event handler on an a tag also" ); equals( clickCounter, 1, "Check that click, triggers onclick event handler on an a tag also" );
elem = jQuery("<img />").load(function(){ elem = jQuery('<img />').load(function(){
ok( true, "Trigger the load event, using the shortcut .load() (#2819)"); ok( true, "Trigger the load event, using the shortcut .load() (#2819)");
}).load(); }).load();
// manually clean up detached elements // manually clean up detached elements
elem.remove(); elem.remove();
// test that special handlers do not blow up with VML elements (#7071)
jQuery('<xml:namespace ns="urn:schemas-microsoft-com:vml" prefix="v" />').appendTo('head');
jQuery('<v:oval id="oval" style="width:100pt;height:75pt;" fillcolor="red"> </v:oval>').appendTo('#form');
jQuery("#oval").click().keydown();
}); });
test("trigger() bubbling", function() { test("trigger() bubbling", function() {
expect(17); expect(14);
var win = 0, doc = 0, html = 0, body = 0, main = 0, ap = 0; var doc = 0, html = 0, body = 0, main = 0, ap = 0;
jQuery(window).bind("click", function(e){ win++; });
jQuery(document).bind("click", function(e){ if ( e.target !== document) { doc++; } }); jQuery(document).bind("click", function(e){ if ( e.target !== document) { doc++; } });
jQuery("html").bind("click", function(e){ html++; }); jQuery("html").bind("click", function(e){ html++; });
jQuery("body").bind("click", function(e){ body++; }); jQuery("body").bind("click", function(e){ body++; });
jQuery("#qunit-fixture").bind("click", function(e){ main++; }); jQuery("#main").bind("click", function(e){ main++; });
jQuery("#ap").bind("click", function(){ ap++; return false; }); jQuery("#ap").bind("click", function(){ ap++; return false; });
jQuery("html").trigger("click"); jQuery("html").trigger("click");
equals( win, 1, "HTML bubble" );
equals( doc, 1, "HTML bubble" ); equals( doc, 1, "HTML bubble" );
equals( html, 1, "HTML bubble" ); equals( html, 1, "HTML bubble" );
jQuery("body").trigger("click"); jQuery("body").trigger("click");
equals( win, 2, "Body bubble" );
equals( doc, 2, "Body bubble" ); equals( doc, 2, "Body bubble" );
equals( html, 2, "Body bubble" ); equals( html, 2, "Body bubble" );
equals( body, 1, "Body bubble" ); equals( body, 1, "Body bubble" );
jQuery("#qunit-fixture").trigger("click"); jQuery("#main").trigger("click");
equals( win, 3, "Main bubble" );
equals( doc, 3, "Main bubble" ); equals( doc, 3, "Main bubble" );
equals( html, 3, "Main bubble" ); equals( html, 3, "Main bubble" );
equals( body, 2, "Main bubble" ); equals( body, 2, "Main bubble" );
@ -901,11 +772,11 @@ test("trigger() bubbling", function() {
// manually clean up events from elements outside the fixture // manually clean up events from elements outside the fixture
jQuery(document).unbind("click"); jQuery(document).unbind("click");
jQuery("html, body, #qunit-fixture").unbind("click"); jQuery("html, body, #main").unbind("click");
}); });
test("trigger(type, [data], [fn])", function() { test("trigger(type, [data], [fn])", function() {
expect(16); expect(14);
var handler = function(event, a, b, c) { var handler = function(event, a, b, c) {
equals( event.type, "click", "check passed data" ); equals( event.type, "click", "check passed data" );
@ -922,23 +793,6 @@ test("trigger(type, [data], [fn])", function() {
ok( true, "Native call was triggered" ); ok( true, "Native call was triggered" );
}; };
$elem.live('mouseenter', function(){
ok( true, 'Trigger mouseenter bound by live' );
});
$elem.live('mouseleave', function(){
ok( true, 'Trigger mouseleave bound by live' );
});
$elem.trigger('mouseenter');
$elem.trigger('mouseleave');
$elem.die('mouseenter');
$elem.die('mouseleave');
// Triggers handlrs and native // Triggers handlrs and native
// Trigger 5 // Trigger 5
$elem.bind("click", handler).trigger("click", [1, "2", "abc"]); $elem.bind("click", handler).trigger("click", [1, "2", "abc"]);
@ -954,7 +808,7 @@ test("trigger(type, [data], [fn])", function() {
var pass = true; var pass = true;
try { try {
jQuery("#form input:first").hide().trigger("focus"); jQuery('#form input:first').hide().trigger('focus');
} catch(e) { } catch(e) {
pass = false; pass = false;
} }
@ -962,7 +816,7 @@ test("trigger(type, [data], [fn])", function() {
pass = true; pass = true;
try { try {
jQuery("#qunit-fixture table:first").bind("test:test", function(){}).trigger("test:test"); jQuery('#main table:first').bind('test:test', function(){}).trigger('test:test');
} catch (e) { } catch (e) {
pass = false; pass = false;
} }
@ -1000,8 +854,8 @@ test("jQuery.Event.currentTarget", function(){
test("trigger(eventObject, [data], [fn])", function() { test("trigger(eventObject, [data], [fn])", function() {
expect(25); expect(25);
var $parent = jQuery("<div id='par' />").hide().appendTo("body"), var $parent = jQuery('<div id="par" />').hide().appendTo('body'),
$child = jQuery("<p id='child'>foo</p>").appendTo( $parent ); $child = jQuery('<p id="child">foo</p>').appendTo( $parent );
var event = jQuery.Event("noNew"); var event = jQuery.Event("noNew");
ok( event != window, "Instantiate jQuery.Event without the 'new' keyword" ); ok( event != window, "Instantiate jQuery.Event without the 'new' keyword" );
@ -1021,21 +875,21 @@ test("trigger(eventObject, [data], [fn])", function() {
equals( event.isPropagationStopped(), true, "Verify isPropagationStopped" ); equals( event.isPropagationStopped(), true, "Verify isPropagationStopped" );
equals( event.isImmediatePropagationStopped(), true, "Verify isPropagationStopped" ); equals( event.isImmediatePropagationStopped(), true, "Verify isPropagationStopped" );
$parent.bind("foo",function(e){ $parent.bind('foo',function(e){
// Tries bubbling // Tries bubbling
equals( e.type, "foo", "Verify event type when passed passing an event object" ); equals( e.type, 'foo', 'Verify event type when passed passing an event object' );
equals( e.target.id, "child", "Verify event.target when passed passing an event object" ); equals( e.target.id, 'child', 'Verify event.target when passed passing an event object' );
equals( e.currentTarget.id, "par", "Verify event.target when passed passing an event object" ); equals( e.currentTarget.id, 'par', 'Verify event.target when passed passing an event object' );
equals( e.secret, "boo!", "Verify event object's custom attribute when passed passing an event object" ); equals( e.secret, 'boo!', 'Verify event object\'s custom attribute when passed passing an event object' );
}); });
// test with an event object // test with an event object
event = new jQuery.Event("foo"); event = new jQuery.Event("foo");
event.secret = "boo!"; event.secret = 'boo!';
$child.trigger(event); $child.trigger(event);
// test with a literal object // test with a literal object
$child.trigger({type: "foo", secret: "boo!"}); $child.trigger({type:'foo', secret:'boo!'});
$parent.unbind(); $parent.unbind();
@ -1043,9 +897,9 @@ test("trigger(eventObject, [data], [fn])", function() {
ok( false, "This assertion shouldn't be reached"); ok( false, "This assertion shouldn't be reached");
} }
$parent.bind("foo", error ); $parent.bind('foo', error );
$child.bind("foo",function(e, a, b, c ){ $child.bind('foo',function(e, a, b, c ){
equals( arguments.length, 4, "Check arguments length"); equals( arguments.length, 4, "Check arguments length");
equals( a, 1, "Check first custom argument"); equals( a, 1, "Check first custom argument");
equals( b, 2, "Check second custom argument"); equals( b, 2, "Check second custom argument");
@ -1063,50 +917,29 @@ test("trigger(eventObject, [data], [fn])", function() {
// We should add this back in when we want to test the order // We should add this back in when we want to test the order
// in which event handlers are iterated. // in which event handlers are iterated.
//$child.bind("foo", error ); //$child.bind('foo', error );
event = new jQuery.Event("foo"); event = new jQuery.Event("foo");
$child.trigger( event, [1,2,3] ).unbind(); $child.trigger( event, [1,2,3] ).unbind();
equals( event.result, "result", "Check event.result attribute"); equals( event.result, "result", "Check event.result attribute");
// Will error if it bubbles // Will error if it bubbles
$child.triggerHandler("foo"); $child.triggerHandler('foo');
$child.unbind(); $child.unbind();
$parent.unbind().remove(); $parent.unbind().remove();
}); });
test("jQuery.Event( type, props )", function() {
expect(4);
var event = jQuery.Event( "keydown", { keyCode: 64 }),
handler = function( event ) {
ok( "keyCode" in event, "Special property 'keyCode' exists" );
equal( event.keyCode, 64, "event.keyCode has explicit value '64'" );
};
// Supports jQuery.Event implementation
equal( event.type, "keydown", "Verify type" );
ok( "keyCode" in event, "Special 'keyCode' property exists" );
jQuery("body").bind( "keydown", handler ).trigger( event );
jQuery("body").unbind( "keydown" );
});
test("jQuery.Event.currentTarget", function(){ test("jQuery.Event.currentTarget", function(){
expect(1); expect(1);
var counter = 0, var counter = 0,
$elem = jQuery("<button>a</button>").click(function(e){ $elem = jQuery('<button>a</button>').click(function(e){
equals( e.currentTarget, this, "Check currentTarget on "+(counter++?"native":"fake") +" event" ); equals( e.currentTarget, this, "Check currentTarget on "+(counter++?"native":"fake") +" event" );
}); });
// Fake event // Fake event
$elem.trigger("click"); $elem.trigger('click');
// Cleanup // Cleanup
$elem.unbind(); $elem.unbind();
@ -1119,7 +952,7 @@ test("toggle(Function, Function, ...)", function() {
fn1 = function(e) { count++; }, fn1 = function(e) { count++; },
fn2 = function(e) { count--; }, fn2 = function(e) { count--; },
preventDefault = function(e) { e.preventDefault() }, preventDefault = function(e) { e.preventDefault() },
link = jQuery("#mark"); link = jQuery('#mark');
link.click(preventDefault).click().toggle(fn1, fn2).click().click().click().click().click(); link.click(preventDefault).click().toggle(fn1, fn2).click().click().click().click().click();
equals( count, 1, "Check for toggle(fn, fn)" ); equals( count, 1, "Check for toggle(fn, fn)" );
@ -1163,8 +996,8 @@ test("toggle(Function, Function, ...)", function() {
$div.click(); $div.click();
equals( turn, 2, "Trying toggle with 3 functions, attempt 5 yields 2"); equals( turn, 2, "Trying toggle with 3 functions, attempt 5 yields 2");
$div.unbind("click",fns[0]); $div.unbind('click',fns[0]);
var data = jQuery._data( $div[0], "events" ); var data = jQuery._data( $div[0], 'events' );
ok( !data, "Unbinding one function from toggle unbinds them all"); ok( !data, "Unbinding one function from toggle unbinds them all");
// manually clean up detached elements // manually clean up detached elements
@ -1279,12 +1112,12 @@ test(".live()/.die()", function() {
jQuery("div").die("submit"); jQuery("div").die("submit");
// Test binding with a different context // Test binding with a different context
var clicked = 0, container = jQuery("#qunit-fixture")[0]; var clicked = 0, container = jQuery('#main')[0];
jQuery("#foo", container).live("click", function(e){ clicked++; }); jQuery("#foo", container).live("click", function(e){ clicked++; });
jQuery("div").trigger("click"); jQuery("div").trigger('click');
jQuery("#foo").trigger("click"); jQuery("#foo").trigger('click');
jQuery("#qunit-fixture").trigger("click"); jQuery("#main").trigger('click');
jQuery("body").trigger("click"); jQuery("body").trigger('click');
equals( clicked, 2, "live with a context" ); equals( clicked, 2, "live with a context" );
// Make sure the event is actually stored on the context // Make sure the event is actually stored on the context
@ -1292,7 +1125,7 @@ test(".live()/.die()", function() {
// Test unbinding with a different context // Test unbinding with a different context
jQuery("#foo", container).die("click"); jQuery("#foo", container).die("click");
jQuery("#foo").trigger("click"); jQuery("#foo").trigger('click');
equals( clicked, 2, "die with a context"); equals( clicked, 2, "die with a context");
// Test binding with event data // Test binding with event data
@ -1374,9 +1207,9 @@ test(".live()/.die()", function() {
// Make sure we don't loose the target by DOM modifications // Make sure we don't loose the target by DOM modifications
// after the bubble already reached the liveHandler // after the bubble already reached the liveHandler
var livec = 0, elemDiv = jQuery("#nothiddendivchild").html("<span></span>").get(0); var livec = 0, elemDiv = jQuery("#nothiddendivchild").html('<span></span>').get(0);
jQuery("#nothiddendivchild").live("click", function(e){ jQuery("#nothiddendivchild").html(""); }); jQuery("#nothiddendivchild").live("click", function(e){ jQuery("#nothiddendivchild").html(''); });
jQuery("#nothiddendivchild").live("click", function(e){ if(e.target) {livec++;} }); jQuery("#nothiddendivchild").live("click", function(e){ if(e.target) {livec++;} });
jQuery("#nothiddendiv span").click(); jQuery("#nothiddendiv span").click();
@ -1391,20 +1224,20 @@ test(".live()/.die()", function() {
var lived = 0, livee = 0; var lived = 0, livee = 0;
// bind one pair in one order // bind one pair in one order
jQuery("span#liveSpan1 a").live("click", function(){ lived++; return false; }); jQuery('span#liveSpan1 a').live('click', function(){ lived++; return false; });
jQuery("span#liveSpan1").live("click", function(){ livee++; }); jQuery('span#liveSpan1').live('click', function(){ livee++; });
jQuery("span#liveSpan1 a").click(); jQuery('span#liveSpan1 a').click();
equals( lived, 1, "Verify that only one first handler occurred." ); equals( lived, 1, "Verify that only one first handler occurred." );
equals( livee, 0, "Verify that second handler doesn't." ); equals( livee, 0, "Verify that second handler doesn't." );
// and one pair in inverse // and one pair in inverse
jQuery("span#liveSpan2").live("click", function(){ livee++; }); jQuery('span#liveSpan2').live('click', function(){ livee++; });
jQuery("span#liveSpan2 a").live("click", function(){ lived++; return false; }); jQuery('span#liveSpan2 a').live('click', function(){ lived++; return false; });
lived = 0; lived = 0;
livee = 0; livee = 0;
jQuery("span#liveSpan2 a").click(); jQuery('span#liveSpan2 a').click();
equals( lived, 1, "Verify that only one first handler occurred." ); equals( lived, 1, "Verify that only one first handler occurred." );
equals( livee, 0, "Verify that second handler doesn't." ); equals( livee, 0, "Verify that second handler doesn't." );
@ -1415,15 +1248,15 @@ test(".live()/.die()", function() {
jQuery("span#liveSpan2").die("click"); jQuery("span#liveSpan2").die("click");
// Test this, target and currentTarget are correct // Test this, target and currentTarget are correct
jQuery("span#liveSpan1").live("click", function(e){ jQuery('span#liveSpan1').live('click', function(e){
equals( this.id, "liveSpan1", "Check the this within a live handler" ); equals( this.id, 'liveSpan1', 'Check the this within a live handler' );
equals( e.currentTarget.id, "liveSpan1", "Check the event.currentTarget within a live handler" ); equals( e.currentTarget.id, 'liveSpan1', 'Check the event.currentTarget within a live handler' );
equals( e.target.nodeName.toUpperCase(), "A", "Check the event.target within a live handler" ); equals( e.target.nodeName.toUpperCase(), 'A', 'Check the event.target within a live handler' );
}); });
jQuery("span#liveSpan1 a").click(); jQuery('span#liveSpan1 a').click();
jQuery("span#liveSpan1").die("click"); jQuery('span#liveSpan1').die('click');
// Work with deep selectors // Work with deep selectors
livee = 0; livee = 0;
@ -1806,20 +1639,20 @@ test(".delegate()/.undelegate()", function() {
jQuery("#body").undelegate("div", "submit"); jQuery("#body").undelegate("div", "submit");
// Test binding with a different context // Test binding with a different context
var clicked = 0, container = jQuery("#qunit-fixture")[0]; var clicked = 0, container = jQuery('#main')[0];
jQuery("#qunit-fixture").delegate("#foo", "click", function(e){ clicked++; }); jQuery("#main").delegate("#foo", "click", function(e){ clicked++; });
jQuery("div").trigger("click"); jQuery("div").trigger('click');
jQuery("#foo").trigger("click"); jQuery("#foo").trigger('click');
jQuery("#qunit-fixture").trigger("click"); jQuery("#main").trigger('click');
jQuery("body").trigger("click"); jQuery("body").trigger('click');
equals( clicked, 2, "delegate with a context" ); equals( clicked, 2, "delegate with a context" );
// Make sure the event is actually stored on the context // Make sure the event is actually stored on the context
ok( jQuery._data(container, "events").live, "delegate with a context" ); ok( jQuery._data(container, "events").live, "delegate with a context" );
// Test unbinding with a different context // Test unbinding with a different context
jQuery("#qunit-fixture").undelegate("#foo", "click"); jQuery("#main").undelegate("#foo", "click");
jQuery("#foo").trigger("click"); jQuery("#foo").trigger('click');
equals( clicked, 2, "undelegate with a context"); equals( clicked, 2, "undelegate with a context");
// Test binding with event data // Test binding with event data
@ -1905,9 +1738,9 @@ test(".delegate()/.undelegate()", function() {
// Make sure we don't loose the target by DOM modifications // Make sure we don't loose the target by DOM modifications
// after the bubble already reached the liveHandler // after the bubble already reached the liveHandler
var livec = 0, elemDiv = jQuery("#nothiddendivchild").html("<span></span>").get(0); var livec = 0, elemDiv = jQuery("#nothiddendivchild").html('<span></span>').get(0);
jQuery("#body").delegate("#nothiddendivchild", "click", function(e){ jQuery("#nothiddendivchild").html(""); }); jQuery("#body").delegate("#nothiddendivchild", "click", function(e){ jQuery("#nothiddendivchild").html(''); });
jQuery("#body").delegate("#nothiddendivchild", "click", function(e){ if(e.target) {livec++;} }); jQuery("#body").delegate("#nothiddendivchild", "click", function(e){ if(e.target) {livec++;} });
jQuery("#nothiddendiv span").click(); jQuery("#nothiddendiv span").click();
@ -1922,20 +1755,20 @@ test(".delegate()/.undelegate()", function() {
var lived = 0, livee = 0; var lived = 0, livee = 0;
// bind one pair in one order // bind one pair in one order
jQuery("#body").delegate("span#liveSpan1 a", "click", function(){ lived++; return false; }); jQuery("#body").delegate('span#liveSpan1 a', 'click', function(){ lived++; return false; });
jQuery("#body").delegate("span#liveSpan1", "click", function(){ livee++; }); jQuery("#body").delegate('span#liveSpan1', 'click', function(){ livee++; });
jQuery("span#liveSpan1 a").click(); jQuery('span#liveSpan1 a').click();
equals( lived, 1, "Verify that only one first handler occurred." ); equals( lived, 1, "Verify that only one first handler occurred." );
equals( livee, 0, "Verify that second handler doesn't." ); equals( livee, 0, "Verify that second handler doesn't." );
// and one pair in inverse // and one pair in inverse
jQuery("#body").delegate("span#liveSpan2", "click", function(){ livee++; }); jQuery("#body").delegate('span#liveSpan2', 'click', function(){ livee++; });
jQuery("#body").delegate("span#liveSpan2 a", "click", function(){ lived++; return false; }); jQuery("#body").delegate('span#liveSpan2 a', 'click', function(){ lived++; return false; });
lived = 0; lived = 0;
livee = 0; livee = 0;
jQuery("span#liveSpan2 a").click(); jQuery('span#liveSpan2 a').click();
equals( lived, 1, "Verify that only one first handler occurred." ); equals( lived, 1, "Verify that only one first handler occurred." );
equals( livee, 0, "Verify that second handler doesn't." ); equals( livee, 0, "Verify that second handler doesn't." );
@ -1943,15 +1776,15 @@ test(".delegate()/.undelegate()", function() {
jQuery("#body").undelegate("click"); jQuery("#body").undelegate("click");
// Test this, target and currentTarget are correct // Test this, target and currentTarget are correct
jQuery("#body").delegate("span#liveSpan1", "click", function(e){ jQuery("#body").delegate('span#liveSpan1', 'click', function(e){
equals( this.id, "liveSpan1", "Check the this within a delegate handler" ); equals( this.id, 'liveSpan1', 'Check the this within a delegate handler' );
equals( e.currentTarget.id, "liveSpan1", "Check the event.currentTarget within a delegate handler" ); equals( e.currentTarget.id, 'liveSpan1', 'Check the event.currentTarget within a delegate handler' );
equals( e.target.nodeName.toUpperCase(), "A", "Check the event.target within a delegate handler" ); equals( e.target.nodeName.toUpperCase(), 'A', 'Check the event.target within a delegate handler' );
}); });
jQuery("span#liveSpan1 a").click(); jQuery('span#liveSpan1 a').click();
jQuery("#body").undelegate("span#liveSpan1", "click"); jQuery("#body").undelegate('span#liveSpan1', 'click');
// Work with deep selectors // Work with deep selectors
livee = 0; livee = 0;
@ -2123,37 +1956,16 @@ test("delegate with submit", function() {
jQuery(document).undelegate(); jQuery(document).undelegate();
}); });
test("undelegate() with only namespaces", function() {
expect(2);
var $delegate = jQuery("#liveHandlerOrder"),
count = 0;
$delegate.delegate("a", "click.ns", function(e) {
count++;
});
jQuery("a", $delegate).eq(0).trigger("click.ns");
equals( count, 1, "delegated click.ns");
$delegate.undelegate(".ns");
jQuery("a", $delegate).eq(1).trigger("click.ns");
equals( count, 1, "no more .ns after undelegate");
});
test("Non DOM element events", function() { test("Non DOM element events", function() {
expect(1); expect(1);
var o = {}; var o = {};
jQuery(o).bind("nonelementobj", function(e) { jQuery(o).bind('nonelementobj', function(e) {
ok( true, "Event on non-DOM object triggered" ); ok( true, "Event on non-DOM object triggered" );
}); });
jQuery(o).trigger("nonelementobj"); jQuery(o).trigger('nonelementobj');
}); });
test("window resize", function() { test("window resize", function() {
@ -2171,7 +1983,7 @@ test("window resize", function() {
test("focusin bubbles", function() { test("focusin bubbles", function() {
expect(5); expect(5);
var input = jQuery( "<input type='text' />" ).prependTo( "body" ), var input = jQuery( '<input type="text" />' ).prependTo( "body" ),
order = 0; order = 0;
jQuery( "body" ).bind( "focusin.focusinBubblesTest", function(){ jQuery( "body" ).bind( "focusin.focusinBubblesTest", function(){
@ -2198,94 +2010,15 @@ test("focusin bubbles", function() {
jQuery( "body" ).unbind( "focusin.focusinBubblesTest" ); jQuery( "body" ).unbind( "focusin.focusinBubblesTest" );
}); });
test("custom events with colons (#3533, #8272)", function() { /*
expect(1); test("jQuery(function($) {})", function() {
stop();
var tab = jQuery("<table><tr><td>trigger</td></tr></table>").appendTo("body"); jQuery(function($) {
try { equals(jQuery, $, "ready doesn't provide an event object, instead it provides a reference to the jQuery function, see http://docs.jquery.com/Events/ready#fn");
tab.trigger("back:forth"); start();
ok( true, "colon events don't throw" ); });
} catch ( e ) {
ok( false, "colon events die" );
};
tab.remove();
}); });
(function(){
// This code must be run before DOM ready!
var notYetReady, noEarlyExecution,
order = [],
args = {};
notYetReady = !jQuery.isReady;
test("jQuery.isReady", function() {
expect(2);
equals(notYetReady, true, "jQuery.isReady should not be true before DOM ready");
equals(jQuery.isReady, true, "jQuery.isReady should be true once DOM is ready");
});
// Create an event handler.
function makeHandler( testId ) {
// When returned function is executed, push testId onto `order` array
// to ensure execution order. Also, store event handler arg to ensure
// the correct arg is being passed into the event handler.
return function( arg ) {
order.push(testId);
args[testId] = arg;
};
}
// Bind to the ready event in every possible way.
jQuery(makeHandler("a"));
jQuery(document).ready(makeHandler("b"));
jQuery(document).bind("ready.readytest", makeHandler("c"));
// Do it twice, just to be sure.
jQuery(makeHandler("d"));
jQuery(document).ready(makeHandler("e"));
jQuery(document).bind("ready.readytest", makeHandler("f"));
noEarlyExecution = order.length == 0;
// This assumes that QUnit tests are run on DOM ready!
test("jQuery ready", function() {
expect(10);
ok(noEarlyExecution, "Handlers bound to DOM ready should not execute before DOM ready");
// Ensure execution order.
same(order, ["a", "b", "d", "e", "c", "f"], "Bound DOM ready handlers should execute in bind-order, but those bound with jQuery(document).bind( 'ready', fn ) will always execute last");
// Ensure handler argument is correct.
equals(args.a, jQuery, "Argument passed to fn in jQuery( fn ) should be jQuery");
equals(args.b, jQuery, "Argument passed to fn in jQuery(document).ready( fn ) should be jQuery");
ok(args.c instanceof jQuery.Event, "Argument passed to fn in jQuery(document).bind( 'ready', fn ) should be an event object");
order = [];
// Now that the ready event has fired, again bind to the ready event
// in every possible way. These event handlers should execute immediately.
jQuery(makeHandler("g"));
equals(order.pop(), "g", "Event handler should execute immediately");
equals(args.g, jQuery, "Argument passed to fn in jQuery( fn ) should be jQuery");
jQuery(document).ready(makeHandler("h"));
equals(order.pop(), "h", "Event handler should execute immediately");
equals(args.h, jQuery, "Argument passed to fn in jQuery(document).ready( fn ) should be jQuery");
jQuery(document).bind("ready.readytest", makeHandler("never"));
equals(order.length, 0, "Event handler should never execute since DOM ready has already passed");
// Cleanup.
jQuery(document).unbind("ready.readytest");
});
})();
/*
test("event properties", function() { test("event properties", function() {
stop(); stop();
jQuery("#simon1").click(function(event) { jQuery("#simon1").click(function(event) {
@ -2294,4 +2027,3 @@ test("event properties", function() {
}).click(); }).click();
}); });
*/ */

File diff suppressed because it is too large Load diff

View file

@ -20,7 +20,7 @@ testoffset("absolute"/* in iframe */, function($, iframe) {
// this insures that the results will be wrong // this insures that the results will be wrong
// if the offset method is using the scroll offset // if the offset method is using the scroll offset
// of the parent window // of the parent window
var forceScroll = jQuery("<div>", { width: 2000, height: 2000 }).appendTo("body"); var forceScroll = jQuery('<div>', { width: 2000, height: 2000 }).appendTo('body');
window.scrollTo(200, 200); window.scrollTo(200, 200);
if ( document.documentElement.scrollTop || document.body.scrollTop ) { if ( document.documentElement.scrollTop || document.body.scrollTop ) {
@ -31,7 +31,7 @@ testoffset("absolute"/* in iframe */, function($, iframe) {
// get offset // get offset
tests = [ tests = [
{ id: "#absolute-1", top: 1, left: 1 } { id: '#absolute-1', top: 1, left: 1 }
]; ];
jQuery.each( tests, function() { jQuery.each( tests, function() {
equals( jQuery( this.id, doc ).offset().top, this.top, "jQuery('" + this.id + "').offset().top" ); equals( jQuery( this.id, doc ).offset().top, this.top, "jQuery('" + this.id + "').offset().top" );
@ -41,7 +41,7 @@ testoffset("absolute"/* in iframe */, function($, iframe) {
// get position // get position
tests = [ tests = [
{ id: "#absolute-1", top: 0, left: 0 } { id: '#absolute-1', top: 0, left: 0 }
]; ];
jQuery.each( tests, function() { jQuery.each( tests, function() {
equals( jQuery( this.id, doc ).position().top, this.top, "jQuery('" + this.id + "').position().top" ); equals( jQuery( this.id, doc ).position().top, this.top, "jQuery('" + this.id + "').position().top" );
@ -56,10 +56,10 @@ testoffset("absolute", function( jQuery ) {
// get offset tests // get offset tests
var tests = [ var tests = [
{ id: "#absolute-1", top: 1, left: 1 }, { id: '#absolute-1', top: 1, left: 1 },
{ id: "#absolute-1-1", top: 5, left: 5 }, { id: '#absolute-1-1', top: 5, left: 5 },
{ id: "#absolute-1-1-1", top: 9, left: 9 }, { id: '#absolute-1-1-1', top: 9, left: 9 },
{ id: "#absolute-2", top: 20, left: 20 } { id: '#absolute-2', top: 20, left: 20 }
]; ];
jQuery.each( tests, function() { jQuery.each( tests, function() {
equals( jQuery( this.id ).offset().top, this.top, "jQuery('" + this.id + "').offset().top" ); equals( jQuery( this.id ).offset().top, this.top, "jQuery('" + this.id + "').offset().top" );
@ -69,10 +69,10 @@ testoffset("absolute", function( jQuery ) {
// get position // get position
tests = [ tests = [
{ id: "#absolute-1", top: 0, left: 0 }, { id: '#absolute-1', top: 0, left: 0 },
{ id: "#absolute-1-1", top: 1, left: 1 }, { id: '#absolute-1-1', top: 1, left: 1 },
{ id: "#absolute-1-1-1", top: 1, left: 1 }, { id: '#absolute-1-1-1', top: 1, left: 1 },
{ id: "#absolute-2", top: 19, left: 19 } { id: '#absolute-2', top: 19, left: 19 }
]; ];
jQuery.each( tests, function() { jQuery.each( tests, function() {
equals( jQuery( this.id ).position().top, this.top, "jQuery('" + this.id + "').position().top" ); equals( jQuery( this.id ).position().top, this.top, "jQuery('" + this.id + "').position().top" );
@ -80,29 +80,29 @@ testoffset("absolute", function( jQuery ) {
}); });
// test #5781 // test #5781
var offset = jQuery( "#positionTest" ).offset({ top: 10, left: 10 }).offset(); var offset = jQuery( '#positionTest' ).offset({ top: 10, left: 10 }).offset();
equals( offset.top, 10, "Setting offset on element with position absolute but 'auto' values." ) equals( offset.top, 10, "Setting offset on element with position absolute but 'auto' values." )
equals( offset.left, 10, "Setting offset on element with position absolute but 'auto' values." ) equals( offset.left, 10, "Setting offset on element with position absolute but 'auto' values." )
// set offset // set offset
tests = [ tests = [
{ id: "#absolute-2", top: 30, left: 30 }, { id: '#absolute-2', top: 30, left: 30 },
{ id: "#absolute-2", top: 10, left: 10 }, { id: '#absolute-2', top: 10, left: 10 },
{ id: "#absolute-2", top: -1, left: -1 }, { id: '#absolute-2', top: -1, left: -1 },
{ id: "#absolute-2", top: 19, left: 19 }, { id: '#absolute-2', top: 19, left: 19 },
{ id: "#absolute-1-1-1", top: 15, left: 15 }, { id: '#absolute-1-1-1', top: 15, left: 15 },
{ id: "#absolute-1-1-1", top: 5, left: 5 }, { id: '#absolute-1-1-1', top: 5, left: 5 },
{ id: "#absolute-1-1-1", top: -1, left: -1 }, { id: '#absolute-1-1-1', top: -1, left: -1 },
{ id: "#absolute-1-1-1", top: 9, left: 9 }, { id: '#absolute-1-1-1', top: 9, left: 9 },
{ id: "#absolute-1-1", top: 10, left: 10 }, { id: '#absolute-1-1', top: 10, left: 10 },
{ id: "#absolute-1-1", top: 0, left: 0 }, { id: '#absolute-1-1', top: 0, left: 0 },
{ id: "#absolute-1-1", top: -1, left: -1 }, { id: '#absolute-1-1', top: -1, left: -1 },
{ id: "#absolute-1-1", top: 5, left: 5 }, { id: '#absolute-1-1', top: 5, left: 5 },
{ id: "#absolute-1", top: 2, left: 2 }, { id: '#absolute-1', top: 2, left: 2 },
{ id: "#absolute-1", top: 0, left: 0 }, { id: '#absolute-1', top: 0, left: 0 },
{ id: "#absolute-1", top: -1, left: -1 }, { id: '#absolute-1', top: -1, left: -1 },
{ id: "#absolute-1", top: 1, left: 1 } { id: '#absolute-1', top: 1, left: 1 }
]; ];
jQuery.each( tests, function() { jQuery.each( tests, function() {
jQuery( this.id ).offset({ top: this.top, left: this.left }); jQuery( this.id ).offset({ top: this.top, left: this.left });
@ -144,9 +144,9 @@ testoffset("relative", function( jQuery ) {
// get offset // get offset
var tests = [ var tests = [
{ id: "#relative-1", top: ie ? 6 : 7, left: 7 }, { id: '#relative-1', top: ie ? 6 : 7, left: 7 },
{ id: "#relative-1-1", top: ie ? 13 : 15, left: 15 }, { id: '#relative-1-1', top: ie ? 13 : 15, left: 15 },
{ id: "#relative-2", top: ie ? 141 : 142, left: 27 } { id: '#relative-2', top: ie ? 141 : 142, left: 27 }
]; ];
jQuery.each( tests, function() { jQuery.each( tests, function() {
equals( jQuery( this.id ).offset().top, this.top, "jQuery('" + this.id + "').offset().top" ); equals( jQuery( this.id ).offset().top, this.top, "jQuery('" + this.id + "').offset().top" );
@ -156,9 +156,9 @@ testoffset("relative", function( jQuery ) {
// get position // get position
tests = [ tests = [
{ id: "#relative-1", top: ie ? 5 : 6, left: 6 }, { id: '#relative-1', top: ie ? 5 : 6, left: 6 },
{ id: "#relative-1-1", top: ie ? 4 : 5, left: 5 }, { id: '#relative-1-1', top: ie ? 4 : 5, left: 5 },
{ id: "#relative-2", top: ie ? 140 : 141, left: 26 } { id: '#relative-2', top: ie ? 140 : 141, left: 26 }
]; ];
jQuery.each( tests, function() { jQuery.each( tests, function() {
equals( jQuery( this.id ).position().top, this.top, "jQuery('" + this.id + "').position().top" ); equals( jQuery( this.id ).position().top, this.top, "jQuery('" + this.id + "').position().top" );
@ -168,18 +168,18 @@ testoffset("relative", function( jQuery ) {
// set offset // set offset
tests = [ tests = [
{ id: "#relative-2", top: 200, left: 50 }, { id: '#relative-2', top: 200, left: 50 },
{ id: "#relative-2", top: 100, left: 10 }, { id: '#relative-2', top: 100, left: 10 },
{ id: "#relative-2", top: -5, left: -5 }, { id: '#relative-2', top: -5, left: -5 },
{ id: "#relative-2", top: 142, left: 27 }, { id: '#relative-2', top: 142, left: 27 },
{ id: "#relative-1-1", top: 100, left: 100 }, { id: '#relative-1-1', top: 100, left: 100 },
{ id: "#relative-1-1", top: 5, left: 5 }, { id: '#relative-1-1', top: 5, left: 5 },
{ id: "#relative-1-1", top: -1, left: -1 }, { id: '#relative-1-1', top: -1, left: -1 },
{ id: "#relative-1-1", top: 15, left: 15 }, { id: '#relative-1-1', top: 15, left: 15 },
{ id: "#relative-1", top: 100, left: 100 }, { id: '#relative-1', top: 100, left: 100 },
{ id: "#relative-1", top: 0, left: 0 }, { id: '#relative-1', top: 0, left: 0 },
{ id: "#relative-1", top: -1, left: -1 }, { id: '#relative-1', top: -1, left: -1 },
{ id: "#relative-1", top: 7, left: 7 } { id: '#relative-1', top: 7, left: 7 }
]; ];
jQuery.each( tests, function() { jQuery.each( tests, function() {
jQuery( this.id ).offset({ top: this.top, left: this.left }); jQuery( this.id ).offset({ top: this.top, left: this.left });
@ -205,10 +205,10 @@ testoffset("static", function( jQuery ) {
// get offset // get offset
var tests = [ var tests = [
{ id: "#static-1", top: ie ? 6 : 7, left: 7 }, { id: '#static-1', top: ie ? 6 : 7, left: 7 },
{ id: "#static-1-1", top: ie ? 13 : 15, left: 15 }, { id: '#static-1-1', top: ie ? 13 : 15, left: 15 },
{ id: "#static-1-1-1", top: ie ? 20 : 23, left: 23 }, { id: '#static-1-1-1', top: ie ? 20 : 23, left: 23 },
{ id: "#static-2", top: ie ? 121 : 122, left: 7 } { id: '#static-2', top: ie ? 121 : 122, left: 7 }
]; ];
jQuery.each( tests, function() { jQuery.each( tests, function() {
equals( jQuery( this.id ).offset().top, this.top, "jQuery('" + this.id + "').offset().top" ); equals( jQuery( this.id ).offset().top, this.top, "jQuery('" + this.id + "').offset().top" );
@ -218,10 +218,10 @@ testoffset("static", function( jQuery ) {
// get position // get position
tests = [ tests = [
{ id: "#static-1", top: ie ? 5 : 6, left: 6 }, { id: '#static-1', top: ie ? 5 : 6, left: 6 },
{ id: "#static-1-1", top: ie ? 12 : 14, left: 14 }, { id: '#static-1-1', top: ie ? 12 : 14, left: 14 },
{ id: "#static-1-1-1", top: ie ? 19 : 22, left: 22 }, { id: '#static-1-1-1', top: ie ? 19 : 22, left: 22 },
{ id: "#static-2", top: ie ? 120 : 121, left: 6 } { id: '#static-2', top: ie ? 120 : 121, left: 6 }
]; ];
jQuery.each( tests, function() { jQuery.each( tests, function() {
equals( jQuery( this.id ).position().top, this.top, "jQuery('" + this.top + "').position().top" ); equals( jQuery( this.id ).position().top, this.top, "jQuery('" + this.top + "').position().top" );
@ -231,22 +231,22 @@ testoffset("static", function( jQuery ) {
// set offset // set offset
tests = [ tests = [
{ id: "#static-2", top: 200, left: 200 }, { id: '#static-2', top: 200, left: 200 },
{ id: "#static-2", top: 100, left: 100 }, { id: '#static-2', top: 100, left: 100 },
{ id: "#static-2", top: -2, left: -2 }, { id: '#static-2', top: -2, left: -2 },
{ id: "#static-2", top: 121, left: 6 }, { id: '#static-2', top: 121, left: 6 },
{ id: "#static-1-1-1", top: 50, left: 50 }, { id: '#static-1-1-1', top: 50, left: 50 },
{ id: "#static-1-1-1", top: 10, left: 10 }, { id: '#static-1-1-1', top: 10, left: 10 },
{ id: "#static-1-1-1", top: -1, left: -1 }, { id: '#static-1-1-1', top: -1, left: -1 },
{ id: "#static-1-1-1", top: 22, left: 22 }, { id: '#static-1-1-1', top: 22, left: 22 },
{ id: "#static-1-1", top: 25, left: 25 }, { id: '#static-1-1', top: 25, left: 25 },
{ id: "#static-1-1", top: 10, left: 10 }, { id: '#static-1-1', top: 10, left: 10 },
{ id: "#static-1-1", top: -3, left: -3 }, { id: '#static-1-1', top: -3, left: -3 },
{ id: "#static-1-1", top: 14, left: 14 }, { id: '#static-1-1', top: 14, left: 14 },
{ id: "#static-1", top: 30, left: 30 }, { id: '#static-1', top: 30, left: 30 },
{ id: "#static-1", top: 2, left: 2 }, { id: '#static-1', top: 2, left: 2 },
{ id: "#static-1", top: -2, left: -2 }, { id: '#static-1', top: -2, left: -2 },
{ id: "#static-1", top: 7, left: 7 } { id: '#static-1', top: 7, left: 7 }
]; ];
jQuery.each( tests, function() { jQuery.each( tests, function() {
jQuery( this.id ).offset({ top: this.top, left: this.left }); jQuery( this.id ).offset({ top: this.top, left: this.left });
@ -270,8 +270,8 @@ testoffset("fixed", function( jQuery ) {
jQuery.offset.initialize(); jQuery.offset.initialize();
var tests = [ var tests = [
{ id: "#fixed-1", top: 1001, left: 1001 }, { id: '#fixed-1', top: 1001, left: 1001 },
{ id: "#fixed-2", top: 1021, left: 1021 } { id: '#fixed-2', top: 1021, left: 1021 }
]; ];
jQuery.each( tests, function() { jQuery.each( tests, function() {
@ -284,18 +284,18 @@ testoffset("fixed", function( jQuery ) {
equals( jQuery( this.id ).offset().left, this.left, "jQuery('" + this.id + "').offset().left" ); equals( jQuery( this.id ).offset().left, this.left, "jQuery('" + this.id + "').offset().left" );
} else { } else {
// need to have same number of assertions // need to have same number of assertions
ok( true, "Fixed position is not supported" ); ok( true, 'Fixed position is not supported' );
ok( true, "Fixed position is not supported" ); ok( true, 'Fixed position is not supported' );
} }
}); });
tests = [ tests = [
{ id: "#fixed-1", top: 100, left: 100 }, { id: '#fixed-1', top: 100, left: 100 },
{ id: "#fixed-1", top: 0, left: 0 }, { id: '#fixed-1', top: 0, left: 0 },
{ id: "#fixed-1", top: -4, left: -4 }, { id: '#fixed-1', top: -4, left: -4 },
{ id: "#fixed-2", top: 200, left: 200 }, { id: '#fixed-2', top: 200, left: 200 },
{ id: "#fixed-2", top: 0, left: 0 }, { id: '#fixed-2', top: 0, left: 0 },
{ id: "#fixed-2", top: -5, left: -5 } { id: '#fixed-2', top: -5, left: -5 }
]; ];
jQuery.each( tests, function() { jQuery.each( tests, function() {
@ -314,58 +314,58 @@ testoffset("fixed", function( jQuery ) {
equals( jQuery( this.id ).offset().left, this.left + 1, "jQuery('" + this.id + "').offset({ left: " + (this.left + 1) + ", using: fn })" ); equals( jQuery( this.id ).offset().left, this.left + 1, "jQuery('" + this.id + "').offset({ left: " + (this.left + 1) + ", using: fn })" );
} else { } else {
// need to have same number of assertions // need to have same number of assertions
ok( true, "Fixed position is not supported" ); ok( true, 'Fixed position is not supported' );
ok( true, "Fixed position is not supported" ); ok( true, 'Fixed position is not supported' );
ok( true, "Fixed position is not supported" ); ok( true, 'Fixed position is not supported' );
ok( true, "Fixed position is not supported" ); ok( true, 'Fixed position is not supported' );
} }
}); });
// Bug 8316 // Bug 8316
var $noTopLeft = jQuery("#fixed-no-top-left"); var $noTopLeft = jQuery('#fixed-no-top-left');
if ( jQuery.offset.supportsFixedPosition ) { if ( jQuery.offset.supportsFixedPosition ) {
equals( $noTopLeft.offset().top, 1007, "Check offset top for fixed element with no top set" ); equals( $noTopLeft.offset().top, 1007, "Check offset top for fixed element with no top set" );
equals( $noTopLeft.offset().left, 1007, "Check offset left for fixed element with no left set" ); equals( $noTopLeft.offset().left, 1007, "Check offset left for fixed element with no left set" );
} else { } else {
// need to have same number of assertions // need to have same number of assertions
ok( true, "Fixed position is not supported" ); ok( true, 'Fixed position is not supported' );
ok( true, "Fixed position is not supported" ); ok( true, 'Fixed position is not supported' );
} }
}); });
testoffset("table", function( jQuery ) { testoffset("table", function( jQuery ) {
expect(4); expect(4);
equals( jQuery("#table-1").offset().top, 6, "jQuery('#table-1').offset().top" ); equals( jQuery('#table-1').offset().top, 6, "jQuery('#table-1').offset().top" );
equals( jQuery("#table-1").offset().left, 6, "jQuery('#table-1').offset().left" ); equals( jQuery('#table-1').offset().left, 6, "jQuery('#table-1').offset().left" );
equals( jQuery("#th-1").offset().top, 10, "jQuery('#th-1').offset().top" ); equals( jQuery('#th-1').offset().top, 10, "jQuery('#th-1').offset().top" );
equals( jQuery("#th-1").offset().left, 10, "jQuery('#th-1').offset().left" ); equals( jQuery('#th-1').offset().left, 10, "jQuery('#th-1').offset().left" );
}); });
testoffset("scroll", function( jQuery, win ) { testoffset("scroll", function( jQuery, win ) {
expect(22); expect(16);
var ie = jQuery.browser.msie && parseInt( jQuery.browser.version, 10 ) < 8; var ie = jQuery.browser.msie && parseInt( jQuery.browser.version, 10 ) < 8;
// IE is collapsing the top margin of 1px // IE is collapsing the top margin of 1px
equals( jQuery("#scroll-1").offset().top, ie ? 6 : 7, "jQuery('#scroll-1').offset().top" ); equals( jQuery('#scroll-1').offset().top, ie ? 6 : 7, "jQuery('#scroll-1').offset().top" );
equals( jQuery("#scroll-1").offset().left, 7, "jQuery('#scroll-1').offset().left" ); equals( jQuery('#scroll-1').offset().left, 7, "jQuery('#scroll-1').offset().left" );
// IE is collapsing the top margin of 1px // IE is collapsing the top margin of 1px
equals( jQuery("#scroll-1-1").offset().top, ie ? 9 : 11, "jQuery('#scroll-1-1').offset().top" ); equals( jQuery('#scroll-1-1').offset().top, ie ? 9 : 11, "jQuery('#scroll-1-1').offset().top" );
equals( jQuery("#scroll-1-1").offset().left, 11, "jQuery('#scroll-1-1').offset().left" ); equals( jQuery('#scroll-1-1').offset().left, 11, "jQuery('#scroll-1-1').offset().left" );
// scroll offset tests .scrollTop/Left // scroll offset tests .scrollTop/Left
equals( jQuery("#scroll-1").scrollTop(), 5, "jQuery('#scroll-1').scrollTop()" ); equals( jQuery('#scroll-1').scrollTop(), 5, "jQuery('#scroll-1').scrollTop()" );
equals( jQuery("#scroll-1").scrollLeft(), 5, "jQuery('#scroll-1').scrollLeft()" ); equals( jQuery('#scroll-1').scrollLeft(), 5, "jQuery('#scroll-1').scrollLeft()" );
equals( jQuery("#scroll-1-1").scrollTop(), 0, "jQuery('#scroll-1-1').scrollTop()" ); equals( jQuery('#scroll-1-1').scrollTop(), 0, "jQuery('#scroll-1-1').scrollTop()" );
equals( jQuery("#scroll-1-1").scrollLeft(), 0, "jQuery('#scroll-1-1').scrollLeft()" ); equals( jQuery('#scroll-1-1').scrollLeft(), 0, "jQuery('#scroll-1-1').scrollLeft()" );
// equals( jQuery("body").scrollTop(), 0, "jQuery("body").scrollTop()" ); // equals( jQuery('body').scrollTop(), 0, "jQuery('body').scrollTop()" );
// equals( jQuery("body").scrollLeft(), 0, "jQuery("body").scrollTop()" ); // equals( jQuery('body').scrollLeft(), 0, "jQuery('body').scrollTop()" );
win.name = "test"; win.name = "test";
@ -390,21 +390,13 @@ testoffset("scroll", function( jQuery, win ) {
equals( jQuery(window).scrollLeft(), 0, "jQuery(window).scrollLeft() other window" ); equals( jQuery(window).scrollLeft(), 0, "jQuery(window).scrollLeft() other window" );
equals( jQuery(document).scrollTop(), 0, "jQuery(window).scrollTop() other document" ); equals( jQuery(document).scrollTop(), 0, "jQuery(window).scrollTop() other document" );
equals( jQuery(document).scrollLeft(), 0, "jQuery(window).scrollLeft() other document" ); equals( jQuery(document).scrollLeft(), 0, "jQuery(window).scrollLeft() other document" );
// Tests scrollTop/Left with empty jquery objects
notEqual( jQuery().scrollTop(100), null, "jQuery().scrollTop(100) testing setter on empty jquery object" );
notEqual( jQuery().scrollLeft(100), null, "jQuery().scrollLeft(100) testing setter on empty jquery object" );
notEqual( jQuery().scrollTop(null), null, "jQuery().scrollTop(null) testing setter on empty jquery object" );
notEqual( jQuery().scrollLeft(null), null, "jQuery().scrollLeft(null) testing setter on empty jquery object" );
strictEqual( jQuery().scrollTop(), null, "jQuery().scrollTop(100) testing setter on empty jquery object" );
strictEqual( jQuery().scrollLeft(), null, "jQuery().scrollLeft(100) testing setter on empty jquery object" );
}); });
testoffset("body", function( jQuery ) { testoffset("body", function( jQuery ) {
expect(2); expect(2);
equals( jQuery("body").offset().top, 1, "jQuery('#body').offset().top" ); equals( jQuery('body').offset().top, 1, "jQuery('#body').offset().top" );
equals( jQuery("body").offset().left, 1, "jQuery('#body').offset().left" ); equals( jQuery('body').offset().left, 1, "jQuery('#body').offset().left" );
}); });
test("Chaining offset(coords) returns jQuery object", function() { test("Chaining offset(coords) returns jQuery object", function() {
@ -441,33 +433,7 @@ test("offsetParent", function(){
equals( div[1], jQuery("#nothiddendiv")[0], "The div is the offsetParent." ); equals( div[1], jQuery("#nothiddendiv")[0], "The div is the offsetParent." );
}); });
test("fractions (see #7730 and #7885)", function() { function testoffset( name, fn ) {
expect(2);
jQuery('body').append('<div id="fractions"/>');
var expected = { top: 1000, left: 1000 };
var div = jQuery('#fractions');
div.css({
position: 'absolute',
left: '1000.7432222px',
top: '1000.532325px',
width: 100,
height: 100
});
div.offset(expected);
var result = div.offset();
equals( result.top, expected.top, "Check top" );
equals( result.left, expected.left, "Check left" );
div.remove();
});
function testoffset(name, fn) {
test(name, function() { test(name, function() {
// pause execution for now // pause execution for now
@ -490,10 +456,10 @@ function testoffset(name, fn) {
}); });
function loadFixture() { function loadFixture() {
var src = "./data/offset/" + name + ".html?" + parseInt( Math.random()*1000, 10 ), var src = './data/offset/' + name + '.html?' + parseInt( Math.random()*1000, 10 ),
iframe = jQuery("<iframe />").css({ iframe = jQuery('<iframe />').css({
width: 500, height: 500, position: "absolute", top: -600, left: -600, visibility: "hidden" width: 500, height: 500, position: 'absolute', top: -600, left: -600, visibility: 'hidden'
}).appendTo("body")[0]; }).appendTo('body')[0];
iframe.contentWindow.location = src; iframe.contentWindow.location = src;
return iframe; return iframe;
} }

View file

@ -1,50 +1,38 @@
module("queue", { teardown: moduleTeardown }); module("queue", { teardown: moduleTeardown });
test("queue() with other types",function() { test("queue() with other types",function() {
expect(11); expect(9);
var counter = 0; var counter = 0;
stop(); var $div = jQuery({});
var $div = jQuery({}),
defer;
$div.promise("foo").done(function() {
equals( counter, 0, "Deferred for collection with no queue is automatically resolved" );
});
$div $div
.queue("foo",function(){ .queue('foo',function(){
equals( ++counter, 1, "Dequeuing" ); equals( ++counter, 1, "Dequeuing" );
jQuery.dequeue(this,"foo"); jQuery.dequeue(this,'foo');
}) })
.queue("foo",function(){ .queue('foo',function(){
equals( ++counter, 2, "Dequeuing" ); equals( ++counter, 2, "Dequeuing" );
jQuery(this).dequeue("foo"); jQuery(this).dequeue('foo');
}) })
.queue("foo",function(){ .queue('foo',function(){
equals( ++counter, 3, "Dequeuing" ); equals( ++counter, 3, "Dequeuing" );
}) })
.queue("foo",function(){ .queue('foo',function(){
equals( ++counter, 4, "Dequeuing" ); equals( ++counter, 4, "Dequeuing" );
}); });
defer = $div.promise("foo").done(function() { equals( $div.queue('foo').length, 4, "Testing queue length" );
equals( counter, 4, "Testing previous call to dequeue in deferred" );
start();
});
equals( $div.queue("foo").length, 4, "Testing queue length" ); $div.dequeue('foo');
$div.dequeue("foo");
equals( counter, 3, "Testing previous call to dequeue" ); equals( counter, 3, "Testing previous call to dequeue" );
equals( $div.queue("foo").length, 1, "Testing queue length" ); equals( $div.queue('foo').length, 1, "Testing queue length" );
$div.dequeue("foo"); $div.dequeue('foo');
equals( counter, 4, "Testing previous call to dequeue" ); equals( counter, 4, "Testing previous call to dequeue" );
equals( $div.queue("foo").length, 0, "Testing queue length" ); equals( $div.queue('foo').length, 0, "Testing queue length" );
}); });
test("queue(name) passes in the next item in the queue as a parameter", function() { test("queue(name) passes in the next item in the queue as a parameter", function() {
@ -86,7 +74,7 @@ test("queue(name) passes in the next item in the queue as a parameter", function
}); });
test("queue() passes in the next item in the queue as a parameter to fx queues", function() { test("queue() passes in the next item in the queue as a parameter to fx queues", function() {
expect(3); expect(2);
stop(); stop();
var div = jQuery({}); var div = jQuery({});
@ -99,39 +87,11 @@ test("queue() passes in the next item in the queue as a parameter to fx queues",
}).queue(function(next) { }).queue(function(next) {
equals(++counter, 2, "Next was called"); equals(++counter, 2, "Next was called");
next(); next();
start();
}).queue("bar", function() { }).queue("bar", function() {
equals(++counter, 3, "Other queues are not triggered by next()") equals(++counter, 3, "Other queues are not triggered by next()")
}); });
jQuery.when( div.promise("fx"), div ).done(function() {
equals(counter, 2, "Deferreds resolved");
start();
});
});
test("callbacks keep their place in the queue", function() {
expect(5);
stop();
var div = jQuery("<div>"),
counter = 0;
div.queue(function( next ) {
equal( ++counter, 1, "Queue/callback order: first called" );
setTimeout( next, 200 );
}).show(100, function() {
equal( ++counter, 2, "Queue/callback order: second called" );
jQuery(this).hide(100, function() {
equal( ++counter, 4, "Queue/callback order: fourth called" );
});
}).queue(function( next ) {
equal( ++counter, 3, "Queue/callback order: third called" );
next();
});
div.promise("fx").done(function() {
equals(counter, 4, "Deferreds resolved");
start();
});
}); });
test("delay()", function() { test("delay()", function() {
@ -150,9 +110,7 @@ test("delay()", function() {
}); });
test("clearQueue(name) clears the queue", function() { test("clearQueue(name) clears the queue", function() {
expect(2); expect(1);
stop()
var div = jQuery({}); var div = jQuery({});
var counter = 0; var counter = 0;
@ -165,11 +123,6 @@ test("clearQueue(name) clears the queue", function() {
counter++; counter++;
}); });
div.promise("foo").done(function() {
ok( true, "dequeue resolves the deferred" );
start();
});
div.dequeue("foo"); div.dequeue("foo");
equals(counter, 1, "the queue was cleared"); equals(counter, 1, "the queue was cleared");
@ -193,81 +146,3 @@ test("clearQueue() clears the fx queue", function() {
div.removeData(); div.removeData();
}); });
test("_mark() and _unmark()", function() {
expect(1);
var div = {},
$div = jQuery( div );
stop();
jQuery._mark( div, "foo" );
jQuery._mark( div, "foo" );
jQuery._unmark( div, "foo" );
jQuery._unmark( div, "foo" );
$div.promise( "foo" ).done(function() {
ok( true, "No more marks" );
start();
});
});
test("_mark() and _unmark() default to 'fx'", function() {
expect(1);
var div = {},
$div = jQuery( div );
stop();
jQuery._mark( div );
jQuery._mark( div );
jQuery._unmark( div, "fx" );
jQuery._unmark( div );
$div.promise().done(function() {
ok( true, "No more marks" );
start();
});
});
test("promise()", function() {
expect(1);
stop();
var objects = [];
jQuery.each( [{}, {}], function( i, div ) {
var $div = jQuery( div );
$div.queue(function( next ) {
setTimeout( function() {
if ( i ) {
next();
setTimeout( function() {
jQuery._unmark( div );
}, 20 );
} else {
jQuery._unmark( div );
setTimeout( function() {
next();
}, 20 );
}
}, 50 );
}).queue(function( next ) {
next();
});
jQuery._mark( div );
objects.push( $div );
});
jQuery.when.apply( jQuery, objects ).done(function() {
ok( true, "Deferred resolved" );
start();
});
jQuery.each( objects, function() {
this.dequeue();
});
});

View file

@ -1,55 +0,0 @@
module("support", { teardown: moduleTeardown });
function supportIFrameTest( title, url, noDisplay, func ) {
if ( noDisplay !== true ) {
func = noDisplay;
noDisplay = false;
}
test( title, function() {
var iframe;
stop();
window.supportCallback = function() {
var self = this,
args = arguments;
setTimeout( function() {
window.supportCallback = undefined;
iframe.remove();
func.apply( self, args );
start();
}, 0 );
};
iframe = jQuery( "<div/>" ).css( "display", noDisplay ? "none" : "block" ).append(
jQuery( "<iframe/>" ).attr( "src", "data/support/" + url + ".html" )
).appendTo( "body" );
});
}
supportIFrameTest( "proper boxModel in compatMode CSS1Compat (IE6 and IE7)", "boxModelIE", function( compatMode, boxModel ) {
ok( compatMode !== "CSS1Compat" || boxModel, "boxModel properly detected" );
});
supportIFrameTest( "body background is not lost if set prior to loading jQuery (#9238)", "bodyBackground", function( color, support ) {
expect( 2 );
var okValue = {
"#000000": true,
"rgb(0, 0, 0)": true
};
ok( okValue[ color ], "color was not reset (" + color + ")" );
var i, passed = true;
for ( i in jQuery.support ) {
if ( jQuery.support[ i ] !== support[ i ] ) {
passed = false;
strictEquals( jQuery.support[ i ], support[ i ], "Support property " + i + " is different" );
}
}
for ( i in support ) {
if ( !( i in jQuery.support ) ) {
ok = false;
strictEquals( src[ i ], dest[ i ], "Unexpected property: " + i );
}
}
ok( passed, "Same support properties" );
});

View file

@ -2,100 +2,47 @@ module("traversing", { teardown: moduleTeardown });
test("find(String)", function() { test("find(String)", function() {
expect(5); expect(5);
equals( "Yahoo", jQuery("#foo").find(".blogTest").text(), "Check for find" ); equals( 'Yahoo', jQuery('#foo').find('.blogTest').text(), 'Check for find' );
// using contents will get comments regular, text, and comment nodes // using contents will get comments regular, text, and comment nodes
var j = jQuery("#nonnodes").contents(); var j = jQuery("#nonnodes").contents();
equals( j.find("div").length, 0, "Check node,textnode,comment to find zero divs" ); equals( j.find("div").length, 0, "Check node,textnode,comment to find zero divs" );
same( jQuery("#qunit-fixture").find("> div").get(), q("foo", "moretests", "tabindex-tests", "liveHandlerOrder", "siblingTest"), "find child elements" ); same( jQuery("#main").find("> div").get(), q("foo", "moretests", "tabindex-tests", "liveHandlerOrder", "siblingTest"), "find child elements" );
same( jQuery("#qunit-fixture").find("> #foo, > #moretests").get(), q("foo", "moretests"), "find child elements" ); same( jQuery("#main").find("> #foo, > #moretests").get(), q("foo", "moretests"), "find child elements" );
same( jQuery("#qunit-fixture").find("> #foo > p").get(), q("sndp", "en", "sap"), "find child elements" ); same( jQuery("#main").find("> #foo > p").get(), q("sndp", "en", "sap"), "find child elements" );
}); });
test("find(node|jQuery object)", function() { test("is(String)", function() {
expect( 11 ); expect(26);
ok( jQuery('#form').is('form'), 'Check for element: A form must be a form' );
var $foo = jQuery("#foo"), ok( !jQuery('#form').is('div'), 'Check for element: A form is not a div' );
$blog = jQuery(".blogTest"), ok( jQuery('#mark').is('.blog'), 'Check for class: Expected class "blog"' );
$first = jQuery("#first"), ok( !jQuery('#mark').is('.link'), 'Check for class: Did not expect class "link"' );
$two = $blog.add( $first ), ok( jQuery('#simon').is('.blog.link'), 'Check for multiple classes: Expected classes "blog" and "link"' );
$fooTwo = $foo.add( $blog ); ok( !jQuery('#simon').is('.blogTest'), 'Check for multiple classes: Expected classes "blog" and "link", but not "blogTest"' );
ok( jQuery('#en').is('[lang="en"]'), 'Check for attribute: Expected attribute lang to be "en"' );
equals( $foo.find( $blog ).text(), "Yahoo", "Find with blog jQuery object" ); ok( !jQuery('#en').is('[lang="de"]'), 'Check for attribute: Expected attribute lang to be "en", not "de"' );
equals( $foo.find( $blog[0] ).text(), "Yahoo", "Find with blog node" ); ok( jQuery('#text1').is('[type="text"]'), 'Check for attribute: Expected attribute type to be "text"' );
equals( $foo.find( $first ).length, 0, "#first is not in #foo" ); ok( !jQuery('#text1').is('[type="radio"]'), 'Check for attribute: Expected attribute type to be "text", not "radio"' );
equals( $foo.find( $first[0]).length, 0, "#first not in #foo (node)" ); ok( jQuery('#text2').is(':disabled'), 'Check for pseudoclass: Expected to be disabled' );
ok( $foo.find( $two ).is(".blogTest"), "Find returns only nodes within #foo" ); ok( !jQuery('#text1').is(':disabled'), 'Check for pseudoclass: Expected not disabled' );
ok( $fooTwo.find( $blog ).is(".blogTest"), "Blog is part of the collection, but also within foo" ); ok( jQuery('#radio2').is(':checked'), 'Check for pseudoclass: Expected to be checked' );
ok( $fooTwo.find( $blog[0] ).is(".blogTest"), "Blog is part of the collection, but also within foo(node)" ); ok( !jQuery('#radio1').is(':checked'), 'Check for pseudoclass: Expected not checked' );
ok( jQuery('#foo').is(':has(p)'), 'Check for child: Expected a child "p" element' );
equals( $two.find( $foo ).length, 0, "Foo is not in two elements" ); ok( !jQuery('#foo').is(':has(ul)'), 'Check for child: Did not expect "ul" element' );
equals( $two.find( $foo[0] ).length, 0, "Foo is not in two elements(node)" ); ok( jQuery('#foo').is(':has(p):has(a):has(code)'), 'Check for childs: Expected "p", "a" and "code" child elements' );
equals( $two.find( $first ).length, 0, "first is in the collection and not within two" ); ok( !jQuery('#foo').is(':has(p):has(a):has(code):has(ol)'), 'Check for childs: Expected "p", "a" and "code" child elements, but no "ol"' );
equals( $two.find( $first ).length, 0, "first is in the collection and not within two(node)" ); ok( !jQuery('#foo').is(0), 'Expected false for an invalid expression - 0' );
ok( !jQuery('#foo').is(null), 'Expected false for an invalid expression - null' );
}); ok( !jQuery('#foo').is(''), 'Expected false for an invalid expression - ""' );
ok( !jQuery('#foo').is(undefined), 'Expected false for an invalid expression - undefined' );
test("is(String|undefined)", function() {
expect(27);
ok( jQuery("#form").is("form"), "Check for element: A form must be a form" );
ok( !jQuery("#form").is("div"), "Check for element: A form is not a div" );
ok( jQuery("#mark").is(".blog"), "Check for class: Expected class 'blog'" );
ok( !jQuery("#mark").is(".link"), "Check for class: Did not expect class 'link'" );
ok( jQuery("#simon").is(".blog.link"), "Check for multiple classes: Expected classes 'blog' and 'link'" );
ok( !jQuery("#simon").is(".blogTest"), "Check for multiple classes: Expected classes 'blog' and 'link', but not 'blogTest'" );
ok( jQuery("#en").is("[lang=\"en\"]"), "Check for attribute: Expected attribute lang to be 'en'" );
ok( !jQuery("#en").is("[lang=\"de\"]"), "Check for attribute: Expected attribute lang to be 'en', not 'de'" );
ok( jQuery("#text1").is("[type=\"text\"]"), "Check for attribute: Expected attribute type to be 'text'" );
ok( !jQuery("#text1").is("[type=\"radio\"]"), "Check for attribute: Expected attribute type to be 'text', not 'radio'" );
ok( jQuery("#text2").is(":disabled"), "Check for pseudoclass: Expected to be disabled" );
ok( !jQuery("#text1").is(":disabled"), "Check for pseudoclass: Expected not disabled" );
ok( jQuery("#radio2").is(":checked"), "Check for pseudoclass: Expected to be checked" );
ok( !jQuery("#radio1").is(":checked"), "Check for pseudoclass: Expected not checked" );
ok( jQuery("#foo").is(":has(p)"), "Check for child: Expected a child 'p' element" );
ok( !jQuery("#foo").is(":has(ul)"), "Check for child: Did not expect 'ul' element" );
ok( jQuery("#foo").is(":has(p):has(a):has(code)"), "Check for childs: Expected 'p', 'a' and 'code' child elements" );
ok( !jQuery("#foo").is(":has(p):has(a):has(code):has(ol)"), "Check for childs: Expected 'p', 'a' and 'code' child elements, but no 'ol'" );
ok( !jQuery("#foo").is(0), "Expected false for an invalid expression - 0" );
ok( !jQuery("#foo").is(null), "Expected false for an invalid expression - null" );
ok( !jQuery("#foo").is(""), "Expected false for an invalid expression - \"\"" );
ok( !jQuery("#foo").is(undefined), "Expected false for an invalid expression - undefined" );
ok( !jQuery("#foo").is({ plain: "object" }), "Check passing invalid object" );
// test is() with comma-seperated expressions // test is() with comma-seperated expressions
ok( jQuery("#en").is("[lang=\"en\"],[lang=\"de\"]"), "Comma-seperated; Check for lang attribute: Expect en or de" ); ok( jQuery('#en').is('[lang="en"],[lang="de"]'), 'Comma-seperated; Check for lang attribute: Expect en or de' );
ok( jQuery("#en").is("[lang=\"de\"],[lang=\"en\"]"), "Comma-seperated; Check for lang attribute: Expect en or de" ); ok( jQuery('#en').is('[lang="de"],[lang="en"]'), 'Comma-seperated; Check for lang attribute: Expect en or de' );
ok( jQuery("#en").is("[lang=\"en\"] , [lang=\"de\"]"), "Comma-seperated; Check for lang attribute: Expect en or de" ); ok( jQuery('#en').is('[lang="en"] , [lang="de"]'), 'Comma-seperated; Check for lang attribute: Expect en or de' );
ok( jQuery("#en").is("[lang=\"de\"] , [lang=\"en\"]"), "Comma-seperated; Check for lang attribute: Expect en or de" ); ok( jQuery('#en').is('[lang="de"] , [lang="en"]'), 'Comma-seperated; Check for lang attribute: Expect en or de' );
});
test("is(jQuery)", function() {
expect(21);
ok( jQuery("#form").is( jQuery("form") ), "Check for element: A form is a form" );
ok( !jQuery("#form").is( jQuery("div") ), "Check for element: A form is not a div" );
ok( jQuery("#mark").is( jQuery(".blog") ), "Check for class: Expected class 'blog'" );
ok( !jQuery("#mark").is( jQuery(".link") ), "Check for class: Did not expect class 'link'" );
ok( jQuery("#simon").is( jQuery(".blog.link") ), "Check for multiple classes: Expected classes 'blog' and 'link'" );
ok( !jQuery("#simon").is( jQuery(".blogTest") ), "Check for multiple classes: Expected classes 'blog' and 'link', but not 'blogTest'" );
ok( jQuery("#en").is( jQuery("[lang=\"en\"]") ), "Check for attribute: Expected attribute lang to be 'en'" );
ok( !jQuery("#en").is( jQuery("[lang=\"de\"]") ), "Check for attribute: Expected attribute lang to be 'en', not 'de'" );
ok( jQuery("#text1").is( jQuery("[type=\"text\"]") ), "Check for attribute: Expected attribute type to be 'text'" );
ok( !jQuery("#text1").is( jQuery("[type=\"radio\"]") ), "Check for attribute: Expected attribute type to be 'text', not 'radio'" );
ok( !jQuery("#text1").is( jQuery("input:disabled") ), "Check for pseudoclass: Expected not disabled" );
ok( jQuery("#radio2").is( jQuery("input:checked") ), "Check for pseudoclass: Expected to be checked" );
ok( !jQuery("#radio1").is( jQuery("input:checked") ), "Check for pseudoclass: Expected not checked" );
ok( jQuery("#foo").is( jQuery("div:has(p)") ), "Check for child: Expected a child 'p' element" );
ok( !jQuery("#foo").is( jQuery("div:has(ul)") ), "Check for child: Did not expect 'ul' element" );
// Some raw elements
ok( jQuery("#form").is( jQuery("form")[0] ), "Check for element: A form is a form" );
ok( !jQuery("#form").is( jQuery("div")[0] ), "Check for element: A form is not a div" );
ok( jQuery("#mark").is( jQuery(".blog")[0] ), "Check for class: Expected class 'blog'" );
ok( !jQuery("#mark").is( jQuery(".link")[0] ), "Check for class: Did not expect class 'link'" );
ok( jQuery("#simon").is( jQuery(".blog.link")[0] ), "Check for multiple classes: Expected classes 'blog' and 'link'" );
ok( !jQuery("#simon").is( jQuery(".blogTest")[0] ), "Check for multiple classes: Expected classes 'blog' and 'link', but not 'blogTest'" );
}); });
test("index()", function() { test("index()", function() {
@ -108,15 +55,15 @@ test("index(Object|String|undefined)", function() {
expect(16); expect(16);
var elements = jQuery([window, document]), var elements = jQuery([window, document]),
inputElements = jQuery("#radio1,#radio2,#check1,#check2"); inputElements = jQuery('#radio1,#radio2,#check1,#check2');
// Passing a node // Passing a node
equals( elements.index(window), 0, "Check for index of elements" ); equals( elements.index(window), 0, "Check for index of elements" );
equals( elements.index(document), 1, "Check for index of elements" ); equals( elements.index(document), 1, "Check for index of elements" );
equals( inputElements.index(document.getElementById("radio1")), 0, "Check for index of elements" ); equals( inputElements.index(document.getElementById('radio1')), 0, "Check for index of elements" );
equals( inputElements.index(document.getElementById("radio2")), 1, "Check for index of elements" ); equals( inputElements.index(document.getElementById('radio2')), 1, "Check for index of elements" );
equals( inputElements.index(document.getElementById("check1")), 2, "Check for index of elements" ); equals( inputElements.index(document.getElementById('check1')), 2, "Check for index of elements" );
equals( inputElements.index(document.getElementById("check2")), 3, "Check for index of elements" ); equals( inputElements.index(document.getElementById('check2')), 3, "Check for index of elements" );
equals( inputElements.index(window), -1, "Check for not found index" ); equals( inputElements.index(window), -1, "Check for not found index" );
equals( inputElements.index(document), -1, "Check for not found index" ); equals( inputElements.index(document), -1, "Check for not found index" );
@ -128,24 +75,19 @@ test("index(Object|String|undefined)", function() {
// Passing a selector or nothing // Passing a selector or nothing
// enabled since [6330] // enabled since [6330]
equals( jQuery("#text2").index(), 2, "Check for index amongst siblings" ); equals( jQuery('#text2').index(), 2, "Check for index amongst siblings" );
equals( jQuery("#form").children().eq(4).index(), 4, "Check for index amongst siblings" ); equals( jQuery('#form').children().eq(4).index(), 4, "Check for index amongst siblings" );
equals( jQuery("#radio2").index("#form :radio") , 1, "Check for index within a selector" ); equals( jQuery('#radio2').index('#form :radio') , 1, "Check for index within a selector" );
equals( jQuery("#form :radio").index( jQuery("#radio2") ), 1, "Check for index within a selector" ); equals( jQuery('#form :radio').index( jQuery('#radio2') ), 1, "Check for index within a selector" );
equals( jQuery("#radio2").index("#form :text") , -1, "Check for index not found within a selector" ); equals( jQuery('#radio2').index('#form :text') , -1, "Check for index not found within a selector" );
}); });
test("filter(Selector|undefined)", function() { test("filter(Selector)", function() {
expect(9); expect(5);
same( jQuery("#form input").filter(":checked").get(), q("radio2", "check1"), "filter(String)" ); same( jQuery("#form input").filter(":checked").get(), q("radio2", "check1"), "filter(String)" );
same( jQuery("p").filter("#ap, #sndp").get(), q("ap", "sndp"), "filter('String, String')" ); same( jQuery("p").filter("#ap, #sndp").get(), q("ap", "sndp"), "filter('String, String')" );
same( jQuery("p").filter("#ap,#sndp").get(), q("ap", "sndp"), "filter('String,String')" ); same( jQuery("p").filter("#ap,#sndp").get(), q("ap", "sndp"), "filter('String,String')" );
same( jQuery("p").filter(null).get(), [], "filter(null) should return an empty jQuery object");
same( jQuery("p").filter(undefined).get(), [], "filter(undefined) should return an empty jQuery object");
same( jQuery("p").filter(0).get(), [], "filter(0) should return an empty jQuery object");
same( jQuery("p").filter("").get(), [], "filter('') should return an empty jQuery object");
// using contents will get comments regular, text, and comment nodes // using contents will get comments regular, text, and comment nodes
var j = jQuery("#nonnodes").contents(); var j = jQuery("#nonnodes").contents();
equals( j.filter("span").length, 1, "Check node,textnode,comment to filter the one span" ); equals( j.filter("span").length, 1, "Check node,textnode,comment to filter the one span" );
@ -155,9 +97,9 @@ test("filter(Selector|undefined)", function() {
test("filter(Function)", function() { test("filter(Function)", function() {
expect(2); expect(2);
same( jQuery("#qunit-fixture p").filter(function() { return !jQuery("a", this).length }).get(), q("sndp", "first"), "filter(Function)" ); same( jQuery("#main p").filter(function() { return !jQuery("a", this).length }).get(), q("sndp", "first"), "filter(Function)" );
same( jQuery("#qunit-fixture p").filter(function(i, elem) { return !jQuery("a", elem).length }).get(), q("sndp", "first"), "filter(Function) using arg" ); same( jQuery("#main p").filter(function(i, elem) { return !jQuery("a", elem).length }).get(), q("sndp", "first"), "filter(Function) using arg" );
}); });
test("filter(Element)", function() { test("filter(Element)", function() {
@ -182,11 +124,11 @@ test("filter(jQuery)", function() {
}) })
test("closest()", function() { test("closest()", function() {
expect(13); expect(11);
same( jQuery("body").closest("body").get(), q("body"), "closest(body)" ); same( jQuery("body").closest("body").get(), q("body"), "closest(body)" );
same( jQuery("body").closest("html").get(), q("html"), "closest(html)" ); same( jQuery("body").closest("html").get(), q("html"), "closest(html)" );
same( jQuery("body").closest("div").get(), [], "closest(div)" ); same( jQuery("body").closest("div").get(), [], "closest(div)" );
same( jQuery("#qunit-fixture").closest("span,#html").get(), q("html"), "closest(span,#html)" ); same( jQuery("#main").closest("span,#html").get(), q("html"), "closest(span,#html)" );
same( jQuery("div:eq(1)").closest("div:first").get(), [], "closest(div:first)" ); same( jQuery("div:eq(1)").closest("div:first").get(), [], "closest(div:first)" );
same( jQuery("div").closest("body:first div:last").get(), q("fx-tests"), "closest(body:first div:last)" ); same( jQuery("div").closest("body:first div:last").get(), q("fx-tests"), "closest(body:first div:last)" );
@ -198,14 +140,10 @@ test("closest()", function() {
same( jq.closest("#nothiddendiv", document.body).get(), q("nothiddendiv"), "Context not reached." ); same( jq.closest("#nothiddendiv", document.body).get(), q("nothiddendiv"), "Context not reached." );
//Test that .closest() returns unique'd set //Test that .closest() returns unique'd set
equals( jQuery("#qunit-fixture p").closest("#qunit-fixture").length, 1, "Closest should return a unique set" ); equals( jQuery('#main p').closest('#main').length, 1, "Closest should return a unique set" );
// Test on disconnected node // Test on disconnected node
equals( jQuery("<div><p></p></div>").find("p").closest("table").length, 0, "Make sure disconnected closest work." ); equals( jQuery("<div><p></p></div>").find("p").closest("table").length, 0, "Make sure disconnected closest work." );
// Bug #7369
equals( jQuery("<div foo='bar'></div>").closest("[foo]").length, 1, "Disconnected nodes with attribute selector" );
equals( jQuery("<div>text</div>").closest("[lang]").length, 0, "Disconnected nodes with text and non-existent attribute selector" );
}); });
test("closest(Array)", function() { test("closest(Array)", function() {
@ -213,45 +151,23 @@ test("closest(Array)", function() {
same( jQuery("body").closest(["body"]), [{selector:"body", elem:document.body, level:1}], "closest([body])" ); same( jQuery("body").closest(["body"]), [{selector:"body", elem:document.body, level:1}], "closest([body])" );
same( jQuery("body").closest(["html"]), [{selector:"html", elem:document.documentElement, level:2}], "closest([html])" ); same( jQuery("body").closest(["html"]), [{selector:"html", elem:document.documentElement, level:2}], "closest([html])" );
same( jQuery("body").closest(["div"]), [], "closest([div])" ); same( jQuery("body").closest(["div"]), [], "closest([div])" );
same( jQuery("#yahoo").closest(["div"]), [{"selector":"div", "elem": document.getElementById("foo"), "level": 3}, { "selector": "div", "elem": document.getElementById("qunit-fixture"), "level": 4 }], "closest([div])" ); same( jQuery("#yahoo").closest(["div"]), [{"selector":"div", "elem": document.getElementById("foo"), "level": 3}, { "selector": "div", "elem": document.getElementById("main"), "level": 4 }], "closest([div])" );
same( jQuery("#qunit-fixture").closest(["span,#html"]), [{selector:"span,#html", elem:document.documentElement, level:4}], "closest([span,#html])" ); same( jQuery("#main").closest(["span,#html"]), [{selector:"span,#html", elem:document.documentElement, level:4}], "closest([span,#html])" );
same( jQuery("body").closest(["body","html"]), [{selector:"body", elem:document.body, level:1}, {selector:"html", elem:document.documentElement, level:2}], "closest([body, html])" ); same( jQuery("body").closest(["body","html"]), [{selector:"body", elem:document.body, level:1}, {selector:"html", elem:document.documentElement, level:2}], "closest([body, html])" );
same( jQuery("body").closest(["span","html"]), [{selector:"html", elem:document.documentElement, level:2}], "closest([body, html])" ); same( jQuery("body").closest(["span","html"]), [{selector:"html", elem:document.documentElement, level:2}], "closest([body, html])" );
}); });
test("closest(jQuery)", function() { test("not(Selector)", function() {
expect(8); expect(7);
var $child = jQuery("#nothiddendivchild"), equals( jQuery("#main > p#ap > a").not("#google").length, 2, "not('selector')" );
$parent = jQuery("#nothiddendiv"),
$main = jQuery("#qunit-fixture"),
$body = jQuery("body");
ok( $child.closest( $parent ).is("#nothiddendiv"), "closest( jQuery('#nothiddendiv') )" );
ok( $child.closest( $parent[0] ).is("#nothiddendiv"), "closest( jQuery('#nothiddendiv') ) :: node" );
ok( $child.closest( $child ).is("#nothiddendivchild"), "child is included" );
ok( $child.closest( $child[0] ).is("#nothiddendivchild"), "child is included :: node" );
equals( $child.closest( document.createElement("div") ).length, 0, "created element is not related" );
equals( $child.closest( $main ).length, 0, "Main not a parent of child" );
equals( $child.closest( $main[0] ).length, 0, "Main not a parent of child :: node" );
ok( $child.closest( $body.add($parent) ).is("#nothiddendiv"), "Closest ancestor retrieved." );
});
test("not(Selector|undefined)", function() {
expect(11);
equals( jQuery("#qunit-fixture > p#ap > a").not("#google").length, 2, "not('selector')" );
same( jQuery("p").not(".result").get(), q("firstp", "ap", "sndp", "en", "sap", "first"), "not('.class')" ); same( jQuery("p").not(".result").get(), q("firstp", "ap", "sndp", "en", "sap", "first"), "not('.class')" );
same( jQuery("p").not("#ap, #sndp, .result").get(), q("firstp", "en", "sap", "first"), "not('selector, selector')" ); same( jQuery("p").not("#ap, #sndp, .result").get(), q("firstp", "en", "sap", "first"), "not('selector, selector')" );
same( jQuery("#form option").not("option.emptyopt:contains('Nothing'),[selected],[value='1']").get(), q("option1c", "option1d", "option2c", "option3d", "option3e", "option4e","option5b"), "not('complex selector')"); same( jQuery("#form option").not("option.emptyopt:contains('Nothing'),[selected],[value='1']").get(), q("option1c", "option1d", "option2c", "option3d", "option3e", "option4e","option5b"), "not('complex selector')");
same( jQuery("#ap *").not("code").get(), q("google", "groups", "anchor1", "mark"), "not('tag selector')" ); same( jQuery('#ap *').not('code').get(), q("google", "groups", "anchor1", "mark"), "not('tag selector')" );
same( jQuery("#ap *").not("code, #mark").get(), q("google", "groups", "anchor1"), "not('tag, ID selector')" ); same( jQuery('#ap *').not('code, #mark').get(), q("google", "groups", "anchor1"), "not('tag, ID selector')" );
same( jQuery("#ap *").not("#mark, code").get(), q("google", "groups", "anchor1"), "not('ID, tag selector')"); same( jQuery('#ap *').not('#mark, code').get(), q("google", "groups", "anchor1"), "not('ID, tag selector')");
var all = jQuery("p").get();
same( jQuery("p").not(null).get(), all, "not(null) should have no effect");
same( jQuery("p").not(undefined).get(), all, "not(undefined) should have no effect");
same( jQuery("p").not(0).get(), all, "not(0) should have no effect");
same( jQuery("p").not("").get(), all, "not('') should have no effect");
}); });
test("not(Element)", function() { test("not(Element)", function() {
@ -262,13 +178,13 @@ test("not(Element)", function() {
}); });
test("not(Function)", function() { test("not(Function)", function() {
same( jQuery("#qunit-fixture p").not(function() { return jQuery("a", this).length }).get(), q("sndp", "first"), "not(Function)" ); same( jQuery("#main p").not(function() { return jQuery("a", this).length }).get(), q("sndp", "first"), "not(Function)" );
}); });
test("not(Array)", function() { test("not(Array)", function() {
expect(2); expect(2);
equals( jQuery("#qunit-fixture > p#ap > a").not(document.getElementById("google")).length, 2, "not(DOMElement)" ); equals( jQuery("#main > p#ap > a").not(document.getElementById("google")).length, 2, "not(DOMElement)" );
equals( jQuery("p").not(document.getElementsByTagName("p")).length, 0, "not(Array-like DOM collection)" ); equals( jQuery("p").not(document.getElementsByTagName("p")).length, 0, "not(Array-like DOM collection)" );
}); });
@ -281,37 +197,37 @@ test("not(jQuery)", function() {
test("has(Element)", function() { test("has(Element)", function() {
expect(2); expect(2);
var obj = jQuery("#qunit-fixture").has(jQuery("#sndp")[0]); var obj = jQuery("#main").has(jQuery("#sndp")[0]);
same( obj.get(), q("qunit-fixture"), "Keeps elements that have the element as a descendant" ); same( obj.get(), q("main"), "Keeps elements that have the element as a descendant" );
var multipleParent = jQuery("#qunit-fixture, #header").has(jQuery("#sndp")[0]); var multipleParent = jQuery("#main, #header").has(jQuery("#sndp")[0]);
same( obj.get(), q("qunit-fixture"), "Does not include elements that do not have the element as a descendant" ); same( obj.get(), q("main"), "Does not include elements that do not have the element as a descendant" );
}); });
test("has(Selector)", function() { test("has(Selector)", function() {
expect(3); expect(3);
var obj = jQuery("#qunit-fixture").has("#sndp"); var obj = jQuery("#main").has("#sndp");
same( obj.get(), q("qunit-fixture"), "Keeps elements that have any element matching the selector as a descendant" ); same( obj.get(), q("main"), "Keeps elements that have any element matching the selector as a descendant" );
var multipleParent = jQuery("#qunit-fixture, #header").has("#sndp"); var multipleParent = jQuery("#main, #header").has("#sndp");
same( obj.get(), q("qunit-fixture"), "Does not include elements that do not have the element as a descendant" ); same( obj.get(), q("main"), "Does not include elements that do not have the element as a descendant" );
var multipleHas = jQuery("#qunit-fixture").has("#sndp, #first"); var multipleHas = jQuery("#main").has("#sndp, #first");
same( multipleHas.get(), q("qunit-fixture"), "Only adds elements once" ); same( multipleHas.get(), q("main"), "Only adds elements once" );
}); });
test("has(Arrayish)", function() { test("has(Arrayish)", function() {
expect(3); expect(3);
var simple = jQuery("#qunit-fixture").has(jQuery("#sndp")); var simple = jQuery("#main").has(jQuery("#sndp"));
same( simple.get(), q("qunit-fixture"), "Keeps elements that have any element in the jQuery list as a descendant" ); same( simple.get(), q("main"), "Keeps elements that have any element in the jQuery list as a descendant" );
var multipleParent = jQuery("#qunit-fixture, #header").has(jQuery("#sndp")); var multipleParent = jQuery("#main, #header").has(jQuery("#sndp"));
same( multipleParent.get(), q("qunit-fixture"), "Does not include elements that do not have an element in the jQuery list as a descendant" ); same( multipleParent.get(), q("main"), "Does not include elements that do not have an element in the jQuery list as a descendant" );
var multipleHas = jQuery("#qunit-fixture").has(jQuery("#sndp, #first")); var multipleHas = jQuery("#main").has(jQuery("#sndp, #first"));
same( simple.get(), q("qunit-fixture"), "Only adds elements once" ); same( simple.get(), q("main"), "Only adds elements once" );
}); });
test("andSelf()", function() { test("andSelf()", function() {
@ -319,7 +235,7 @@ test("andSelf()", function() {
same( jQuery("#en").siblings().andSelf().get(), q("sndp", "en", "sap"), "Check for siblings and self" ); same( jQuery("#en").siblings().andSelf().get(), q("sndp", "en", "sap"), "Check for siblings and self" );
same( jQuery("#foo").children().andSelf().get(), q("foo", "sndp", "en", "sap"), "Check for children and self" ); same( jQuery("#foo").children().andSelf().get(), q("foo", "sndp", "en", "sap"), "Check for children and self" );
same( jQuery("#sndp, #en").parent().andSelf().get(), q("foo","sndp","en"), "Check for parent and self" ); same( jQuery("#sndp, #en").parent().andSelf().get(), q("foo","sndp","en"), "Check for parent and self" );
same( jQuery("#groups").parents("p, div").andSelf().get(), q("qunit-fixture", "ap", "groups"), "Check for parents and self" ); same( jQuery("#groups").parents("p, div").andSelf().get(), q("main", "ap", "groups"), "Check for parents and self" );
}); });
test("siblings([String])", function() { test("siblings([String])", function() {
@ -352,9 +268,9 @@ test("parents([String])", function() {
expect(5); expect(5);
equals( jQuery("#groups").parents()[0].id, "ap", "Simple parents check" ); equals( jQuery("#groups").parents()[0].id, "ap", "Simple parents check" );
equals( jQuery("#groups").parents("p")[0].id, "ap", "Filtered parents check" ); equals( jQuery("#groups").parents("p")[0].id, "ap", "Filtered parents check" );
equals( jQuery("#groups").parents("div")[0].id, "qunit-fixture", "Filtered parents check2" ); equals( jQuery("#groups").parents("div")[0].id, "main", "Filtered parents check2" );
same( jQuery("#groups").parents("p, div").get(), q("ap", "qunit-fixture"), "Check for multiple filters" ); same( jQuery("#groups").parents("p, div").get(), q("ap", "main"), "Check for multiple filters" );
same( jQuery("#en, #sndp").parents().get(), q("foo", "qunit-fixture", "dl", "body", "html"), "Check for unique results from parents" ); same( jQuery("#en, #sndp").parents().get(), q("foo", "main", "dl", "body", "html"), "Check for unique results from parents" );
}); });
test("parentsUntil([String])", function() { test("parentsUntil([String])", function() {
@ -364,10 +280,10 @@ test("parentsUntil([String])", function() {
same( jQuery("#groups").parentsUntil().get(), parents.get(), "parentsUntil with no selector (nextAll)" ); same( jQuery("#groups").parentsUntil().get(), parents.get(), "parentsUntil with no selector (nextAll)" );
same( jQuery("#groups").parentsUntil(".foo").get(), parents.get(), "parentsUntil with invalid selector (nextAll)" ); same( jQuery("#groups").parentsUntil(".foo").get(), parents.get(), "parentsUntil with invalid selector (nextAll)" );
same( jQuery("#groups").parentsUntil("#html").get(), parents.not(":last").get(), "Simple parentsUntil check" ); same( jQuery("#groups").parentsUntil("#html").get(), parents.not(':last').get(), "Simple parentsUntil check" );
equals( jQuery("#groups").parentsUntil("#ap").length, 0, "Simple parentsUntil check" ); equals( jQuery("#groups").parentsUntil("#ap").length, 0, "Simple parentsUntil check" );
same( jQuery("#groups").parentsUntil("#html, #body").get(), parents.slice( 0, 3 ).get(), "Less simple parentsUntil check" ); same( jQuery("#groups").parentsUntil("#html, #body").get(), parents.slice( 0, 3 ).get(), "Less simple parentsUntil check" );
same( jQuery("#groups").parentsUntil("#html", "div").get(), jQuery("#qunit-fixture").get(), "Filtered parentsUntil check" ); same( jQuery("#groups").parentsUntil("#html", "div").get(), jQuery("#main").get(), "Filtered parentsUntil check" );
same( jQuery("#groups").parentsUntil("#html", "p,div,dl").get(), parents.slice( 0, 3 ).get(), "Multiple-filtered parentsUntil check" ); same( jQuery("#groups").parentsUntil("#html", "p,div,dl").get(), parents.slice( 0, 3 ).get(), "Multiple-filtered parentsUntil check" );
equals( jQuery("#groups").parentsUntil("#html", "span").length, 0, "Filtered parentsUntil check, no match" ); equals( jQuery("#groups").parentsUntil("#html", "span").length, 0, "Filtered parentsUntil check, no match" );
same( jQuery("#groups, #ap").parentsUntil("#html", "p,div,dl").get(), parents.slice( 0, 3 ).get(), "Multi-source, multiple-filtered parentsUntil check" ); same( jQuery("#groups, #ap").parentsUntil("#html", "p,div,dl").get(), parents.slice( 0, 3 ).get(), "Multi-source, multiple-filtered parentsUntil check" );
@ -392,29 +308,29 @@ test("prev([String])", function() {
test("nextAll([String])", function() { test("nextAll([String])", function() {
expect(4); expect(4);
var elems = jQuery("#form").children(); var elems = jQuery('#form').children();
same( jQuery("#label-for").nextAll().get(), elems.not(":first").get(), "Simple nextAll check" ); same( jQuery("#label-for").nextAll().get(), elems.not(':first').get(), "Simple nextAll check" );
same( jQuery("#label-for").nextAll("input").get(), elems.not(":first").filter("input").get(), "Filtered nextAll check" ); same( jQuery("#label-for").nextAll('input').get(), elems.not(':first').filter('input').get(), "Filtered nextAll check" );
same( jQuery("#label-for").nextAll("input,select").get(), elems.not(":first").filter("input,select").get(), "Multiple-filtered nextAll check" ); same( jQuery("#label-for").nextAll('input,select').get(), elems.not(':first').filter('input,select').get(), "Multiple-filtered nextAll check" );
same( jQuery("#label-for, #hidden1").nextAll("input,select").get(), elems.not(":first").filter("input,select").get(), "Multi-source, multiple-filtered nextAll check" ); same( jQuery("#label-for, #hidden1").nextAll('input,select').get(), elems.not(':first').filter('input,select').get(), "Multi-source, multiple-filtered nextAll check" );
}); });
test("prevAll([String])", function() { test("prevAll([String])", function() {
expect(4); expect(4);
var elems = jQuery( jQuery("#form").children().slice(0, 12).get().reverse() ); var elems = jQuery( jQuery('#form').children().slice(0, 12).get().reverse() );
same( jQuery("#area1").prevAll().get(), elems.get(), "Simple prevAll check" ); same( jQuery("#area1").prevAll().get(), elems.get(), "Simple prevAll check" );
same( jQuery("#area1").prevAll("input").get(), elems.filter("input").get(), "Filtered prevAll check" ); same( jQuery("#area1").prevAll('input').get(), elems.filter('input').get(), "Filtered prevAll check" );
same( jQuery("#area1").prevAll("input,select").get(), elems.filter("input,select").get(), "Multiple-filtered prevAll check" ); same( jQuery("#area1").prevAll('input,select').get(), elems.filter('input,select').get(), "Multiple-filtered prevAll check" );
same( jQuery("#area1, #hidden1").prevAll("input,select").get(), elems.filter("input,select").get(), "Multi-source, multiple-filtered prevAll check" ); same( jQuery("#area1, #hidden1").prevAll('input,select').get(), elems.filter('input,select').get(), "Multi-source, multiple-filtered prevAll check" );
}); });
test("nextUntil([String])", function() { test("nextUntil([String])", function() {
expect(11); expect(11);
var elems = jQuery("#form").children().slice( 2, 12 ); var elems = jQuery('#form').children().slice( 2, 12 );
same( jQuery("#text1").nextUntil().get(), jQuery("#text1").nextAll().get(), "nextUntil with no selector (nextAll)" ); same( jQuery("#text1").nextUntil().get(), jQuery("#text1").nextAll().get(), "nextUntil with no selector (nextAll)" );
same( jQuery("#text1").nextUntil(".foo").get(), jQuery("#text1").nextAll().get(), "nextUntil with invalid selector (nextAll)" ); same( jQuery("#text1").nextUntil(".foo").get(), jQuery("#text1").nextAll().get(), "nextUntil with invalid selector (nextAll)" );
@ -437,14 +353,14 @@ test("prevUntil([String])", function() {
same( jQuery("#area1").prevUntil().get(), elems.get(), "prevUntil with no selector (prevAll)" ); same( jQuery("#area1").prevUntil().get(), elems.get(), "prevUntil with no selector (prevAll)" );
same( jQuery("#area1").prevUntil(".foo").get(), elems.get(), "prevUntil with invalid selector (prevAll)" ); same( jQuery("#area1").prevUntil(".foo").get(), elems.get(), "prevUntil with invalid selector (prevAll)" );
same( jQuery("#area1").prevUntil("label").get(), elems.not(":last").get(), "Simple prevUntil check" ); same( jQuery("#area1").prevUntil("label").get(), elems.not(':last').get(), "Simple prevUntil check" );
equals( jQuery("#area1").prevUntil("#button").length, 0, "Simple prevUntil check" ); equals( jQuery("#area1").prevUntil("#button").length, 0, "Simple prevUntil check" );
same( jQuery("#area1").prevUntil("label, #search").get(), jQuery("#area1").prev().get(), "Less simple prevUntil check" ); same( jQuery("#area1").prevUntil("label, #search").get(), jQuery("#area1").prev().get(), "Less simple prevUntil check" );
same( jQuery("#area1").prevUntil("label", "input").get(), elems.not(":last").not("button").get(), "Filtered prevUntil check" ); same( jQuery("#area1").prevUntil("label", "input").get(), elems.not(':last').not("button").get(), "Filtered prevUntil check" );
same( jQuery("#area1").prevUntil("label", "button").get(), elems.not(":last").not("input").get(), "Filtered prevUntil check" ); same( jQuery("#area1").prevUntil("label", "button").get(), elems.not(':last').not("input").get(), "Filtered prevUntil check" );
same( jQuery("#area1").prevUntil("label", "button,input").get(), elems.not(":last").get(), "Multiple-filtered prevUntil check" ); same( jQuery("#area1").prevUntil("label", "button,input").get(), elems.not(':last').get(), "Multiple-filtered prevUntil check" );
equals( jQuery("#area1").prevUntil("label", "div").length, 0, "Filtered prevUntil check, no match" ); equals( jQuery("#area1").prevUntil("label", "div").length, 0, "Filtered prevUntil check, no match" );
same( jQuery("#area1, #hidden1").prevUntil("label", "button,input").get(), elems.not(":last").get(), "Multi-source, multiple-filtered prevUntil check" ); same( jQuery("#area1, #hidden1").prevUntil("label", "button,input").get(), elems.not(':last').get(), "Multi-source, multiple-filtered prevUntil check" );
}); });
test("contents()", function() { test("contents()", function() {
@ -483,12 +399,7 @@ test("add(String|Element|Array|undefined)", function() {
expect(16); expect(16);
same( jQuery("#sndp").add("#en").add("#sap").get(), q("sndp", "en", "sap"), "Check elements from document" ); same( jQuery("#sndp").add("#en").add("#sap").get(), q("sndp", "en", "sap"), "Check elements from document" );
same( jQuery("#sndp").add( jQuery("#en")[0] ).add( jQuery("#sap") ).get(), q("sndp", "en", "sap"), "Check elements from document" ); same( jQuery("#sndp").add( jQuery("#en")[0] ).add( jQuery("#sap") ).get(), q("sndp", "en", "sap"), "Check elements from document" );
ok( jQuery([]).add(jQuery("#form")[0].elements).length >= 13, "Check elements from array" );
// We no longer support .add(form.elements), unfortunately.
// There is no way, in browsers, to reliably determine the difference
// between form.elements and form - and doing .add(form) and having it
// add the form elements is way to unexpected, so this gets the boot.
// ok( jQuery([]).add(jQuery("#form")[0].elements).length >= 13, "Check elements from array" );
// For the time being, we're discontinuing support for jQuery(form.elements) since it's ambiguous in IE // For the time being, we're discontinuing support for jQuery(form.elements) since it's ambiguous in IE
// use jQuery([]).add(form.elements) instead. // use jQuery([]).add(form.elements) instead.
@ -524,8 +435,7 @@ test("add(String|Element|Array|undefined)", function() {
var notDefined; var notDefined;
equals( jQuery([]).add(notDefined).length, 0, "Check that undefined adds nothing" ); equals( jQuery([]).add(notDefined).length, 0, "Check that undefined adds nothing" );
equals( jQuery([]).add( document.getElementById("form") ).length, 1, "Add a form" ); ok( jQuery([]).add( document.getElementById('form') ).length >= 13, "Add a form (adds the elements)" );
equals( jQuery([]).add( document.getElementById("select1") ).length, 1, "Add a select" );
}); });
test("add(String, Context)", function() { test("add(String, Context)", function() {

View file

@ -1 +1 @@
1.6.3pre 1.5.2