Native extensions

We've added our own functionality to Mootools to suit our own needs. In the native group we have changes to Element, String, and Window that you may or may not find useful. Note that many of our other classes depend on these extensions. We try to note these dependencies in the documentation for each file.

All my work here is based off of stuff done by Nicholas Barthelemy and Harald Kirshner.

date.js

The native Date object in javascript leaves a lot to be desired, and while Mootools 1.2 doesn't extend it, the content of this library that does will likely make its way into Mootools in the near future.

Here are the methods that are available in date.js; be sure to check out date.extras.js below, which adds a bit more functionality.

Date.clone

Clones a date returning a copy of it:

var now = new Date();
var nowCopy = now.clone();
console.log(now);
console.log(nowCopy); //they are the same
execute this code

Date.increment

Increments a value in the date. Optional values are "year", "month", "week", "day", "hour", "minute", "second", and "ms".

var now = new Date();
var oneSecondLater = now.clone().increment('second');
var thirtySecondsLater = now.clone().increment('second', 30);
console.log(now);
console.log(oneSecondLater);
console.log(thirtySecondsLater);
execute this code
var now = new Date();
var nextMonth = now.clone().increment('month');
var twoYears = now.clone().increment('year', 2);
console.log(now);
console.log(nextMonth);
console.log(twoYears);
execute this code

The default value is a day:

var today = new Date();
var tomorrow = today.clone().increment(); 
console.log(today);
console.log(tomorrow);
//with no arguments, increment will move forward a day
execute this code

Note: this method will account for the various numbers of days in each month and for leap years.

Date.decrement

Same as Date.increment except moving time backwards.

var now = new Date();
var oneSecondBefore = now.clone().decrement('second');
var thirtySecondsBefore = now.clone().decrement('second', 30);
console.log(now);
console.log(oneSecondBefore);
console.log(thirtySecondsBefore);
execute this code
var now = new Date();
var lastMonth = now.clone().decrement('month');
var twoYearsAgo = now.clone().decrement('year', 2);
console.log(now);
console.log(lastMonth);
console.log(twoYearsAgo);
execute this code

The default value is a day:

var today = new Date();
var yesterday = today.clone().decrement(); 
console.log(today);
console.log(yesterday);
//with no arguments, decrement will move backwards a day
execute this code

Date.isLeapYear

Returns true or false.

new Date().isLeapYear(); //true if this is a leap year
execute this code

Date.clearTime

Sets all the time values to zero (12am exactly).

new Date().clearTime();
execute this code

Date.diff

Compares two dates. If the date passed as an argument is in the future, the value is positive, else negative.

diff takes as its second argument an optional resolution value. Resolution can be "year", "month", "week", "day", "hour", "minute", "second", and "ms". The default is "day".

var now = new Date();
var tomorrow = now.clone().increment();
console.log(now.diff(tomorrow)); /* 1; default resolution is "day" */
console.log(tomorrow.diff(now)); /* -1 */
execute this code
var now = new Date();
var yearAndAMonthAgo = now.clone().decrement('month', 13);
console.log(now.diff(yearAndAMonthAgo)); /* around -390 days, depending on month */
console.log(now.diff(yearAndAMonthAgo, 'year')); /* 1 */
console.log(now.diff(yearAndAMonthAgo, 'month')); /* 13 */
execute this code

