• Stars
    star
    135
  • Rank 269,297 (Top 6 %)
  • Language
    JavaScript
  • Created about 12 years ago
  • Updated about 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Observe DOM mutations with jQuery

jQuery Observe

A jQuery plugin which simplifies the use of the new DOM Mutation Observer interface introduced in newer browsers. jquery-observe.js contains the compiled and minified version of the plugin.

Available through bower

bower install jquery-observe

And npm

npm install @kapetan/jquery-observer

Compatibility

At this point the Mutation Observer API is only available in newer versions of Google Chrome (>= 18) and Mozilla Firefox (>= 14). Can be useful when developing extensions (add-ons) that use content scripts, on a page that you don't control.

There is a fallback for browsers who don't support the Mutation Observer API (mainly IE9 and Opera), using the deprecated DOM Mutation Events interface. These don't act completely as Mutation Observers, and can cause some different behaviour between browsers. For instance an event is fired for every descendant of an inserted node, where only one record is dispatched when using Mutation Observers. Furthermore because mutation events don't have the same information associated with them as Mutation Observer records, some contextual selectors may not match removed nodes. Some of those are :first, :first-child, :eq, :last, :last-child, :even and :odd (not an exhaustive list).

Usage

The observe interface $.fn.observe() is somewhat similar to the jQuery event api using the $.fn.on() method.

$('#content')
	.observe('attributes', function(record) {
		// Observe attribute changes on #content
	})
	.observe('childlist subtree', function(record) {
		// Observe changes in the subtree
	})
	.observe({ attributes: true, attributeFilter: ['class'] }, function(record) {
		// Observe changes in attribute class on #content
	});

The callback function gets passed the MutationRecord instance matching the query.

The first argument can either be a string or an object containing the options which are passed to MutaionObserver.observe() method. See the w3c documentation for Mutation Observer for more information on the available options.

All the above observers are collapsed into a single Mutation Observer object using #content as target.

The real power comes when using a selector to filter the elements.

$('#content')
	.observe('childlist', 'ul li:first', function(record) {
		// Observe if elements matching '#content ul li:first' have been added or removed
	})
	.observe('attributes', '.section p:visible', function(record) {
		// Observe if elements matching '#content .section p:visible' have been added or removed
	})

In the above callback functions this refers to the available matched DOM element. In the case where no selector is given this always refers to the element which .observe() was called on. When a selector is present this references different elements.

  • Records of type attributes: this refers to the node which had an attribute changed.

  • Records of type characterData: this refers to the parent element of the text node which had its content modified. The modified text node can be retrieved trough record.target.

  • Records of type childList and the selector matches an added node: this refers to the added node.

  • Records of type childList and the selector matches a removed node: this refers to the parent of the removed node (since the removed node is no longer available in the DOM).

This also means that the callback is called for every matched element (similar to $.fn.on()).

Using the above defined observers with the following HTML:

	<div id='content'>
		<ul>
			<li><span></span></li>
		</ul>
		<span class='section'><p class='hello'>Hello</p></span>
	</div>
  • Running $('#content ul').append('<li></li>') // added as last element will not trigger the first observer neither will $('#content ul li:first').append('<span></span>'), since the observe selector only matches nodes that either have been added or removed.

  • Running $('#content ul').prepend('<li></li>') will trigger the first observer, since a li element was inserted as the first child. And this will reference to the newly inserted node.

  • Running $('#content ul li:first').remove() also triggers the first observer. In this case this will reference to the parent of the removed element (the ul element).

  • Running $('#content ul li:first span').remove() will not trigger the first observer.

  • Running $('#content span p').addClass('myClass') triggers the second observer.

Note that the changes to the DOM don't have to be performed using jQuery. The last example can also be run using plain javascript document.getElementsByClassName('hello')[0].className += ' myClass'.

Extended options

There are two custom Mutation Observer options which can be used together with the other options. These are added and removed. Which only trigger an observer if either a node has been added or removed.

	$('#content')
		.observe('added', 'li:first', function(record) {
			// Only called if a node matching '#content li:first' has been added
		})
		.observe('removed', 'li:first', function(record) {
			// Only called if a node matching '#content li:first' has been removed
		});

Using the options 'added removed' is equivalent to 'childlist'.

Removing observers

