midori
The module midori makes up the core of the midori JavaScript framework, and is used by all other modules. It provides mostly low-level CSS/DOM, event, cookie, form, array and string methods.
CSS / DOM
-
get(selectorText, startAt)Selects elements that match a CSS selector. Your browser may not natively support most CSS2 and CSS3 selectors, but midori does.Supported CSS selectors:
Basic: * #id element .class sel1,sel2,sel3,...Hierarchy: ancestor descendant, parent > childAttributes: [attr] [attr operator value] [attr1][attr2][attr3]...Child: :nth-child(index/even/odd/equation) :first-child :last-child :only-childWhen selecting a simple #id selector, just returns the element. So, you can start using it right away. For example:
midori.get('#page-title').className = 'title';Otherwise, returns an array of matched elements. You can use the apply() method to work on all the elements. Alternatively, you can access individual elements by using array indexes.
If you are going to simply change a property of each returned element, you can directly pass your code like this (check the table below for live results):
// Sets the class of all th elements to "header" midori.get('th').apply('className = "header"'); [Run] // Sets the color of all th elements to "green" // if their class is "header" midori.get('th.header').apply('style.color = "green"'); [Run] // Sets the background color of all the cells in even rows to // "yellow" in the "cities" table midori.get('#cities tr:nth-child(even) td').apply( [Run] 'style.backgroundColor = "yellow"');
Top 5 Cities by Population:# City Population
in millionsCountry 1. Mumbai 13.6 India 2. Karachi 12.1 Pakistan 3. Istanbul 11.3 Turkey 4. Delhi 11.3 India 5. Sao Paulo 10.8 Brazil
Otherwise, you can pass a function that takes a single parameter, and matching elements will be passed to your function one by one:
// Marks the cells whose values are 12 or bigger in the "cities" table midori.get('#cities td').apply(function (o) { [Run] if (parseInt(o.innerHTML) >= 12) o.style.backgroundColor = 'red'; } );
Working with Attributes:Attributes allow you to access elements by querying their attributes. For example (see the table above for live results):
// Marks the cells that has a class attribute AND // an id starting with "ist" in the "cities" table midori.get('#cities td[class][id^=ist]').apply( [Run] 'style.backgroundColor = "red"'); // Marks the cells not having the class "city" in the "cities" table midori.get('#cities td[class!=city]').apply( [Run] 'style.backgroundColor = "blue"');
The full list of operators that you can use are:
Notes:= Equals to != Not equals to ^= Starts with $= Ends with *= Contains ~= Equals to an item in a white-space separated list - If you pass a DOM object as the startAt parameter, the search for matching elements will start from that object instead of the document root.
- Multiple class matches is possible like this: div.suggestion.selected
- You can put attribute values inside double quotes when necessary. For example, div[class="suggestion selected"]
- :nth-child equations must be in the format: an+b. Valid values include: 2n+1 (equals to "odd"), 3n, -n+5.
- Escaping characters with '\\' is supported.
-
getCssRule(stylesheet, rule, property)Returns the original value of a stylesheet rule property.
The value for stylesheet must be an array index. This is 0 for the first stylesheet in a document.
The returned value is the original value as specified in the stylesheet. It does not reflect any changes made after the document is loaded.
Example:var originalBodyFontSize = midori.getCssRule(0, 'body', 'fontSize');
-
getPos(obj)Returns the x and y coordinates of an object's top-left corner.Example:
<a href="#getPos" onclick=" [Run] objPos = midori.getPos(this); alert('x: ' + objPos.x + 'y: ' + objPos.y)">Run</a>
-
getWindowDims()Returns the width and height of the currently visible browser client area, and the amount of vertical scrolling from the very top.
The returned object has the following members: windowWidth, windowHeight, scrollTop.
The width and height do not include anything outside the active area (e.g. menus, toolbars, scrollbars).
Example:<a href="#getWindowDims" onclick=" [Run] dims = midori.getWindowDims(); alert('width: ' + dims.windowWidth + ', height: ' + dims.windowHeight + ', scrolled: ' + dims.scrollTop)">Run</a>
-
each(parentObj, callBack, depthFirst)Passes all the objects under the parent object to the callback function.
If depthFirst is true (false by default), the callback function is called after branching to the children.
-
removeNode(obj)Removes a node from the document and returns it.Example:
// Removes the first div element from the document var removedDiv = midori.removeNode(midori.get('div')[0]); -
resizeImg(obj, maxWidth)Resizes all images wider than maxWidth to maxWidth in an object.
maxWidth is optional, and defaults to 400 pixels.
Example:// Resizes all images wider than 500 pixels in document body midori.resizeImg(document.body, 500); -
setAttributes(obj, attrList)Sets multiple attributes in one go.Example:
// Sets the id and class of the first div element midori.setAttributes(midori.get('div')[0], { id: 'first-div', className: 'title' } ); -
setStyles(obj, styleList)Sets multiple styles in one go.Example:
// Sets the color and background color of the body element midori.setStyles(document.body, { color: '#333', backgroundColor: '#FFF' } ); -
shortenWords(obj, maxLen)Shortens all words longer than maxLen in an object.
This method is useful to shorten long pieces of continuous text such as URLs to avoid page layout and horizontal page scrolling issues. A long URL like: http://www.midorijs.com/midori.html#shortenWords will look like this: http://www.midorijs...i.html#shortenWords after processing. Shortened URLs will continue to work when clicked.
maxLen is optional, defaults to 45 characters.
Example:// Shortens all words longer than 50 characters in document body midori.shortenWords(document.body, 50); -
sibling(obj, direction)Returns the previous or next sibling of an object by filtering out text nodes.
direction can be either 'prev' or 'next'.
Example:// Returns the next sibling of the first div element midori.sibling(midori.get('div')[0], 'next');
Event
-
addEventListener(target, eventType, listenerFunc)Adds an event listener to an object.
eventType can be any event such as 'click' and 'mouseover'.
midori also supports a special event type called 'ready' which is identical to the 'load' event except for one thing: Your listenerFunc is called immediately after the document is parsed by the web browser. Unlike 'load', there is no need to wait for all the images to load.
The event object is passed to your listenerFunc.
Examples:// Initializes the tabs as soon as the document is parsed midori.addEventListener(window, 'ready', function (e) { midoriTab.init() } ); // Adds a click event to all links to store the // last clicked link in a cookie midori.get('a').apply(function (o) { midori.addEventListener(o, 'click', function (e) { midori.setCookie('history', o.href+'||'+o.innerHTML, 86400*365); } ) } );
-
getEventTarget(event)Returns the target object of the last event.Example:
<a href="#getEventTarget" onclick=" [Run] alert(midori.getEventTarget(event).innerHTML)">Run</a>
-
getMousePos(event)Returns the x and y coordinates of the mouse cursor position.Example:
<a href="#getMousePos" onclick=" [Run] mousePos = midori.getMousePos(event); alert('x: ' + mousePos.x + 'y: ' + mousePos.y)">Run</a>
-
preventBubble(event)Prevents the bubbling of an event.Example:Outside ClickableInside not
<div onclick="alert('Clicked')" style="..."> Outside Clickable <div onclick="midori.preventBubble(event)" style="..."> Inside not </div> </div> -
preventDefault(event)Prevents the default event from happening.Example:
// Cancels the click event - nothing will happen <a href="http://www.example.net" onclick=" [Run] midori.preventDefault(event)">Run</a>
Cookie
-
getCookie(cookieName)Returns the value of a cookie.Example:
var cookieValue = midori.getCookie('mycookie'); -
setCookie(name, value, expires, path, domain)Sets a cookie.
You can have multiple cookies for a single domain, but each web browser has different limits usually ranging from 20 to 50, and if you exceed the limit, new cookies may overwrite the old ones.
You cannot store more than 4096 bytes (4K) of data in a cookie or *all* of your cookies depending on the web browser you are using. So, it is safe to use no more than 4K for all your cookies combined.
expires must be the number of seconds from now. For example, if you want your cookie to persist for a year on a user's web browser, you can use something like 86400 * 365.
path and domain are optional. To make a cookie accessible from all the subdomains of a domain, you can use '.example.net' (note the dot in the beginning).
Example:// Adds a click event to all links to store the // last clicked link in a cookie midori.get('a').apply(function (o) { midori.addEventListener(o, 'click', function (e) { midori.setCookie('history', o.href+'||'+o.innerHTML, 86400*365); } ) } );
Form
-
checkRequiredFields(vars)Checks if all the required fields in a form are filled.
Accepts the following parameters:
- event is the event object.
- formId is id of the form.
- required is a comma separated list of required field ids.
- message is the text of the message that will be displayed if there are unfilled required fields.
- callback is the optional callback function. If the function returns false, the form is not submitted even if all the required fields are filled.
Notes:
- There must a be an element on the page that has an id in the following format: formId-status. The error message will be displayed in it.
- For required checkbox fields, there must be a container field such as <label> so the associated text can be highlighted if the checkbox is not checked.
Example:
<div id="message-form-status"> </div><br /> <form id="message-form" method="post" action="midori.html" onsubmit=" return midori.checkRequiredFields( { event: event, formId: 'message-form', required: 'pm_to', message: 'Please fill marked fields.' } )"> <div> <b>To:*</b><br /> <input type="text" name="pm_to" id="pm_to" /> <br /><br /> <b>Subject:</b><br /> <input type="text" name="pm_subject" /> <br /><br /> <input type="submit" value="Submit" /> </div> </form> - event is the event object.
-
convertToFields(parentNode, prefix, a)Converts the name-value pairs in an object to hidden form fields.
This method converts the data stored in a JavaScript object to hidden form fields for transparent server-side processing. Some scripting languages such as PHP automatically converts array-style form fields to arrays.
parentNode is the node the new fields will be inserted into.
prefix is a string that will be added to the beginning of the names of the new input fields.
a is an object that contains name-value pairs. Nesting objects is possible, but there is no check for duplicate keys.
Example:var citiesContainer = document.createElement('div'); [Run] document.body.appendChild(citiesContainer); midori.convertToFields(citiesContainer, 'cities', { 'San Francisco': 'CA', 'Seattle': 'WA', 'Chicago': 'IL' } ); alert(citiesContainer.innerHTML);
Array
-
concatUnique(a1, a2)Merges two arrays, but removes any duplicates.Example:
alert(midori.concatUnique( [Run] ['Red', 'Green', 'Blue'], ['Red', 'Yellow', 'Green']));
-
implode(glue, a)Joins array elements with a string (glue).Example:
alert(midori.implode( [Run] ' + ', ['Red', 'Green', 'Blue']) + ' = Color');
-
inArray(v, a)Returns true if a value is found in the specified array.Example:
alert(midori.inArray('Green', ['Red', 'Green', 'Blue'])); [Run]
String
-
replace(st, params)Replaces parameters with the corresponding values in a given string.
Parameters in the string st must be prefixed with a colon (:). The order of the parameter-value pairs in params is not important.
Example:alert(midori.replace( [Run] 'Name: :name, Homepage: <a href=":url">:url</a>', { name: 'John', url: 'http://www.example.net' } ));
-
trim(st)Strips any white-space from the beginning and end of a string.Example:
alert('*' + midori.trim(' Trimmed Stars ') + '*'); [Run] -
uniqid(range)Generates a random number between 0 and range (default: 100,000).Example:
alert(midori.uniqid()); [Run]