Note: All values are rounded down (so if you compare two dates that are 26 hours apart with a resolution of "day", you'll get one). When comparing years you'll get the numerical difference between the years, meaning that if you compare Jan 08 to Dec 09, which is 23 months, you'll still only get 1 as a result because 09 - 08 is 1.

Date.getTimezone

Returns the time zone string; e.g. "GMT".

new Date().getTimezone();
execute this code

Date.getGMTOffset

Returns the offset of the time zone from GMT; e.g. "-0800".

new Date().getGMTOffset();
execute this code

Date.parse

Parses a string, date, or number to a date using predefined regular expressions. date.js comes with only two of these defined (MM/DD/YYYY, where the / can be a period or a dash, and the other parser is exactly like the first except it adds time parsing: MM/DD/YYYY HH:MM[pm|am]). date.extras.js provides many more of these. See below for how to write your own. If the value fails to parse, returns Date with a value of "Invalid Date" (just as if you tried new Date('foo')).

Date.parse("12/31/1999");
execute this code
Date.parse("12/31/1999 11:59pm");
execute this code
Date.parse("foo"); //Invalid Date
execute this code
Date.parse(new Date()); //just returns the value of new Date()
execute this code
var now = new Date();
Date.parse(now); //just returns now
execute this code

Note: Date.parse can be executed as a static method on the Date namespace (as above) and it will return a new Date instance with the parsed date to you. Alternatively, if you execute Date.parse on an instance of a date, you'll alter that instance to the parsed value:

var partyTime = new Date();
partyTime.parse("12.31.1999 11:59pm");
console.log(partyTime);
 
/* same as 
var partyTime = new Date().parse("12.31.1999 11:59pm");
or
var partyTime = Date.parse("12.31.1999 11:59pm");
*/
execute this code

Writing your own parsers

You can write your own regular expressions to parse formats you wish to support. To do this, you need to push your parser into the array of parsers that come with date.js. Here's what it looks like:

//this pattern looks for a string beginning with 
//"tod" or "Tod" and assumes that the user means
//"today", and returns the current date
Date.$parsePatterns.extend([{
  re: /^tod/i,
  handler: function() {
    return new Date();
  }
},{
//this one looks for "tom" or "Tom"
//and assumes the user means tomorrow
  re: /^tom/i,
  handler: function() {
    return new Date().increment();
  }
},{
  //"12.31.08", "12-31-08", "12/31/08", "12.31.2008",
  //"12-31-2008", "12/31/2008"
  re: /^(\d{1,2})[\.\-\/](\d{1,2})[\.\-\/](\d{2,4})$/,
  handler: function(bits){
    var d = new Date();
    d.setYear(bits[3]);
    d.setMonth(bits[1].toInt() - 1, bits[2].toInt());
    return Date.fixY2K(d);
  }
}]);

For each parser you add, you define an object with re and handler. re is the regular expression applied to the date value being parsed. handler receives as its arguments the result of that regular expression and should create a date and return it.

Date.format

Yeah! A date formatter for javascript! It's pretty standard stuff, though it's not as full featured as other languages.

<ul>

<li><b>a</b> - short day ("Mon", "Tue")</li>
<li><b>A</b> - full day ("Monday")</li>
<li><b>b</b> - short month ("Jan", "Feb")</li>
<li><b>B</b> - full month ("Janurary")</li>
<li><b>c</b> - the full date to string ("Mon Dec 10 2007 14:35:42 GMT-0800 (Pacific Standard Time)"; same as .toString() method.</li>
<li><b>d</b> - the date to two digits (01, 05, etc)</li>
<li><b>H</b> - the hour to two digits in military time (24 hr mode) (01, 11, 14, etc)</li>
<li><b>I</b> - the hour in 12 hour time (01, 11, 2, etc)</li>
<li><b>j</b> - the day of the year to three digits (001 is Jan 1st)</li>
<li><b>m</b> - the numerical month to two digits (01 is Jan, 12 is Dec)</li>
<li><b>M</b> - the minuts to two digits (01, 40, 59)</li>
<li><b>p</b> - 'AM' or 'PM'</li>
<li><b>S</b> - the seconds to two digits (01, 40, 59)</li>
<li><b>U</b> - the week to two digits (01 is the week of Jan 1, 52 is the week of Dec 31)</li>
<li><b>W</b> - not yet supported</li>
<li><b>w</b> - the numerical day of the week, one digit (0 is Sunday, 1 is Monday)</li>
<li><b>x</b> - returns the format %m/%d/%Y (12/10/2007)</li>
<li><b>X</b> - returns %I:%M%p (02:45PM)</li>
<li><b>y</b> - the short year (to digits; "07")</li>
<li><b>Y</b> - the four digit year</li>
<li><b>T</b> - the GMT offset ("-0800")</li>
<li><b>Z</b> - the time zone ("GMT")</li>
<li><b>%</b> - returns % (example: %y%% = 07%)</li>

</ul>

There are some shortcuts, too (these don't use the percent signs; see example below): <ul>

<li><b>db</b> - "%Y-%m-%d %H:%M:%S"</li>
<li><b>compact</b> - "%Y%m%dT%H%M%S"</li>
<li><b>iso8601</b> - "%Y-%m-%dT%H:%M:%S%T"</li>
<li><b>rfc822</b> - "%a, %d %b %Y %H:%M:%S %Z"</li>
<li><b>short</b> - "%d %b %H:%M"</li>
<li><b>long</b> - "%B %d, %Y %H:%M"</li>

</ul>

Example:

var today = new Date();
console.log(today.format("%x")); /* 12/31/1999 */
console.log(today.format("%x %X")); /* 12/31/1999 11:59pm */
console.log(today.format("db")); /* 1999-12-31 23:59:59 */
execute this code

Note: it's a good idea to write parsers for any inputs that you output data in a given format. If you show the user a date format on your page, any inputs on that page that accept dates should be able to parse that format.

Date.setAMPM

This lets you set the time of day to before or after noon.

var today = new Date().clearTime(); /* midnight */
today.setAMPM("pm"); /* noon! */
console.log(today);
execute this code

date.extras.js

date.extras.js just adds some more functionality to the date.js extensions to the Date native. They are split up so that if you have something simple to implement that you want to keep the code small (like our Date Picker, you can only include the basic date.js.

Here's what you get with date.extras.js:

Date.timeAgoInWords

var example = new Date();
console.log(example.timeAgoInWords()); /* "less than a minute ago" */
example.decrement('hour');
console.log(example.timeAgoInWords()); /* "about an hour ago" */
execute this code

Date.getOrdinal

Returns the ordinal for the day ("th", "nd", etc).

new Date().getOrdinal();
execute this code

Date.getDayOfYear

Returns the day of the year (so Dec 31 is 365 unless it's leap year).

Date.parse("12.31.1999").getDayOfYear(); //365
execute this code

Date.getLastDayOfMonth

So for Dec you'd get 31.

var dec = new Date();
dec.setMonth(11);
dec.getLastDayOfMonth(); //31
execute this code

Date.getWeek

Returns what week you're in of the year, so Dec 31 will return 52.

Date.parse("12.31.1999").getWeek(); //52
execute this code

Additional Parsers

The biggest thing you get with date.extras.js is a whole bunch of parsers. date.js just includes the basics ("12/31/1999" and "12/31/1999 11:59pm"), while date.extras.js includes another ten.

Date.parse('1999-12-31 23:59:59')
execute this code
Date.parse('1999-12-31T23:59:59+0200')
execute this code
Date.parse('today')
execute this code
Date.parse('tomorrow')
execute this code
Date.parse('yesterday')
execute this code
Date.parse('next monday')
execute this code
Date.parse('1st')
execute this code
Date.parse('14th October')
execute this code
Date.parse('24th May, 2007')
execute this code
Date.parse('May 3rd 2006')
execute this code

element.shortcuts.js

Mootools has a lot of love for DOM elements, but there were a few functions we included that aren't in Mootools. Some of these are here because we needed compatibility with Prototype.lite (a thin version of Prototype.js that came with Moo.fx, the predecessor to Mootools).

Others are shortcuts for things that we end up typing often. svn

Element.isVisible

Returns true if display != none. (This used to be Element.visible, which is still there but is deprecated).

$('fxTarget').isVisible(); //true
execute this code

Element.toggle

Toggles between display = block and display = none.

$('fxTarget').toggle(); //hides
$('fxTarget').toggle.delay(1000, $('fxTarget')); //shows again
execute this code

Element.hide(), .show

Element.hide() will set an element's display to 'none'.

Element.show() will set it back to what it was before you hid it (inline, block, etc.) or, if you didn't call .hide() on it previously it defaults to 'block'. You can specify what to set the display to by passing that in (Element.show('block') or Element.show('inline'));

These are just shortcuts for Element.setStyle('display', 'block').

$('fxTarget').hide(); /*hides*/
$('fxTarget').show.delay(1000, $('fxTarget')); /*shows again*/
execute this code

Element.tidy

Removes MS-Word style non-ASCI characters from an input. See also String.tidy.

$('tidyExample').tidy();
//input value is now "'...'"
execute this code

Element.findParent

Finds first element that contains this element within a collection. I.e. you pass it a bunch of items that you think are parents and it returns the first one that is.

$('findParentExample').findParent($$('div')); 
//find the first div that contains our example
execute this code
$('findParentExample').findParent($$('#leftCol, #rightCol')); 
//which column is it in?
execute this code

element.dimensions.js

Mootools has several tools for figuring out the sizes of things, but there were some things we wanted to do that needed a bit more code. svn

Element.getDimensions

Element.getDimensions() returns an object that has the width and the height of an element ({width: 10, height: 20}) for example).

Mootools has it's own Element.getSize() which returns an object with scroll, size, and scrollsize values, as well as its getStyle (.getStyle('width') for example), and its .getPosition which returns width, height, left, right, top, and bottom values.

So why do we have our function? It does one thing that Mootools many methods of getting width and height does not: it will return these values for elements that are hidden (display: none, specifically).

It does this by cloning the element off screen and showing it, then removing the clone. If you try and ascertain the width and height of an element that is not displayed, you'll get a zero back for each. So getDimensions is something we use when the element isn't displayed.

/*first, let's print to the console 
  the size before we hide it*/
console.log('target visible, size: %o', $('fxTarget').getSize().size);
 
$('fxTarget').setStyle('display', 'none');
/*let's try and get size for it now that it's hidden*/
console.log('target hidden, size: %o', $('fxTarget').getSize().size);
/*ok, that didn't work, so let's try getDimensions*/
console.log('target hidden, getDimensions: %o', $('fxTarget').getDimensions());
$('fxTarget').setStyle('display','block');
 
/* should print the following in the console:
target visible, size: Object x=102 y=102
target hidden, size: Object x=0 y=0
target hidden, getDimensions: Object width=102 height=102 x=102 y=102 */
execute this code

Note that it returns .width and .height in addition to .x and .y. The values are the same (width == x, height == y) so you can use either.

If you want, use can use Element.getComputedSize by passing in the option computeSize as true. This will use getDimensions method of getting values for hidden objects but return to you the object that getComputedSize generates.

$('fxTarget').getDimensions({computeSize: true});
execute this code

Element.getComputedSize

This might get added into Mootools, but until then I'm including it here. This function allows you to get the calculated width of an element as well as the values for padding and border (or optionally additional css properties) that are used in computing that size.

The object you get back looks like this:

{
  padding-top:0,
  border-top-width:1,
  padding-bottom:0,
  border-bottom-width:1,
  padding-left:0,
  border-left-width:1,
  padding-right:0,
  border-right-width:1,
  width:100,
  height:100,
  totalHeight:102,
  computedTop:1,
  computedBottom:1,
  totalWidth:102,
  computedLeft:1,
  computedRight:1
}

This is useful when you want to position something or figure out its dimensions including various css properties. It's used in Element.setPosition() and also can be used in Element.getDimensions.

$('fxTarget').getComputedSize();
/*returns
{
  padding-top:0,
  border-top-width:1,
  padding-bottom:0,
  border-bottom-width:1,
  padding-left:0,
  border-left-width:1,
  padding-right:0,
  border-right-width:1,
  width:100,
  height:100,
  totalHeight:102,
  computedTop:1,
  computedBottom:1,
  totalWidth:102,
  computedLeft:1,
  computedRight:1
}*/
execute this code
$('fxTarget').getComputedSize({
  /*limit our calculations to height, top, and bottom */
  mode: 'vertical' 
});
/*returns{
  padding-top  :0,
  border-top-width  :1,
  padding-bottom  :0,
  border-bottom-width  :1,
  height  :100,
  totalHeight  :102,
  computedTop  :1,
  computedBottom  :1
}*/
execute this code
$('fxTarget').setStyles({
  margin: '5px',
  padding: '7px'
}).getComputedSize({
  /*include margin in addition to the default border and padding */
  styles: ['border','padding','margin'] 
});
/*returns{
  border-top-width  :1,
  padding-top  :7,
  margin-top  :5,
  border-bottom-width  :1,
  padding-bottom  :7,
  margin-bottom  :5,
  border-left-width  :1,
  padding-left  :7,
  margin-left  :5,
  border-right-width  :1,
  padding-right  :7,
  margin-right  :5,
  width  :100,
  height  :100,
  totalHeight  :126,
  computedTop  :13,
  computedBottom  :13,
  totalWidth  :126,
  computedLeft  :13,
  computedRight  :13
}*/
execute this code

element.position.js

This script is very specifically for positioning elements in the window relative to something else. svn

Element.setPosition

.setPosition lets you position an element relative to another one. So if you have an element and you want it next to or on top of another, this extension helps you handle that positioning.

The element you are positioning has to be positioned absolutely, and if you don't specify an element that you're going to make it relevant to, it'll use the document window. Here are some examples:





The default is to position is centered relative to the target:

$('setPositionTarget').setPosition(); //centered in the window
execute this code
$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget') /*centered over a target*/
});
execute this code

You can also specify a location relative to the relativeTo object:

$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: 'upperRight'
});
execute this code

