Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ded/bonzo
library agnostic, extensible DOM utility
https://github.com/ded/bonzo
Last synced: about 1 month ago
JSON representation
library agnostic, extensible DOM utility
- Host: GitHub
- URL: https://github.com/ded/bonzo
- Owner: ded
- License: other
- Created: 2011-04-07T23:59:24.000Z (over 13 years ago)
- Default Branch: master
- Last Pushed: 2016-06-02T12:05:39.000Z (over 8 years ago)
- Last Synced: 2024-05-19T04:02:58.522Z (6 months ago)
- Language: JavaScript
- Homepage:
- Size: 965 KB
- Stars: 1,318
- Watchers: 65
- Forks: 139
- Open Issues: 24
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
## Bonzo
A library agnostic extensible DOM utility. Nothing else.
Bonzo is designed to live in any host library, such as [Ender](http://enderjs.com), or simply as a stand-alone tool for the majority of your DOM-related tasks.
**It looks like this:**
``` js
bonzo(elements)
.hide()
.addClass('foo')
.append('the happs
')
.css({
color: 'red',
'background-color': 'white'
})
.show()
```---------
* Use with a selector engine
* Bonzo extension API
* Complete Bonzo API
* About the name "Bonzo"
* Contributing:
- Building
- Tests
* Browser support
* Ender integration
* Contributors
* Licence & copyright--------------------------------------------------------
### Use with a selector engineA great way to use Bonzo is with a selector engine, like [Qwery](https://github.com/ded/qwery). You could wrap Bonzo up and augment your wrapper to inherit the same methods:
``` js
function $(selector) {
return bonzo(qwery(selector))
}
```This now allows you to write the following code:
``` js
$('#content a[rel~="bookmark"]').after('√').css('text-decoration', 'none')
```See
bonzo.setQueryEngine()
for more details.One of the greatest parts about Bonzo is its simplicity to hook into the internal chain to create custom methods. For example you can create a method called `color()` like this:
``` js
bonzo.aug({
color: function (c) {
return this.css('color', c);
}
})// you can now do the following
$('p').color('aqua')
```*
bonzo()
*
bonzo().get()
*bonzo().each()
*bonzo().deepEach()
*bonzo().map()
*bonzo().html()
*bonzo().text()
*bonzo().addClass()
*bonzo().removeClass()
*bonzo().hasClass()
*bonzo().toggleClass()
*bonzo().show()
*bonzo().hide()
*bonzo().toggle()
*bonzo().first()
*bonzo().last()
*bonzo().next()
*bonzo().previous()
*bonzo().parent()
*bonzo().focus()
*bonzo().blur()
*bonzo().append()
*bonzo().appendTo()
*bonzo().prepend()
*bonzo().prependTo()
*bonzo().before()
*bonzo().insertBefore()
*bonzo().after()
*bonzo().insertAfter()
*bonzo().replaceWith()
*bonzo().css()
*bonzo().offset()
*bonzo().dim()
*bonzo().attr()
*bonzo().removeAttr()
*bonzo().val()
*bonzo().data()
*bonzo().remove()
*bonzo().empty()
*bonzo().detach()
*bonzo().scrollLeft()
*bonzo().scrollTop()
*
bonzo.aug()
*bonzo.doc()
*bonzo.viewport()
*bonzo.firstChild()
*bonzo.isAncestor()
*bonzo.create()
*bonzo.setQueryEngine()
Added in the Ender bridge:
*
$().parents()
*$().closest()
*$().siblings()
*$().children()
*$().width()
*$().height()
------------------------------------------------
### bonzo(DOMElement | ArrayLikeDOMElementCollection)
Factory function for bonzo objects. Takes in either a single `DOMElement`, or an array-like object or array of them. Returns an array-like `Bonzo` object possessing all of the [instance methods](#instance) documented below.
```js
var elem = document.getElementById('foo');
var $elem = bonzo(elem);
// $elem now has all the special powers listed below...
```------------------------------------------------
### bonzo().get(index)
Returns the raw `DOMElement` held at `index`. Because Bonzo objects are array-like, this is identical to saying `bonzo()[index]`.
```js
var elem = document.getElementById('bar');
var $elem = bonzo(elem);
var sameElem = $elem.get(0);
var sameElemAgain = $elem[0];
// elem === sameElem && sameElem === sameElemAgain
```------------------------------------------------
### bonzo().each(fn[, scope])
Allows you to iterate over the raw elements contained in `bonzo` collections. `fn` gets called once for each element in the collection, with each element, in turn, as its first argument. If the optional `scope` argument is supplied, then it is used as the `this` value of the function. Otherwise, the same element that is passed as the first argument is used. The index of the element is passed as the second argument, and the collection itself is passed as the third.------------------------------------------------
### bonzo().deepEach(fn[, scope])
`deepEach()` ...------------------------------------------------
### bonzo().map(fn[, rejectFn])
`map()` ...------------------------------------------------
### bonzo().html([content])`bonzo.html()` either sets or gets the elements' `innerHTML` to `content`, depending if the optional `content` argument is pased in. If called without the argument, `.html()` returns the element's `innerHTML`.
* `content` is an *optional* argument. If it is passed in, it will **set** the `innerHTML` of a given element and return a `Bonzo` object.
#### Examples
```js
bonzo(element).html('foo
');
bonzo(element).html(); //foo
```------------------------------------------------
### bonzo().text([content])`bonzo.text()` is very similar to [`.html`](#api-html), but uses the elements' `textContent` instead of `innerHTML` when setting the `content`. Thus, the `content` will not get parsed as markup.
This method either **gets** or **sets** the text of a given element, depending if the optional *content* argument is passed in.
* `content` is an *optional* argument. If it is passed in, it will **set** the text value of a given element and return a `Bonzo` object.
If no `content` is specified, the `.text()` method will return the text that makes up that element.
If the element has children (i.e. a `ul` containing several `li` children), the children's text is included in the return value.
#### Examples
``` js
bonzo("hello, world
").text()
// → returns "hello, world"bonzo("
i'm going to change
").text("changed you!")
// thenow says "changed you!"
// → returns a Bonzo objectbonzo("
- one
- two
// → returns "one
// two"
bonzo("
- one
- two
// the html is now
- hello
// → returns a Bonzo object
```
------------------------------------------------
### bonzo().addClass(class | classList)
`bonzo.addClass(class | classList)` adds the specified `class` to the given element. It returns a `Bonzo` object.
* `class` is a *required* argument. It is the name of the class you wish to add to the given element.
* If you'd like to add multiple classes at once, simply use a
space-separated string, a `classList` (i.e. "classOne classTwo").
#### Examples
``` js
bonzo("
hello, world
").addClass('big')// the html is now
hello, world
// → returns a Bonzo object
bonzo("
hello, world
").addClass()// throws an error, since the argument is required
bonzo("
i want lots of classes
").addClass("one two three")// the html is now
i want lots of classes
// → returns a Bonzo object
```
------------------------------------------------
### bonzo().removeClass(class | classList)
`bonzo.removeClass(class)` removes the specified `class` from the given element. It returns a `Bonzo` object.
* `class` is a *required* argument. It is the name of the class you wish to remove from the given element.
* If you'd like to remove multiple classes at once, simply use a
space-separated string, a `classList` (i.e. "classOne classTwo").
#### Examples
``` js
bonzo("
hello, world
").removeClass('small')// the html is now
hello, world
// → returns a Bonzo object
bonzo("
hello, world
").removeClass()// throws an error, since the argument is required
bonzo("
i have lots of classes
").removeClass("one two three")// the html is now
i have lots of classes
// → returns a Bonzo object
bonzo("
hello, world
").removeClass('does_not_exist')// → since the argument does not match a classlist the
has, nothing happens and a Bonzo object is returned
```
------------------------------------------------
### bonzo().hasClass(class | classList)
`bonzo.hasClass(class)` returns **true** or **false**, based on whether
or not the specified element has a given *class*. It returns **true** if
the specified element *does* have the `class`, and returns **false** if
the specified element **does not** have the `class`.
* `class` is a *required* argument. It is the name of the class you wish to check for in a given element.
* **NOTE**: if you pass in a space-separated `classList` like you can
in addClass and removeClass, this method will return
**true** if **any** of the space-separated `classList` classes are present in the element.
#### Examples
``` js
bonzo("
something went wrong
").hasClass('alert')// → returns true
bonzo("
something went wrong
").hasClass('normal')// → returns false
bonzo("
something went wrong
").hasClass('one two three')// → returns true
bonzo("
something went wrong
").hasClass('three two one')// → returns true
bonzo("
something went wrong
").hasClass('small tiny')// → returns false
```
------------------------------------------------
### bonzo().toggleClass(class | classList)
`bonzo.toggleClass(class)` either adds or removes a specified `class` to the given element, depending on whether or not the given element already has a class with that `class` or not.
If the element **does** have a class named `class`, calling `toggleClass()` will **remove** the `class` class from it. If the element **does not** have a class with the specified `class`, calling `toggleClass()` will **add** a class with that `class`.
* `class` is a *required* argument. It is the name of the class you wish to toggle.
* If you'd like to toggle multiple classes at once, simply use a
space-separated string, a `classList` (i.e. "classOne classTwo").
#### Examples
``` js
bonzo("
something went wrong
").toggleClass('alert')// the html is now
something went wrong
// → returns a Bonzo object
bonzo("
something went wrong
").toggleClass('different')// the html is now
something went wrong
// → returns a Bonzo object
bonzo("
something went wrong
").toggleClass('three two one')// the html is now
something went wrong
// → returns a Bonzo object
bonzo("
something went wrong
").toggleClass('small tiny')// the html is now
something went wrong
// → returns a Bonzo object
```
------------------------------------------------
### bonzo().show([type])
`bonzo.show()` sets a given element or set of elements' `display` style property. By passing in an optional `type` argument, you can specify the attribute of the `display` property Bonzo gives the element(s).
* `type` is an *optional* argument. It is the display type you wish to
utilize.
If you specify an unsupported `type` (i.e. something other than `block`, `compact`, `inline-block`, `inline`, `inline-table`, `list-item`, `run-in`, `table`, `table-caption`, `table-cell`, `table-column`, `table-column-group`, `table-footer-group`, `table-header-group`, `table-row`, or `table-row-group`), Bonzo will ignore the invalid `type`.
#### Examples
``` js
bonzo("
I was hidden
").show()// html is now
I was hidden
// → returns a Bonzo object
bonzo("
I was hidden
").show('inline-block')// html is now
I was hidden
// → returns a Bonzo object
```
------------------------------------------------
### bonzo().hide()
`bonzo.hide()` adds a `display: none;` to the specified element.
#### Examples
``` js
bonzo("
Hello, world
").hide()// html is now
Hello, world
// → returns a Bonzo object
```
------------------------------------------------
### bonzo().toggle([callback[, type]])
`toggle()` ...
------------------------------------------------
### bonzo().first()
`bonzo.first()` returns a Bonzo object referencing the first element in a set of elements. If the set is empty, the a Bonzo object will still be returned, but it won't contain any children.
#### Examples
``` js
var firstItem = bonzo("
firstItem.text() // "one"
firstItem.length // 1
// → returns a Bonzo object
var el = bonzo("").first()
el.text() // ""
el.length // 0
// → returns a Bonzo object
```
------------------------------------------------
### bonzo().last()
`bonzo.last()` returns a Bonzo object referencing the last element in a set of elements. If the set is empty, the a Bonzo object will still be returned, but it won't contain any children.
#### Examples
``` js
var lastItem = bonzo("
lastItem.text() // "three"
lastItem.length // 1
// → returns a Bonzo object
var el = bonzo("").last()
el.text() // ""
el.length // 0
// → returns a Bonzo object
```
------------------------------------------------
### bonzo().next()
`bonzo.next()` returns a `Bonzo` object with a list of the next element siblings in the initial collection.
------------------------------------------------
### bonzo().previous()
`bonzo.previous()` returns a `Bonzo` object with a list of the previous element siblings in the initial collection.
------------------------------------------------
### bonzo().parent()
`bonzo.parent()` returns a `Bonzo` object with a list of the `parentNode`'s of each item in the initial collection.
------------------------------------------------
### bonzo().focus()
`bonzo.focus()` will send the browser's focus event to an input element. This will only work on the first (zeroith index) item in the `Bonzo` collection.
------------------------------------------------
### bonzo().blur()
`bonzo.blur()` will send the browser's blur event to an input element. This will only work on the first (zeroith index) item in the `Bonzo` collection.
------------------------------------------------
### bonzo().append(html | element | collection)
`bonzo.append()` will insert the supplied html | element | collection at the initial supplied collection.
#### Examples
``` js
bonzo([element1, element2]).append('
hello
world
')bonzo(document.createElement('div')).append(document.createElement('p'))
bonzo(element).append(document.getElementsByTagName('p'))
```
------------------------------------------------
### bonzo().appendTo(target)
`bonzo.appendTo()` will insert the initial collection at the supplied `target`. It's the backwards version of `bonzo.append`
#### Examples
``` js
bonzo('
hello
').appendTo(document.body)bonzo(document.createElement('div')).appendTo(document.querySelectorAll('p'))
```
------------------------------------------------
### bonzo().prepend(html | element | collection)
`bonzo.prepend()` is similar to bonzo.append(), but inserts at the top of a collection (it prepends ;).
------------------------------------------------
### bonzo().prependTo(target)
`prependTo()` is similar to bonzo.appendTo(), but, you know, prepends.
------------------------------------------------
### bonzo().before(html | element | collection)
`bonzo.before()` inserts the supplied content before each item in the initial collection.
#### Examples
``` js
bonzo(document.querySelectorAll('p')).before('hello')
```
------------------------------------------------
### bonzo().insertBefore(target)
`bonzo.insertBefore()` will insert the items in the initial collection before the supplied targets.
#### Examples
``` js
bonzo('
hello
').insertBefore(document.querySelectorAll('div'))```
------------------------------------------------
### bonzo().after(html | element | collection)
`bonzo.after()` will insert the supplied content after each item in the initial collection.
#### Examples
``` js
bonzo(document.querySelectorAll('p')).after(', huh')
```
------------------------------------------------
### bonzo().insertAfter(target)
`insertAfter()` ...
------------------------------------------------
### bonzo().replaceWith(html | element | collection)
`bonzo.replaceWith()` will replace each item in the initial collection with the supplied content.
#### Examples
``` js
bonzo(document.querySelectorAll('p')).replaceWith('
you have been replaced
')```
------------------------------------------------
### bonzo().css(property | hash[, value])
Sets or returns CSS properties of the element. If a single string argument is passed, then the value of that CSS property is returned. If two string arguments are passed, the CSS property specified by the first is set to the value specified by the second. If a single hash argument is passed, then the CSS property corresponding to each property is set to the value designated by the hash property's value.
```js
bonzo(elem).css({
background: 'blue',
color: green;
}).css('border', '2px solid red').css('color'); // "green"
```
------------------------------------------------
### bonzo().offset([ x, y ] | [ hash ])
`bonzo.offset()` is an overloaded setter and getter. When setting the offset of a collection, it will set an element to an explicit x/y coordinate position on the page. When getting the offset, the function returns an object containing the four properties `top`, `left`, `width`, and `height`.
#### Examples
``` js
bonzo(el).offset() // returns { top: n, left: n, width: n, height: n }
bonzo(el).offset(50, 100) // sets left to 50, and top to 100
bonzo(el).offset({ left: 50, top: 100 }) // sets left to 50, and top to 100
```
------------------------------------------------
### bonzo().dim()
`bonzo.dim()` returns the entire `width` and `height` dimensions of an element, including the `scrollHeight`.
------------------------------------------------
### bonzo().attr(key[, value] | hash)
Sets or returns attributes of the element. If the first argument is a hash, then each property of the hash is read and the corresponding attribute of the element is set to the hash property's value. If the first argument is a string and no second argument is provided, the value of the element's attribute with the same name is returned. If a second argument *is* supplied, then the element's attribute of the same name as the first argument is set to the value of the second argument.
------------------------------------------------
### bonzo().removeAttr(key)
`bonzo.removeAttr()` removes the supplied attribute from each item in the initial collection.
------------------------------------------------
### bonzo().val([ value ])
`bonzo.val()` is an overloaded setter and getter. it returns the content from the first element `value` attribute. When setting it sets the `value` attribute of each item in the initial collection.
------------------------------------------------
### bonzo().data([ key[, value ] ] | [ hash ])
`bonzo.data()` is an overloaded setter and getter. `data` can be set to any value and referenced further when getting the data.
#### Examples
``` js
bonzo(el).data('username', 'ded')
bonzo(el).data('username') // returns 'ded'
bonzo(another).data('userinfo', {
id: 911,
name: 'agent'
age: 2
})
```
------------------------------------------------
### bonzo().remove()
`bonzo.remove()` removes the initial supplied collection from the DOM
#### Examples
``` js
bonzo(document.querySelectorAll('p')).remove()
```
------------------------------------------------
### bonzo().empty()
`bonzo.empty()` will empty out the content of the initial supplied collection, but not remove the nodes themselves.
------------------------------------------------
### bonzo().detach()
`bonzo.detach()` returns a `Bonzo` object containing the supplied collection, but detached from the DOM. This is useful if you wish to do heavy operations an offline Node, and then inserting it back into the DOM again.
#### Examples
``` js
bonzo(document.querySelectorAll('p')).detach().addClass('eyo').html('
stuff
').appendTo(document.body)```
------------------------------------------------
### bonzo().scrollLeft([ x ])
`bonzo.scrollLeft()` is an overloaded setter and getter. it returns the `scrollLeft` of an element when no argument is supplied, otherwise, sets it.
------------------------------------------------
### bonzo().scrollTop([ y ]
`bonzo.scrollTop()` is an overloaded setter and getter. it returns the `scrollTop` of an element when no argument is supplied, otherwise, sets it.
------------------------------------------------
### bonzo.aug(hash)
`bonzo.aug()` will agument the `Bonzo` prototype so that you can customize and include additions to your liking.
#### Examples
``` js
bonzo.aug({
color: function (c) {
// `this` is the scope of the `Bonzo` instance
return this.css('color', c)
}
})
// you can now do the following
$('p').color('aqua')
```
------------------------------------------------
### bonzo.doc()
`bonzo.doc()` returns an object containing `width` and `height` information regarding the document size. This includes `scrollWidth` and `scrollHeight`.
------------------------------------------------
### bonzo.viewport()
`bonzo.viewport()` returns an object containing `width` and `height` information regarding the document viewport. This is usually the same as using `bonzo.doc()`, but can be smaller given it's only what you *see* in the viewport, and not the entire document (with scrolling).
------------------------------------------------
### bonzo.firstChild(element)
`firstChild()` ...
------------------------------------------------
### bonzo.isAncestor(container, element)
`isAncestor()` ...
------------------------------------------------
### bonzo.create(container, element)
`create()` ...
------------------------------------------------
### $().parents()
`parents()` ...
------------------------------------------------
### bonzo.setQueryEngine(engine)
`bonzo.setQueryEngine()` is a useful utility that allows you to pair `Bonzo` with a selector engine.
For the insertion methods you can set a query selector host:
#### Examples
``` js
// using Ender supported modules
bonzo.setQueryEngine(require('qwery'))
bonzo(bonzo.create('
// or Sizzle
bonzo.setQueryEngine(Sizzle)
```
------------------------------------------------
### $().closest()
`closest()` ...
------------------------------------------------
### $().siblings()
`siblings()` ...
------------------------------------------------
### $().children()
`children()` ...
------------------------------------------------
### $().width([ value ])
`width()` ...
------------------------------------------------
### $().height([ value ])
`height()` ...
------------------------------------------------
About the name "Bonzo"
----------------------
*Bonzo Madrid* was a malicious battle school commander of whom eventually is killed by [Ender Wiggin](http://en.wikipedia.org/wiki/Ender_Wiggin). Bonzo represents the DOM, of whom we'd all love to slay.
You should only edit the files in the *src/* directory. Bonzo is compiled into the *bonzo.js* and *bonzo.min.js* files contained in the root directory by the build command:
```sh
$ npm install
$ make
```
Point your test browser(s) to *tests/tests.html*, or:
```sh
$ open tests/tests.html
```
Please try to include tests or adjustments to existing tests with all non-trivial contributions.
Browser support
---------------
* IE9+
* Chrome
* Safari 5+
* Firefox 10+
* Opera
Ender integration
-----------------
Bonzo is a registered npm package and fits in nicely with the [Ender](http://enderjs.com) framework. If you don't have Ender, you should install now, and never look back, *ever*. As a side note the *query engine host* is set for you when you include it with Ender.
```sh
$ npm install ender -g
```
To combine Bonzo to your Ender build, you can add it as such:
```sh
$ ender build bonzo[ package-b[ package-c ...]]
```
or, add it to your existing ender package
```sh
$ ender add bonzo
```
Bonzo is included in [The Jeesh](http://ender.jit.su/#jeesh), Ender's "starter-pack", when you `ender build jeesh` you'll get Bonzo and some other amazing libraries that'll make working in the browser a breeze. See the [Ender documentation](http://ender.jit.su/) for more details.
* [Dustin Diaz](https://github.com/ded/bonzo/commits/master?author=ded)
* [Rod Vagg](https://github.com/ded/bonzo/commits/master?author=rvagg)
* [Jacob Thornton](https://github.com/ded/bonzo/commits/master?author=fat)
Licence & copyright
-------------------
Bonzo is Copyright © 2014 Dustin Diaz [@ded](https://twitter.com/ded) and licensed under the MIT licence. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.