Use the $.fn.disconnect() method to remove an observer. The arguments must match the arguments given to the $.fn.observe() method. Or call the disconnect method without arguments to remove all observers. The underlying Mutation Observer is disabled when there are no observers listening for changes.

Issues

There are some problems getting the characterData option to work in Chrome (may be because of bug #134322).

License

This software is licensed under "MIT"

Copyright (c) 2012 Mirza Kapetanovic

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

titlebar

Emulate OS X window title bar
JavaScript
484
star
2

dns

A DNS library written in C#
C#
395
star
3

electron-drag

Window dragging for electron applications
JavaScript
320
star
4

osx-mouse

Mouse tracking for OS X
C++
73
star
5

win-mouse

Mouse tracking for Windows
C++
52
star
6

repaint

HTML layout engine
JavaScript
48
star
7

css-shorthand-expand

Expand CSS shorthand properties
JavaScript
46
star
8

text-width

Measure the text width in browsers
JavaScript
20
star
9

audio-stream

Stream raw audio data from a MediaStream
JavaScript
19
star
10

browser-beep

Beeping sound in browser using Web Audio API
JavaScript
16
star
11

cordova-plugin-android-wifi-manager

Cordova plugin for accessing Android WifiManager
Java
15
star
12

vue-long-press-directive

Long press directive plugin for Vue.js
JavaScript
10
star
13

syntactical

Browserify transform that emits a descriptive syntax error on invalid javascript
JavaScript
9
star
14

text-height

Measure the text height in browsers
JavaScript
9
star
15

service-names-port-numbers

IANA assigned port numbers
JavaScript
9
star
16

redditor

Minimal reddit API wrapper
JavaScript
7
star
17

the-hunt

2D multiplayer game for the browser
JavaScript
5
star
18

extended-inquiry-response

Bluetooth EIR encoder and decoder
JavaScript
5
star
19

remote-procedure-call-stream

Binary RPC protocol stream
JavaScript
4
star
20

reddit-thread-stream

Writable stream for updating reddit self threads
JavaScript
4
star
21

http.m

A HTTP server library written in Objective-C
Objective-C
4
star
22

render-html

Web component for server-side rendering HTML as images
JavaScript
4
star
23

osx-mouse-stream

Streaming mouse events for OS X
JavaScript
4
star
24

cyclic-array

Simple cyclic array (buffer) implementation
JavaScript
4
star
25

audio-activity

Detect audio activity of a MediaStream
JavaScript
3
star
26

noise-protocol-stream

Node stream wrapper for Noise Protocol C implementation compiled to WebAssembly
JavaScript
3
star
27

iServe

iOS application for serving device assets over HTTP
Objective-C
2
star
28

ruby-mud

A simple package manager for client-side Javascript
Ruby
2
star
29

ejs-stream

Through stream for rendering objects with ejs templates
JavaScript
2
star
30

elite

Tournament web application
JavaScript
2
star
31

service-port

Map a service name to a port number
JavaScript
2
star
32

taco-deploy-extract

Extract tarballs into taco deployment directories
JavaScript
2
star
33

npm-install-cache

Install node_modules from cache
Shell
2
star
34

indexeddown

Leveldown API implementation on top of IndexedDB
JavaScript
2
star
35

ruby-tracker

A small BitTorrent tracker written in Ruby
Ruby
1
star
36

jett

A Java API wrapper for Ge.tt
Java
1
star
37

root.redirects

Redirection handling for root
JavaScript
1
star
38

repaint-chrome

Simple interface for repaint
JavaScript
1
star
39

bitless

A small BitTorrent client written in Python
Python
1
star
40

jquery-tag

A jQuery tagging plugin for input fields
JavaScript
1
star
41

level-tail-stream

Tailable stream from levelup compliant store
JavaScript
1
star
42

get-stats

Basic RTCPeerConnection statistics
JavaScript
1
star
43

bitless.js

A small BitTorrent client written in Javascript
JavaScript
1
star
44

pcm-stream

A transform stream for converting audio encoded as 32-bit floats to 16-bit intergers
JavaScript
1
star
45

dribler

Soccer event stream
JavaScript
1
star
46

ebml-decoder

EBML decoder stream
JavaScript
1
star
47

cordova-plugin-android-imei

Cordova plugin for retrieving IMEI of the device
Java
1
star