specifying position

There are two ways to specify the position: strings and objects. The strings are combinations of "left", "right", and "center" with "top" (or "upper"), "bottom", and "center". These are case insensitive. These translate to:

  • upperLeft, topLeft (same thing) - or upperleft, leftupper, LEFTUPPER whatever.
  • bottomLeft
  • centerLeft
  • upperRight, topRight (same thing)
  • bottomRight
  • centerRight
  • centerTop
  • centerBottom
  • center

Alternatively, you can be a little more expicit by using an object with x and y values. Acceptable values for the x axis are "left", "right", and "center", and for y you can use "top", "bottom" and "center".

  • {x: 'left', y: 'top'} – same as "upperLeft" or "topLeft"
  • {x: 'left', y: 'bottom'} – same as "bottomLeft"
  • etc.

Using these options you can specify a position for each corner of the relativeTo object as well as the points between those corners (center left, top, right, bottom and the center of the entire object).

$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: 'upperLeft'
});
execute this code

The above example is the same as this one:

$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: {
		x: 'left',
		y: 'top'
	}
});
execute this code
$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: 'bottomLeft'
});
execute this code

Same as:

$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: {
		x: 'left',
		y: 'bottom'
	}
});
execute this code
$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: 'bottomCenter'
});
execute this code

Same as:

