DOM Helpers page
JavaScriptMVC adds a bunch of useful jQuery extensions for the dom. Checkthem out on the left.
Set and animate the inner and outer height and width of elements.
$('#foo').outerWidth(100);
$('#bar').animate({innerWidth:500});
This is great when you want to include padding and margin in setting thedimensions of elements.
Set and get cookie values:
$.cookie('cookie','value');
Simulate Ajax responses.
$.fixture("/services/tasks.php','fixtures/tasks.json');
Works with jQuery's Ajax converters!
Compare the location of two elements rapidly.
$('#foo').compare($('#bar')) & 2 // true if #bar isbefore #foo
Get multiple css properties quickly.
$('#foo').curStyles('left','top') //->{left:'20px',top:'10px'}
Serializes a form into a JSON-like object:
$('form').formParams()//-> {name: 'Justin', favs: ['JS','Ruby']}
Gets or sets the current text selection.
// gets selection info
$('pre').selection()//-> {start: 22, end: 57, range: range}
// sets the selection
$('div').selection(20,22)
Returns elements that have a point within their boundaries.
$('.drop').within(200,200) //-> drops thattouch 200,200
Text range utilities.
$('#copy').range() //-> text range that has copy selected
Hash routes mapped to an $.Observe.
$.route(':type',{type: 'videos'})
$.route.delegate('type','set', function(){ ... })
$.route.attr('type','images');
dimensions page
plugin: jquery/dom/dimensions
The dimensions plugin adds support for setting+animatinginner+outer height and widths.
Quick Examples
$(
'#foo').outerWidth(
100).innerHeight(
50);
$(
'#bar').animate({outerWidth:
500});
Use
When writing reusable plugins, you often want to set oranimate an element's width and height that include its padding, border, ormargin. This is especially important in plugins that allow custom styling.
The dimensions plugin overwrites outerHeight,outerWidth,innerHeightand innerWidthto let you set and animate these properties.
Demo
Demo
HTML
<p>Adjust The red box's layout properties.
</p>
<label>Width
</label><input id="width"><br>
<label>+ Padding
</label><input id="paddingRight"><br>
<label>= Inner
</label><input id="innerWidth"><br>
<label>+ Border
</label><input id="borderRightWidth"><br>
<label>= Outer
</label><input id="outerWidth"><br>
<label>Margin
</label><input id="marginRight"><br>
<br>
<div id="wrapper">
<div id="block">
<div id="inner">
Adjust My Layout Properties
</div>
</div>
</div>
Source
steal(
'jquery/dom/dimensions').then(
function(){
// sets the values in the input boxes
varset =
function() {
var
block = $(
'#block');
//get with .fn helpers
$(
"#outerWidth, #innerWidth, #width").each(
function(){
$(
this).val( block[
this.id]() )
})
//use curStyles
$.each($(
'#block').curStyles(
"paddingRight",
"borderRightWidth"
,
"marginRight"
),
function(name, val){
$(
"#"+name).val( parseInt(val) )
});
}
set();
// updates the dimensions of the block
varupdate =
function( ev ) {
var
name = ev.target.id,
val = parseInt( $(ev.target).val() ),
opposite = {Width:
"Height", Right:
"Bottom"},
// the opposite dimension name
otherName = name.replace(
/width|right/i,
function(part, i){
return
i ==
0?
"height": opposite[part];
}),
block = $(
'#block'),
css = {};
if
( block[name] ) {
// set with innerHeight, outerHeight, etc
block[name]( val )[otherName](val)
}
else{
// set as css property
css[name] = val+
"px"
css[otherName] = val+
"px"
block.css(css)
}
set();
};
// call update on change or after
// typing has stopped for a second
var timer;
$(
"input").live(
'change',update)
$(
"input").live(
'keyup',
function(ev) {
clearTimeout(timer)
timer = setTimeout(
function() {
update(ev)
},
1400)
})
})
jQuery.fn.innerHeight function
Lets you set the outer width on an object
API
$.fn.innerHeight(height)
jQuery.fn.innerWidth function
Lets you set the inner height of an object
API
$.fn.innerWidth(height)
height {optional:Number}
jQuery.fn.outerHeight function
Lets you set the outer height of an object where:
outerHeight =height + padding + border + (margin).
$("#foo").outerHeight(100); //sets outerheight
$("#foo").outerHeight(100, true); //uses margins
$("#foo").outerHeight(); //returns outerheight
$("#foo").outerHeight(true); //returns outerheight with margins
When setting the outerHeight, it adjusts the height ofthe element.
API
$.fn.outerHeight(height,includeMargin) -> jQuery|Number
height {optional:Number|Boolean}
If a number is provided -> sets the outer height of the object.
If true is given -> returns the outer height and includes margins.
If no value is given -> returns the outer height without margin.
includeMargin {optional:Boolean}
Makes setting the outerHeight adjust for margin.
returns {jQuery|Number}
If you are setting the value, returns the jQuery wrapped elements.Otherwise, returns outerHeight in pixels.
jQuery.fn.outerWidth function
Lets you set the outer width on an object
API
$.fn.outerWidth(height,includeMargin) -> jQuery|Number
height {optional:Number}
includeMargin {optional:Boolean} defaults to false
Makes setting the outerWidth adjust for margin. Defaults to false.
$('#hasMargin').outerWidth(50, true);
returns {jQuery|Number}
If you are setting the value, returns the jQuery wrapped elements.
jQuery.cookie function
plugin: jquery/dom/cookie
JavaScriptMVC's packaged cookie plugin is written by KlausHartl (stilbuero.de)
Dual licensed under the MIT and GPL licenses:
http://www.opensource.org/licenses/mit-license.php
http://www.gnu.org/licenses/gpl.html
Create a cookie with the given name and value and otheroptional parameters. / Get the value of a cookie with the given name.
Quick Examples
Set the value of a cookie.
$.cookie(
'the_cookie',
'the_value');
Create a cookie with all available options.
$.cookie(
'the_cookie',
'the_value',
{ expires:
7, path:
'/', domain:
'jquery.com', secure:
true});
Create a session cookie.
$.cookie(
'the_cookie',
'the_value');
Delete a cookie by passing null as value. Keep in mind thatyou have to use the same path and domain used when the cookie was set.
$.cookie(
'the_cookie',
null);
Get the value of a cookie.
$.cookie(
'the_cookie');
API
$.cookie(name, value, options, expires, path, domain, secure) -> String
name {optional:String}
The name of the cookie.
value {optional:String}
The value of the cookie.
options {optional:Object}
An object literal containing key/value pairs to provideoptional cookie attributes.
expires {optional:Number|Date}
Either an integer specifying the expiration date from nowon in days or a Date object. If a negative value is specified (e.g. a date inthe past), the cookie will be deleted. If set to null or omitted, the cookiewill be a session cookie and will not be retained when the the browser exits.
path {optional:String}
The value of the path atribute of the cookie (default: pathof page that created the cookie).
domain {optional:String}
The value of the domain attribute of the cookie (default:domain of page that created the cookie).
secure {Boolean}
If true, the secure attribute of the cookie will be set andthe cookie transmission will require a secure protocol (like HTTPS).
returns {String}
the value of the cookie or {undefined} when setting thecookie.
jQuery.fixture function
plugin: jquery/dom/fixture
download: jQuery.fixture
test: qunit.html
$.fixture
intercepts aAJAX request and simulates the response with a file or function. They are agreat technique when you want to develop JavaScript independently of thebackend.
Types of Fixtures
There are two common ways of using fixtures. The first isto map Ajax requests to another file. The following intercepts requests to /tasks.json
and directs them to fixtures/tasks.json
:
$.fixture(
"/tasks.json",
"fixtures/tasks.json");
The other common option is to generate the Ajax responsewith a function. The following intercepts updating tasks at /tasks/ID.json
and responds with updated data:
$.fixture(
"PUT /tasks/{id}.json",
function(original, settings, headers){
return
{ updatedAt :
newDate().getTime() }
})
We categorize fixtures into the following types:
- Static - the response is in a file.
- Dynamic - the response is generated by a function.
There are different ways to lookup static and dynamicfixtures.
Static Fixtures
Static fixtures use an alternate url as the response of theAjax request.
// looks in fixtures/tasks1.json relative to page
$.fixture(
"tasks/1",
"fixtures/task1.json");
$.fixture(
"tasks/1",
"//fixtures/task1.json");
Dynamic Fixtures
Dynamic Fixtures are functions that get the details of theAjax request and return the result of the mocked service request from yourserver.
For example, the following returns a successful responsewith JSON data from the server:
$.fixture(
"/foobar.json",
function(orig, settings, headers){
return
[
200,
"success", {json: {foo:
"bar"} }, {} ]
})
The fixture function has the following signature:
function( originalOptions, options, headers ) {
return
[ status, statusText, responses, responseHeaders ]
}
where the fixture function is called with:
- originalOptions - are the options provided to the ajax method, unmodified, and thus, without defaults from ajaxSettings
- options - are the request options
- headers - a map of key/value request headers
and the fixture function returns an array as arguments forajaxTransport's completeCallback
with:
- status - is the HTTP status code of the response.
- statusText - the status text of the response
- responses - a map of dataType/value that contains the responses for each data format supported
- headers - response headers
However, $.fixture handles the common case where you want asuccessful response with JSON data. The previous can be written like:
$.fixture(
"/foobar.json",
function(orig, settings, headers){
return
{foo:
"bar"};
})
If you want to return an array of data, wrap your array inanother array:
$.fixture(
"/tasks.json",
function(orig, settings, headers){
return
[ [
"first",
"second",
"third"] ];
})
$.fixture works closesly with jQuery's ajaxTransportsystem. Understanding it is the key to creating advanced fixtures.
Templated Urls
Often, you want a dynamic fixture to handle urls formultiple resources (for example a REST url scheme). $.fixture's templated urlsallow you to match urls with a wildcard.
The following example simulates services that get andupdate 100 todos.
// create todos
var todos = {};
for(
vari =
0; i <
100; i++) {
todos[i] = {
id: i,
name:
"Todo "+i
}
}
$.fixture(
"GET /todos/{id}",
function(orig){
// return the JSON data
// notice that id is pulled from the url and added to data
return
todos[orig.data.id]
})
$.fixture(
"PUT /todos/{id}",
function(orig){
// update the todo's data
$.extend( todos[orig.data.id], orig.data );
// return data
return
{};
})
Notice that data found in templated urls (ex: {id}
)is added to the original data object.
Simulating Errors
The following simulates an unauthorized request to /foo
.
$.fixture(
"/foo",
function(){
return
[
401,
"{type: 'unauthorized'}"]
});
This could be received by the following Ajax request:
$.ajax({
url:
'/foo',
error :
function(jqXhr, status, statusText){
// status === 'error'
// statusText === "{type: 'unauthorized'}"
}
})
Turning off Fixtures
You can remove a fixture by passing null
forthe fixture option:
// add a fixture
$.fixture(
"GET todos.json",
"//fixtures/todos.json");
// remove the fixture
$.fixture(
"GET todos.json",
null)
You can also set [jQuery.fixture.on $.fixture.on] to false:
$.fixture.on =
false;
Make
$.fixture.makemakes a CRUD service layer that handles sorting, grouping, filtering and more.
Testing Performance
Dynamic fixtures are awesome for performance testing. Wantto see what 10000 files does to your app's performance? Make a fixture thatreturns 10000 items.
What to see what the app feels like when a request takes 5seconds to return? Set [jQuery.fixture.delay] to 5000.
Demo
HTML
<div id="content"></div>
Source
steal(
'jquery/dom/fixture',
'jquery/dom/form_params'
,
function(){
$.fixture(
"/messages.php",
'fixtures/messages.html'
)
// gets content from a fixture
$.get(
"/messages.php",
function(html){
// put the result in content
$(
'#content').html(html)
},
'text'
);
// makes 20 messages in a fixture
$.fixture.make([
"messages",
"message"],
20,
function(i, messages){
return
{
subject:
"This is message "+i,
body:
"Here is some text for this message",
user:
"Justin",
createdAt: String(
newDate( Math.random() *
newDate().getTime() ))
}
});
// gets messages on submit
$(
"#getMessages").live(
"submit",
function(ev){
ev.preventDefault();
//get the limit and offset
var
params = $(
this).formParams().params;
//use -messages fixture created by make
$.ajax({
url:
"/messages.json",
data: params,
success:
function(json){
$(
"#messages").html( messagesHTML(json) )
},
dataType:
"json",
fixture:
"-messages"
})
});
// a fixture for creating messages
$.fixture[
"-createMessage"] =
function(settings, cbType){
// add to the message data what the server would add
var
message = $.extend({
id: arguments.callee.count++,
user:
"Justin",
createdAt: String(
newDate())
}, settings.data);
message.id = $.fixture[
"~messages"].length;
// adds the message to the fixture data
$.fixture[
"~messages"].push(message);
// return the data for the callback
return
[message];
};
// creates a message on submit
$(
"#message").live(
"submit",
function(ev){
ev.preventDefault();
// get message data
var
message = $(
this).formParams().message;
// uses -createMessage fixture
$.post(
"/message.json", message,
function(json){
//clear the message form
$(
'[name*=message]').val(
"");
//show the new message
$(
'[name*=offset]').val(json.id)
$(
'[name*=limit]').val(
1)
$(
"#getMessages").submit();
},
'json',
"-createMessage")
})
//creates the html from message data
varmessagesHTML =
function(json){
var
html = [
"<h4>Messages (count=",
json.count,
")</h4>"
,
"<table>"
,
"<tr>"
],
cols = [
"subject",
"body"
,
"user"
,
"createdAt"
];
// html for the column headers
$.each(cols,
function(i, prop){
html.push(
"<th>"+prop+
"</th>")
})
html.push(
"</tr>")
// html for the messages
$.each(json.data,
function(m, message){
html.push(
"<tr>")
$.each(cols,
function(i, prop){
html.push(
"<td>"+message[prop]+
"</td>")
})
html.push(
"</tr>")
})
html.push(
"</table>");
return
html.join(
"");
}
});
API
$.fixture(settings, fixture) -> undefined
settings {Object|String}
Configures the AJAX requests the fixture should intercept.If an objectis passed, the object's properties and values are matched against the settingspassed to $.ajax.
If a string is passed, it can be used to match the url and type.Urls can be templated, using {NAME}
as wildcards.
fixture {Function|String}
The response to use for the AJAX request. If a string url ispassed, the ajax request is redirected to the url. If a function isprovided, it looks like:
fixture( originalSettings, settings, headers )
where:
- originalSettings - the orignal settings passed to $.ajax
- settings - the settings after all filters have run
- headers - request headers
If null is passed, and there is a fixture at settings, thatfixture will be removed, allowing the AJAX request to behave normally.
returns {undefined}
Organizing Fixtures page
The best way of organizing fixtures is to have a 'fixtures.js' filethat steals jquery/dom/fixture and defines all your fixtures. For example, if you havea 'todo' application, you might have todo/fixtures/fixtures.js look like:
steal({
path: '//jquery/dom/fixture.js',
ignore: true
})
.then(function(){
$.fixture({
type: 'get',
url: '/services/todos.json'
},
'//todo/fixtures/todos.json');
$.fixture({
type: 'post',
url: '/services/todos.json'
},
function(settings){
return {id:Math.random(),
name: settings.data.name}
});
})
Notice: We used steal's ignoreoption to prevent loading the fixture plugin in production.
Finally, we steal todo/fixtures/fixtures.js in the app file (todo/todo.js) like:
steal({path: '//todo/fixtures/fixtures.js',ignore: true});
//start of your app's steals
steal( ... )
We typically keep it a one liner so it's easy to comment out.
Switching Between Sets of Fixtures
If you are using fixtures for testing, you often want to use differentsets of fixtures. You can add something like the following to your fixtures.jsfile:
if( /fixtureSet1/.test(window.location.search) ){
$.fixture("/foo","//foo/fixtures/foo1.json');
} else if(/fixtureSet2/.test(window.location.search)){
$.fixture("/foo","//foo/fixtures/foo1.json');
} else {
// default fixtures (maybe no fixtures)
}
jQuery.fixture.make function
Used to make fixtures for findAll / findOne style requests.
//makes a nested list of messages
$.fixture.make(["messages","message"],1000, function(i, messages){
return {
subject: "This is message "+i,
body: "Here is some text for this message",
date: Math.floor( newDate().getTime() ),
parentId : i < 100 ? null : Math.floor(Math.random()*i)
}
})
//uses the message fixture to return messages limited byoffset, limit, order, etc.
$.ajax({
url: "messages",
data:{
offset: 100,
limit: 50,
order: ["date ASC"],
parentId: 5},
},
fixture: "-messages",
success: function( messages ) { ... }
});
API
$.fixture.make(types, count,make, filter) -> undefined
types {Array|String}
An array of the fixture names or the singular fixture name. If an array,the first item is the plural fixture name (prefixed with -) and the second itemis the singular name. If a string, it's assumed to be the singular fixturename. Make will simply add s to the end of it for the plural name.
count {Number}
the number of items to create
make {Function}
a function that will return json data representing the object. The makefunction is called back with the id and the current array of items.
filter {Function}
(optional) a function used to further filter results. Used for to simulateserver params like searchText or startDate. The function should return true ifthe item passes the filter, false otherwise. For example:
function(item, settings){
if(settings.data.searchText){
var regex = new RegExp("^"+settings.data.searchText)
return regex.test(item.name);
}
}
returns {undefined}
jQuery.fixture.rand function
Creates random integers or random arrays of other arrays.
Examples
var rand = $.fixture.rand;
// get a random integer between 0 and 10 (inclusive)
rand(11);
// get a random number between -5 and 5 (inclusive)
rand(-5, 6);
// pick a random item from an array
rand(["j","m","v","c"],1)[0]
// pick a random number of items from an array
rand(["j","m","v","c"])
// pick 2 items from an array
rand(["j","m","v","c"],2)
// pick between 2 and 3 items at random
rand(["j","m","v","c"],2,3)
API
$.fixture.rand(arr, min, max)-> undefined
arr {Array|Number}
An array of items to select from. If a number is provided, a random numberis returned. If min and max are not provided, a random number of items areselected from this array.
min {optional:Number}
If only min is provided, min items are selected.
max {optional:Number}
If min and max are provided, a random number of items between min and max(inclusive) is selected.
returns {undefined}
jQuery.fn.closest function
plugin: jquery/dom/closest
Overwrites closest to allow open > selectors. This allows controlleractions such as:
">li click" : function( el, ev ){ ... }
API
$.fn.closest()
jQuery.fn.compare function
plugin: dom/compare
download: jQuery.fn.compare
test: qunit.html
Compares the position of two nodes and returns a bitmaskdetailing how they are positioned relative to each other.
$(
'#foo').compare($(
'#bar'))
//-> Number
You can expect it to return the same results as compareDocumentPosition.Parts of this documentation and source come from John Resig.
Demo
Demo
HTML
<div>
A
<div>
A.1
</div>
<div>
A.2
</div>
</div>
<div>
B
</div>
Source
steal(
'jquery/dom/compare').then(
function(){
var
placing =
'red'
//on click, set red and green and compare positions
$(
'div').click(
function(ev){
var
next = placing ==
'red'?
'green':
'red';
$(
'.'+placing).removeClass(placing)
$(
this).addClass(placing)
placing = next
ev.stopPropagation();
//don't worry about repeat queries for simple example
if
($(
'.green').length){
$(
"#result").text( $(
'.red').compare($(
'.green')) )
}
})
$(
function(){
if
(window.parent == window){
$(
'.hide').show()
}
})
})
API
$.fn.compare(element) -> Number
element {HTMLElement|jQuery}
an element or jQuery collection to compare against.
returns {Number}
A bitmap number representing how the elements arepositioned from each other.
If the code looks like:
$(
'#foo').compare($(
'#bar'))
//-> Number
Number is a bitmap with with the following values:
Bits | Number | Meaning |
000000 | 0 | Elements are identical. |
000001 | 1 | The nodes are in different documents (or one is outside of a document). |
000010 | 2 | #bar precedes #foo. |
000100 | 4 | #foo precedes #bar. |
001000 | 8 | #bar contains #foo. |
010000 | 16 | #foo contains #bar. |
Source
steal(
'jquery/dom/cur_styles').then(
function(){
$.fn.fastHeight =
function(){
var
sum =
this[
0] &&
this[
0].offsetHeight;
$.each(
this.curStyles(
"borderTopWidth"
,
"borderBottomWidth"
,
"paddingTop"
,
"paddingBottom"
),
function(name, val){
sum -= parseInt(val) ||
0;
});
return
sum;
}
vartest =
function(func){
var
start =
newDate(),
content = $(
"#content");
for
(
vari =
0; i <
2000; i++){
content[func]()
}
return
(
newDate() - start );
};
$(
"#content").click(
function(){
var
height = test(
"height"),
fastheight = test(
"fastHeight");
$(
"#content").html(
"jQuery's height: <b>"+
height+
"</b>ms<br/>fastHeight: <b>"
+
fastheight+
"</b>ms"
)
});
});
API
$.fn.curStyles(style) -> Object
style {String}
pass style names as arguments
returns {Object}
an object of style:value pairs
HTML
<form id="fp" action="">
<label>
People Count
</label><br>
<input name="talk[peopleCount]"><br>
<label>
Audience Rating
</label><br>
<select name="talk[audienceRating]">
<option value="3">
3
</option>
<option value="2">
2
</option>
<option value="1">
1
</option>
</select><br>
<label>
Time Left
</label><br>
<input name="talk[timeLeft]" value="1" type="radio">
1 min
<br>
<input name="talk[timeLeft]" value="5" type="radio">
5 min
<br>
<input name="talk[timeLeft]" value="10" type="radio">
10 min
<br>
</form>
Source
steal(
'jquery/dom/form_params',
'jquery/lang/json').then(
function(){
// updates the JSON text
varupdate =
function(){
// get form data
var
json = $(
'#fp').formParams(),
//convert it to JSON
jsonString = $.toJSON( json );
// show JSON
$(
"#result").text( jsonString )
}
// listen for changes and update
$(
'#fp').change(update);
// show json right away
update();
})
API
$.fn.formParams(params, convert) -> Object
params {optional:Object}
If an object is passed, the form will be repopulated withthe values of the object based on the name of the inputs within the form
convert {optional:Boolean} defaults to false
True if strings that look like numbers and booleans shouldbe converted and if empty string should not be added to the result. Defaults tofalse.
returns {Object}
An object of name-value pairs.
jQuery.fn.selection function
tags: beta
Gets or sets the current text selection.
Getting
Gets the current selection in the context of an element.For example:
$(
'textarea').selection()
// -> { .... }
returns an object with:
- start - The number of characters from the start of the element to the start of the selection.
- end - The number of characters from the start of the element to the end of the selection.
- range - A $.Range that represents the current selection.
This lets you get the selected text in a textarea like:
vartextarea = $(
'textarea')
selection = textarea.selection(),
selected = textarea.val().substr(selection.start, selection.end);
alert(
'You selected '+selected+
'.');
Selection works with all elements. If you want to getselection information of the document:
$(document.body).selection();
Setting
By providing a start and end offset, you can select textwithin a given element.
$(
'#rte').selection(
30,
40)
Demo
This demo shows setting the selection in various elements
Demo
HTML
<tbody><tr>
<td>
<a href="javascript://" id="textarea">
Select Textarea
</a></td>
<td><textarea id="">
012
456
</textarea></td>
</tr>
<tr>
<td><a href="javascript://" id="input">
Select Input
</a></td>
<td><input text="text" value="0123456789"></td>
</tr>
<tr>
<td><a href="javascript://" id="p">
Select Within One Element
</a></td>
<td><p id="1">
0123456789
</p></td>
</tr>
<tr>
<td><a href="javascript://" id="multi">
Select Across Multiple Elements
</a></td>
<td><div id="2">
012
<div>3
<span>4
</span>5
</div></div></td>
</tr>
</tbody>
Source
steal(
'jquery/dom/selection',
function(){
$(
'#textarea').click(
function(){
$(
'textarea').selection(
1,
5);
})
$(
'#input').click(
function(){
$(
'input').selection(
1,
5);
})
$(
'#p').click(
function(){
$(
'#1').selection(
1,
5);
})
$(
'#multi').click(
function(){
$(
'#2').selection(
1,
5);
})
});
API
$.fn.selection(start, end) -> Object|jQuery
start {optional:Number}
Start of the range
end {optional:Number}
End of the range
returns {Object|jQuery}
returns the selection information or the jQuery collection forchaining.
jQuery.fn.within function
plugin: jquery/dom/within
Returns the elements are within the position.
// get all elements that touch 200x200.
$('*').within(200, 200);
API
$.fn.within(left, top,useOffsetCache) -> jQuery
left {Number}
the position from the left of the page
top {Number}
the position from the top of the page
useOffsetCache {optional:Boolean}
cache the dimensions and offset of the elements.
returns {jQuery}
a jQuery collection of elements whos area overlaps the element position.
jQuery.fn.withinBox function
returns if elements are within the box
API
$.fn.withinBox(left, top, width,height, cache) -> undefined
left {Object}
top {Object}
width {Object}
height {Object}
cache {Object}
returns {undefined}
jQuery.Range class
tags: alpha
Provides text range helpers for creating, moving, and comparing rangescross browser.
Examples
// Get the current range
var range = $.Range.current()
// move the end of the range 2 characters right
range.end("+2")
// get the startOffset of the range and the container
range.start() //-> { offset: 2, container: HTMLELement }
//get the most common ancestor element
var parent = range.parent()
//select the parent
var range2 = new $.Range(parent)
Constructor
Returns a jQuery range object.
new $.Range(range) -> jquery.range
range {optional:TextRange|HTMLElement|Point}
An object specifiying a range. Depending on the object, the selected textwill be different. $.Range supports the following types
- undefined or null - returns a range with nothing selected
- HTMLElement - returns a range with the node's text selected
- Point - returns a range at the point on the screen. The point can be specified like:
· //clientcoordinates
· {clientX: 200, clientY: 300}
·
·
· //page coordinates
· {pageX: 200, pageY: 300}
· {top: 200, left: 300}
- TextRange a raw text range object.
returns {jquery.range}
jQuery.Range.prototype.clone function
Clones the range and returns a new $.Range object.
API
range.clone() -> jQuery.Range
returns {jQuery.Range}
returns the range as a $.Range.
jQuery.Range.prototype.collapse function
Collapses a range
$('#foo').range().collapse()
API
range.collapse(toStart) ->jQuery.Range
toStart {optional:Boolean}
true if to the start of the range, false if to the end. Defaults to false.
returns {jQuery.Range}
returns the range for chaining.
jQuery.Range.prototype.compare function
Compares one range to another range.
Example
// compare the highlight element's start position
// to the start of the current range
$('#highlight')
.range()
.compare('START_TO_START', $.Range.current())
API
range.compare(type, compareRange)-> Number
type {Object}
Specifies the boundry of the range and the compareRange tocompare.
- START_TO_START - the start of the range and the start of compareRange
- START_TO_END - the start of the range and the end of compareRange
- END_TO_END - the end of the range and the end of compareRange
- END_TO_START - the end of the range and the start of compareRange
compareRange {$.Range}
The other range to compare against.
returns {Number}
a number indicating if the range boundary is before, after, or equal to compareRange's boundary where:
- -1 - the range boundary comes before the compareRange boundary
- 0 - the boundaries are equal
- 1 - the range boundary comes after the compareRange boundary
· jQuery.Range.prototype.end function
· Source
· Sets or gets theend of the range.
It takes similar options as jQuery.Range.prototype.start.
· API
· range.end(set) -> undefined
· set {optional:Object}
· returns {undefined}
jQuery.Range.prototype.move function
Move the endpoints of a range relative to another range.
// Move the current selection's end to the
// end of the #highlight element
$.Range.current().move('END_TO_END',
$('#highlight').range() )
API
range.move(type, referenceRange)-> jQuery.Range
type {String}
a string indicating the ranges boundary point to move to whichreferenceRange boundary point where:
- START_TO_START - the start of the range moves to the start of referenceRange
- START_TO_END - the start of the range move to the end of referenceRange
- END_TO_END - the end of the range moves to the end of referenceRange
- END_TO_START - the end of the range moves to the start of referenceRange
referenceRange {jQuery.Range}
returns {jQuery.Range}
the original range for chaining
jQuery.Range.prototype.overlaps function
Return true if any portion of these two ranges overlap.
var foo = document.getElementById('foo');
$.Range(foo.childNodes[0]).compare(foo.childNodes[1]) //-> false
API
range.overlaps(elRange) ->Boolean
elRange {jQuery.Range}
returns {Boolean}
true if part of the ranges overlap, false if otherwise.
jQuery.Range.prototype.parent function
Returns the most common ancestor element of the endpoints in the range.This will return text elements if the range is within a text element.
API
range.parent() -> HTMLNode
returns {HTMLNode}
the TextNode or HTMLElement that fully contains the range
jQuery.Range.prototype.rect function
Returns the bounding rectangle of this range.
API
range.rect(from) ->TextRectangle
from {optional:String}
- where the coordinates should be positioned from. By default, coordinates are given from the client viewport. But if 'page' is given, they are provided relative to the page.
returns {TextRectangle}
- The client rects.
· jQuery.Range.prototype.rects function
· Source
· Returns clientrects
· API
· range.rects(from) -> undefined
· from {optional:String}
· how the rectscoordinates should be given (viewport or page). Provide 'page' for rectcoordinates from the page.
· returns {undefined}
jQuery.Range.prototype.start function
Gets or sets the start of the range.
If a value is not provided, start returns the range's starting containerand offset like:
$('#foo').range().start()//-> {container: fooElement, offset: 0 }
If a set value is provided, it can set the range. The start of the rangeis set differently depending on the type of set value:
- Object - an object with the new starting container and offset is provided like
· $.Range().start({container: $('#foo')[0], offset: 20})
- Number - the new offset value. The container is kept the same.
- String - adjusts the offset by converting the string offset to a number and adding it to the current offset. For example, the following moves the offset forward four characters:
· $('#foo').range().start("+4")
API
range.start(set) ->jQuery.Range|Object
set {optional:Object|String|Number}
a set value if setting the start of the range or nothing if reading it.
returns {jQuery.Range|Object}
if setting the start, the range is returned for chaining, otherwise, thestart offset and container are returned.
jQuery.Range.prototype.toString function
Returns the text of the range.
currentText =$.Range.current().toString()
API
range.toString() -> String
returns {String}
the text of the range
jQuery.Range.static.current function
Gets the current range.
$.Range.current() //-> jquery.range
API
$.Range.current(el) ->jQuery.Range
el {optional:HTMLElement}
an optional element used to get selection for a given window.
returns {jQuery.Range}
a jQuery.Range wrapped range.
jQuery.route class
inherits: jQuery.Observe
tags: 3.2
plugin: jquery/dom/route
jQuery.route helps manage browser history (and clientstate) by synchronizing the window.location.hash with an jQuery.Observe.
Background Information
To support the browser's back button and bookmarking in anAjax application, most applications use the window.location.hash
.By changing the hash (via a link or JavaScript), one is able to add to thebrowser's history without changing the page. The eventallows you to listen to when the hash is changed.
Combined, this provides the basics needed to create historyenabled Ajax websites. However, jQuery.Route addresses several other needs suchas:
- Pretty Routes
- Keeping routes independent of application code
- Listening to specific parts of the history changing
- Setup / Teardown of widgets.
How it works
$.route
is a $.Observethat represents the window.location.hash
as an object. Forexample, if the hash looks like:
#!type=videos&id=
5
the data in $.route
would look like:
{ type:
'videos', id:
5}
$.route keeps the state of the hash in-sync with the datain $.route.
$.Observe
$.route is a $.Observe.Understanding $.Observe is essential for using $.route correctly.
You can listen to changes in an Observe with bind anddelegate and change $.route's properties with attr and attrs.
Listening to changes in an Observable
Listen to changes in history by bindingto changes in $.route
like:
$.route.bind(
'change',
function(ev, attr, how, newVal, oldVal) {
})
- attr - the name of the changed attribute
- how - the type of Observe change event (add, set or remove)
- newVal/oldVal - the new and old values of the attribute
You can also listen to specific changes with delegate:
$.route.delegate(
'id',
'change',
function(){... })
Observe lets you listen to the following events:
- change - any change to the object
- add - a property is added
- set - a property value is added or changed
- remove - a property is removed
Listening for add
is useful for widget setupbehavior, remove
is useful for teardown.
Updating an observable
Create changes in the route data like:
$.route.attr(
'type',
'images');
Or change multiple properties at once with attrs:
$.route.attr({type:
'pages', id:
5},
true)
When you make changes to $.route, they will automaticallychange the hash
.
Creating a Route
Use $.route(url, defaults)
to create a route.A route is a mapping from a url to an object (that is the $.route's state).
If no routes are added, or no route is matched, $.route'sdata is updated with the deparamedhash.
location.hash =
"#!type=videos";
// $.route -> {type : "videos"}
Once routes are added and the hash changes, $.route looksfor matching routes and uses them to update $.route's data.
$.route(
"content/:type");
location.hash =
"#!content/images";
// $.route -> {type : "images"}
Default values can also be added:
$.route(
"content/:type",{type:
"videos"});
location.hash =
"#!content/"
// $.route -> {type : "videos"}
Delay setting $.route
By default, $.route
sets its initial data ondocument ready. Sometimes, you want to wait to set this data. To wait, call:
$.route.ready(
false);
and when ready, call:
$.route.ready(
true);
Changing the route.
Typically, you never want to set location.hash
directly. Instead, you can change properties on $.route
like:
$.route.attr(
'type',
'videos')
This will automatically look up the appropriate route andupdate the hash.
Often, you want to create links. $.route
provides the jQuery.route.linkand jQuery.route.urlhelpers to make this easy:
$.route.link(
"Videos", {type:
'videos'})
API
$.route(url, defaults) -> jQuery.route
url {String}
the fragment identifier to match.
defaults {optional:Object}
an object of default values
returns {jQuery.route}
jQuery.route.current function
Returns true if the options represent the current page.
API
$.route.current(options) ->Boolean
options {Object}
returns {Boolean}
jQuery.route.deparam function
Populate the JS data object from a given URL.
API
$.route.deparam(url) ->undefined
url {Object}
returns {undefined}
jQuery.route.link function
Returns a link
API
$.route.link(name, options,props, merge) -> undefined
name {Object}
The text of the link.
options {Object}
The route options (variables)
props {Object}
Properties of the <a> other than href.
merge {Boolean}
true if the options should be merged with the current options
returns {undefined}
jQuery.route.param function
Parameterizes the raw JS object representation provided in data. If aroute matching the provided data is found that URL is built from the data. Anyremaining data is added at the end of the URL as & separated key/valueparameters.
API
$.route.param(data) -> String
data {Object}
returns {String}
The route URL and & separated parameters.
jQuery.route.ready function
Indicates that all routes have been added and sets $.route.data based uponthe routes and the current hash.
By default, ready is fired on jQuery's ready event. Sometimes you mightwant it to happen sooner or earlier. To do this call
$.route.ready(false); //prevents firing by the readyevent
$.route.ready(true); // fire the first route change
API
$.route.ready(val, start) ->undefined
val {}
start {optional:Boolean}
jQuery.route.url function
Returns a url from the options
API
$.route.url(options, merge) ->String
options {Object}
merge {Boolean}
true if the options should be merged with the current options
returns {String}