$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: {
		x: 'center',
		y: 'bottom'
	}
});
execute this code
$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: 'leftCenter'
});
execute this code

Same as:

$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: {
		x: 'left',
		y: 'center'
	}
});
execute this code

There's also an offset option:

$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: 'upperRight',
  offset: {x: 20, y: 20} /*move over and down*/
});
execute this code

Additionally, you can specify an edge option that allows you to align the specified edge of the element relative to the relativeTo element's edge specified in the position argument. This lets you, for instance, position the upper right corner of the element to the bottom left corner of the relativeTo element.

Examples:

/* upperRight of element aligned to upperRight of relativeTo element*/
$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: 'upperRight',
  edge: 'upperRight'
});
execute this code
/* bottomLeft of element aligned to bottomLeft of relativeTo element*/
$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: 'bottomLeft',
  edge: 'bottomLeft'
});
execute this code
/* center of element aligned to upperRight of relativeTo element*/
$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: 'upperRight',
  edge: 'center'
});
execute this code
/* center of element aligned to upperRight of relativeTo element*/
$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: 'centerRight',
  edge: 'center'
});
execute this code
/* center of element aligned to upperRight of relativeTo element*/
$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: 'centerBottom',
  edge: 'centerTop'
});
execute this code

Again, you can use objects to describe these positions:

/* center of element aligned to upperRight of relativeTo element*/
$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: {
		x: 'right',
		y: 'top'
	},
  edge: {
		x: 'left',
		y: 'center'
	}
});
execute this code

Ignoring Margins

It's possible to position an element and ignore the margins around it. Here's an example; the first shows you what it looks like with the margins applied but not ignored, then 2 seconds delayed is the method to have it ignore the margin.

$('setPositionTarget').setStyles({
    'margin-right': 30,
    'margin-top': 50,
    'margin-left': 20,
    'margin-bottom': 10
});
$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: {
    x: 'left',
    y: 'top'
  },
  edge: {
    x: 'right',
    y: 'top'
  }
});
 
(function(){
	/*now ignore the margins*/
	$('setPositionTarget').setPosition({
	  relativeTo: $('fxTarget'),
	  ignoreMargins: true,
	  position: {
	    x: 'left',
	    y: 'top'
	  },
	  edge: {
	    x: 'left',
	    y: 'top'
	  }
	});
}).delay(2000);
 
 
/*put the margins back for other examples*/
(function(){
	$('setPositionTarget').setStyles({
	    'margin-right': 0,
	    'margin-top': 0,
	    'margin-left': 0,
	    'margin-bottom': 0
	});
}).delay(5000);
execute this code

returnPos

An additional option for .setPosition is returnPos.

returnPos will just return the x/y coordinates of where the element would move to, but not move it. This lets you use setPosition to get these coords without changing anything.

$('setPositionTarget').setPosition({
  relativeTo: $('fxTarget'),
  position: 'upperRight',
  offset: {x: 20, y: 20},
  returnPos: true
}); //returns something like {top: "123px", left: "234px"}
execute this code

smoothMove

You can also use Fx.SmoothMove to position an element. It works just like setPosition except it allows you to have the element transition to the location instead of just jump there.

element.forms.js

This script has helpers for managing text selection and manipulation in form elements. Eventually I expect more form functionality to get added, but for now, its all about the kind of stuff that wysiwyg editors need to insert html around selected text and that sort of thing.

NOTE Since these examples are all about selections and caret locations, I can't have code examples that you click to execute (because this will change the focus).

docs | svn

Element.getTextInRange

Returns the value of the text within a given range in the input.

text in range (click the input to execute):

Element.getSelectedText

Gets the text that is currently selected.

selected text (select some text to execute):

Element.getSelectedRange

Gets the range that is selected.

getSelectedRange: (select some text to execute)

Element.selectRange

Selects a range of text.

selectRange (click to execute; this example passes in an array [2,5]):

selectRange (click to execute; selectRange also will take two integers; this example passes in '2,5'):

Element.insertAtCursor

Insert text at the cursor location.

insertAtCursor (click anywhere to insert the example):

Element.insertAroundCursor

Wraps text with the given strings.

insertAroundCursor (select some text or click anywhere to insert "<" and ">" around the text):

element.pin.js

Element.pin affixes an element to its current location, setting its css position value to "fixed" so that the element will not move if you scroll the window. This works for draggable elements, too. Browsers that don't support position "fixed" get the element relocated on scroll, so it appears to behave the same (though it may be a little jittery - this is mostly just ie6).

docs|svn

$('fxTarget').pin()
execute this code

You can also easily unpin an element:

$('fxTarget').pin()
/*scroll around a little and in 4 secs it'll go back to being unpinned*/
$('fxTarget').unpin.delay(4000, $('fxTarget'));
execute this code

And you can toggle it:

$('fxTarget').pin()
$('fxTarget').togglepin.delay(1000, $('fxTarget'));
$('fxTarget').togglepin.delay(2000, $('fxTarget'));
$('fxTarget').togglepin.delay(3000, $('fxTarget'));
//etc.
execute this code

Seeing as this is only demonstrable if you can scroll, here's a bunch of white space.

string.cnet.js

Mootools extends Strings in its Native group of code. We've got a few more extensions of our own.

docs | string.cnet.js

stripTags

Removes all html tags from a string:

"<p>I\'m a <b>string</b> with a bunch of <i>tags</i></p>".stripTags();
//returns: I'm a string with a bunch of tags
execute this code

stripScripts

.stripScripts removes any script tags from your string.

('<p>This string contains a script tag.<scri'+'pt>alert("hi");</scri'+'pt></p>').stripScripts();
// that '+' in the script tag is just to keep it from evaluating when this page loads
//returns: <p>This string contains a script tag.</p>
execute this code

.evalScripts

.evalScripts evalutates any javascript in a script tag in a string. It will not insert into the dom a script with a src.

('<p>This string contains a script tag.<scri'+'pt>alert("hi");</scri'+'pt></p>').evalScripts();
// that '+' in the script tag is just to keep it from evaluating when this page loads
//executes: alert("hi");
execute this code

.replaceAll

Replaces all instances of a string within a string with your new value.

"I like cake, any cake.".replaceAll("cake", "cookies");
//returns "I like cookies, any cookies"
execute this code

You can pass in a 3rd argument for your preferred regExp options. Defaults to "ig" (ignore case, global replace).

.parseQuery

This takes a url query string and returns an object of name/value pairs to you.

"apple=red&lemon=yellow".parseQuery();
//returns: {apple: 'red', lemon:'yellow'}
execute this code

.tidy

Removes MS-Word style non-ASCI characters (curly quotes, elipse, etc). See also Element.tidy.

"“‘…’”".tidy();
//returns "'...'"
execute this code

window.cnet.js

Mootools comes with functions to get Window dimensions and a way to attach onDomReady functions. We've added a few more things that our developers needed.

docs | window.cnet.js

.getHost

Returns the fully qualified domain of the page. Will also return the host of a url passed to it.

window.getHost();
//returns "clientside.cnet.com"
execute this code
window.getHost('http://www.example.com/some/path.html');
//returns "www.example.com"
execute this code

.getQueryStringValue

Returns the value of a query string key if it's defined. There shouldn't be one defined looking at this page, so for the purposes of this example, click this link before you execute the code below (it'll reload the page with a query string): reload with a query string

window.getQueryStringValue('red');
//returns: apple
execute this code

You can pass in an optional second argument; a different url. This will return the query string value in that instead of the window location.

window.getQueryStringValue('this', 'http://www.example.com?this=that');
//returns: that
execute this code

.getQueryStringValues

This returns an object of all the query string values. It takes an optional url as its argument, but defaults to the window location. If you haven't already, reload with a query string

window.getQueryStringValues();
//returns {red: 'apple',yellow:'lemon',green:'lime'}
execute this code
window.getQueryStringValues('http://www.example.com?this=that');
//returns {this:'that'}
execute this code

.qs

window.qs is kind of a shortcut to window.getQueryStringValues() except that .qs is not a function it's the object itself. You can't pass a url to it, so it represents only the values in the window location.

window.qs;
//returns {red: 'apple',yellow:'lemon',green:'lime'}
execute this code

.getPort

Returns the port of the url as a string, if there is one.

window.getPort();
//returns: false
execute this code
window.getPort('http://www.example.com:8001/something.html');
//returns: 8001 (a string)
execute this code

window.popup

As I refactored CNET's javascript I kept coming across little functions like this:

f