Mepto

Mepto is a modern, TypeScript rewrite of Zepto — a minimalist JavaScript library for modern browsers with a largely jQuery-compatible API.

If you use jQuery, you already know how to use Mepto.

The goal is to match jQuery's ergonomics while shedding legacy-browser baggage and reducing browser overhead — fewer reflows, repaints, layout thrashes, and unnecessary DOM queries — so teams can gradually replace jQuery with Mepto without sacrificing performance, and often gaining it.

Download & install

Mepto is published to npm as meptos:

npm install meptos

Import it from a bundler or TypeScript project:

import { $ } from 'meptos'

$('#app').addClass('ready').on('click', 'button', handleClick)

Or load the UMD build directly in the browser — it exposes window.$ and window.mepto:

<script src="https://cdn.jsdelivr.net/npm/meptos/dist/meptos.umd.cjs"></script>
<script>
  $(function () {
    $('#app').addClass('ready')
  })
</script>

Unlike Zepto, there is no custom-build step: a single build includes every module (events, ajax, form, fx, touch, and more). TypeScript declarations ship in the package (dist/meptos.d.ts), so editor autocomplete and type-checking work out of the box:

import { $, type MeptoCollection } from 'meptos'

const items: MeptoCollection = $('.item').addClass('active')

Browser support

Evergreen browsers only. Mepto targets the last few versions of Chrome, Firefox, Safari (14+), and Edge. There is no Internet Explorer or legacy-Edge support and no polyfills: Mepto uses native platform APIs (WeakMap, AbortController, fetch, classList, closest, dataset, requestAnimationFrame, …) freely. If you need to support a legacy browser, Mepto is not the right tool.

Modules

Every module below is bundled in every build — there is nothing to configure.

Module What it gives you
mepto Core: selectors, DOM manipulation, traversal, attributes, CSS, dimensions
event on() / off() / trigger(), event delegation, custom events
ajax $.ajax, $.get, $.post, $.getJSON, JSONP (built on fetch)
form serializeArray(), serialize(), submit()
callbacks $.Callbacks
deferred $.Deferred / promise API
data data() storing arbitrary objects (WeakMap-backed, leak-free)
detect $.os and $.browser device/browser sniffing
fx animate()
fx_methods Animated show() / hide() / toggle() / fade*()
selector jQuery CSS pseudo extensions: :first, :visible, etc.
stack end(), andSelf() chaining helpers
touch Tap & swipe events on touch devices
gesture Pinch gesture events

The Zepto-era ie and ios3 modules were dropped along with all legacy browser support.

Creating plug-ins

Add methods to all Mepto collections by extending $.fn. Return this (or a new collection) so your plug-in stays chainable:

;(function ($) {
  $.fn.reverse = function () {
    return $(this.get().reverse())
  }
})(mepto)

$('ul li').reverse().appendTo('ul')

The same pattern in TypeScript — augment the MeptoCollection interface so the new method type-checks everywhere:

import { $, type MeptoCollection } from 'meptos'

declare module 'meptos' {
  interface MeptoCollection {
    reverse(): MeptoCollection
  }
}

$.fn.reverse = function (this: MeptoCollection): MeptoCollection {
  return $(this.get().reverse()) as MeptoCollection
}

Static utilities can be attached directly to $. Inside collection methods, this is the current Mepto collection; inside per-element callbacks (each, event handlers), this is the DOM element.

Core methods

$() $(selector, [context]) ⇒ collection $(collection) ⇒ same collection $(DOM nodes) ⇒ collection $(htmlString) ⇒ collection $(htmlString, attributes) ⇒ collection $(function(){ ... }) ⇒ collection

The main Mepto function. With a CSS selector and an optional context node it returns the matching elements; with an HTML fragment string it creates new (detached) DOM elements; with a DOM node, array of nodes, or another collection it wraps it for chaining; with a function it registers a DOM-ready callback.

$('div')              // all DIV elements on the page
$('#foo')             // element with ID "foo"
$('<p>Hello</p>')    // a new, detached P element
$(document.body)      // wrap an existing element
$(function () {       // run when the DOM is ready
  $('body').addClass('ready')
})

When creating elements from HTML you may pass an object of attributes as the second argument. Keys that name collection methods (such as text, html, val, css, addClass) invoke the method; everything else is set as an attribute:

$('<li>foo</li>', {
  text: 'Hello list',
  addClass: 'greeting',
  css: { color: '#e80' },
  id: 'greeting'
})

$.camelCase $.camelCase(string) ⇒ string

Converts a dash-separated string into camelCase. Memoized for repeated calls.

$.camelCase('hello-there')  //⇒ "helloThere"
$.camelCase('data-id')      //⇒ "dataId"

$.contains $.contains(parent, node) ⇒ boolean

Checks if the parent node contains the given DOM node. Returns false if both are the same node.

$.each $.each(collection, function(index, item){ ... }) ⇒ collection

Iterate over array elements or object key-value pairs. Returning false from the iterator function stops the loop.

$.each(['a', 'b', 'c'], function (index, item) {
  console.log('item %d is: %s', index, item)
})

var hash = { name: 'mepto', size: 'micro' }
$.each(hash, function (key, value) {
  console.log('%s: %s', key, value)
})

$.extend $.extend(target, [source, [source2, ...]]) ⇒ target $.extend(true, target, [source, ...]) ⇒ target

Extend the target object with properties from each source object. When the first argument is true, plain objects and arrays are merged recursively (deep extend). Properties with undefined values are always skipped.

var target = { one: 'patridge' }
var source = { two: 'turtle doves' }

$.extend(target, source)
//⇒ { one: 'patridge', two: 'turtle doves' }

$.fn

$.fn is the prototype object shared by all Mepto collections. Extend it to add methods to every collection — see Creating plug-ins.

$.grep $.grep(items, function(item, index){ ... }) ⇒ array

Returns a new array containing only the items for which the callback returned a truthy value.

$.grep([1, 2, 3], function (item) {
  return item > 1
})  //⇒ [2, 3]

$.inArray $.inArray(element, array, [fromIndex]) ⇒ number

Returns the index of the given element in an array, or -1 if it is not found.

$.isArray $.isArray(object) ⇒ boolean

Returns true if the object is an array. Alias of the native Array.isArray.

$.isEmptyObject $.isEmptyObject(object) ⇒ boolean

Returns true if the object has no enumerable properties of its own.

$.isFunction $.isFunction(object) ⇒ boolean

Returns true if the object is a function.

$.isNumeric $.isNumeric(value) ⇒ boolean

Returns true if the value represents a finite number — accepts numbers and numeric strings, rejects NaN, Infinity, and non-numeric values.

$.isPlainObject $.isPlainObject(object) ⇒ boolean

Returns true if the object is a "plain" object created by {} or new Object, as opposed to a DOM node, window, or a class instance.

$.isPlainObject({})          //⇒ true
$.isPlainObject(new Object()) //⇒ true
$.isPlainObject(window)       //⇒ false
$.isPlainObject(document.body) //⇒ false

$.isWindow $.isWindow(object) ⇒ boolean

Returns true if the object is a window object.

$.map $.map(elements, function(item, index){ ... }) ⇒ array

Iterate over elements of a collection (arrays and array-likes) and produce a new, flattened array of the callback return values. null and undefined results are dropped.

$.map([1, 2, 3], function (n) {
  return n * 2
})  //⇒ [2, 4, 6]

$.noop $.noop() ⇒ undefined

An empty function, useful as a placeholder callback.

$.parseJSON $.parseJSON(string) ⇒ object

Parses a JSON string into a JavaScript value. Alias of the native JSON.parse; throws on malformed input.

$.trim $.trim(string) ⇒ string

Removes whitespace from the beginning and end of a string.

$.type $.type(object) ⇒ string

Returns the internal JavaScript class of an object as a lowercase string: "null", "undefined", "boolean", "number", "string", "function", "array", "date", "regexp", "window", "document", "element", or "object".

$.type(null)      //⇒ "null"
$.type([1, 2])    //⇒ "array"
$.type($('div'))  //⇒ "object"

$.uuid (a counter for unique ids), $.support, and $.expr (the pseudo-selector bucket filled by the selector module) also exist on $ for plug-in authors.

add add(selector, [context]) ⇒ self

Adds more elements to the current collection, matched against an optional context, and returns a new collection with duplicates removed.

$(this).add('li').addClass('item')

addClass addClass(name) ⇒ self addClass(function(index, oldClassName){ ... }) ⇒ self

Adds the CSS class name(s) to each element. Multiple class names can be given in a space-separated string.

$('form input').addClass('required')
$('form input').addClass('required stable')

after after(content) ⇒ self

Insert content after each element in the collection. Content can be an HTML string, a DOM node, or an array of nodes. When the collection holds several elements, the content is cloned for each target.

$('form label').after('<p>A note below the label</p>')

append append(content) ⇒ self

Append content to the DOM inside each element in the collection. Content can be an HTML string, a DOM node, or an array of nodes.

$('ul').append('<li>new list item</li>')

appendTo appendTo(target) ⇒ self

Append the elements of the current collection to the target element(s). The inverse of append.

$('<li>new list item</li>').appendTo('ul')

attr attr(name) ⇒ string attr(name, value) ⇒ self attr(name, function(index, oldValue){ ... }) ⇒ self attr({ name: value, name2: value2, ... }) ⇒ self

Read or set DOM attributes. When no value is given, returns the attribute of the first element. When a value is given, sets the attribute on all elements. Setting the value to null removes the attribute (like removeAttr). Multiple attributes can be set at once with an object.

var name = $('form').attr('name')
$('input').attr('type', 'checkbox')
$('input').attr({ type: 'checkbox', checked: 'checked' })
$('input').attr('disabled', null)  // remove the attribute

before before(content) ⇒ self

Insert content before each element in the collection. Content can be an HTML string, a DOM node, or an array of nodes.

$('table td').before('<td>new cell</td>')

children children([selector]) ⇒ collection

Get the immediate children of each element in the collection, optionally filtered by a selector.

$('ol').children('*:nth-child(2n)')
//⇒ every other list item from every ordered list

classList Mepto extra

A DOMTokenList-compatible bridge to the native Element.classList, exposed on every collection. Mutating methods (add, remove, toggle, replace) return the collection so calls stay chainable; read methods (contains, item, length, value, toString()) read from the first element.

$('.item').classList.add('active').classList.remove('stale')
$('.item').classList.contains('active')  //⇒ true | false
$('.item').classList.toString()          //⇒ "foo bar baz"

This is a migration bridge: $('.x').addClass('y')$('.x').classList.add('y')el.classList.add('y') without any conceptual leap.

clone clone() ⇒ collection

Duplicate all elements in the collection via deep clone. Event handlers attached with Mepto are not copied to the clones.

closest closest(selector, [context]) ⇒ collection closest(collection) ⇒ collection closest(element) ⇒ collection

Get the first element that matches the selector by traversing upwards from the current element through its ancestors. Traversal stops at context if given, or at the document root. String selectors go through the native Element.closest().

var input = $('input[type=text]')
input.closest('form')

concat concat(nodes, [node2, ...]) ⇒ array

Concatenate elements, arrays, or Mepto collections into a new plain array, modifying the collection in place like the native Array.prototype.concat. Collection arguments are flattened to their element arrays first.

contents contents() ⇒ collection

Get the children of each element in the collection, including text and comment nodes. For an iframe, returns its content document.

css css(property) ⇒ value css([property1, property2, ...]) ⇒ object css(property, value) ⇒ self css({ property: value, property2: value2, ... }) ⇒ self

Read or set CSS properties on DOM elements. With a single property name, returns the computed value of the first element. With an array of property names, returns an object of name/value pairs. When a value is given it is set on all elements; setting a value to null or an empty string removes the property. A number is automatically suffixed with px for dimensional properties.

var elem = $('h1')
elem.css('background-color')           //⇒ read a property
elem.css('background-color', '#369')   //⇒ set a property
elem.css('background-color', '')       //⇒ remove a property
elem.css({ backgroundColor: '#8EE', fontSize: 28 })

data data(name) ⇒ value data(name, value) ⇒ self

Read or write data-* DOM attributes. Attribute names are dasherized automatically (data('myVal') reads data-my-val). When reading, values are deserialized: "true"/"false" become booleans, numeric strings become numbers, and JSON strings are parsed.

The bundled data module upgrades this method to store arbitrary objects: values are kept off the DOM node in a WeakMap-backed store, so they are garbage-collected when the node is removed — no leaks and no expando properties visible on elements.

$("#foo").data('count', 1)
$("#foo").data('count')  //⇒ 1

detach detach() ⇒ self Mepto extra

Alias of remove, provided for jQuery compatibility: removes the elements from the DOM and returns the (now detached) collection so it can be re-inserted later.

each each(function(index, item){ ... }) ⇒ self

Iterate through every element of the collection. Inside the iterator function, this refers to the current item. Returning false from the iterator stops the loop.

$('form input').each(function (index) {
  console.log('input %d is: %o', index, this)
})

empty empty() ⇒ self

Clear the DOM contents of each element in the collection.

eq eq(index) ⇒ collection

Get the element at the given index as a new collection. Negative indices count from the end of the collection.

$('li').eq(0)   //⇒ first list item
$('li').eq(-1)  //⇒ last list item

filter filter(selector) ⇒ collection filter(function(index){ ... }) ⇒ collection

Filter the collection to contain only items that match the CSS selector. If a function is given, return only the elements for which the function returns a truthy value.

find find(selector) ⇒ collection find(collection) ⇒ collection find(element) ⇒ collection

Find elements that match a CSS selector, searching within the descendants of each element in the current collection. When given a collection or element, returns only the given nodes that are descendants of the current collection.

var form = $('#myform')
form.find('input, select')

first first() ⇒ collection

Get the first element of the current collection.

$('form').first()

forEach forEach(function(item, index, array){ ... }, [context])

Iterate over every element of the collection with native Array.prototype.forEach semantics: this inside the callback is the optional context argument (not the element), and returning false does not stop the loop. For jQuery-style iteration use each.

get get() ⇒ array get(index) ⇒ DOM node

Get all elements as a plain array, or a single element by index. Negative indices count from the end: get(-1) returns the last element.

var elements = $('h2')
elements.get()   //⇒ array of all H2 nodes
elements.get(0)  //⇒ the first H2 node

has has(selector) ⇒ collection has(node) ⇒ collection

Filter the collection to only elements that have a descendant matching the selector, or that contain the given DOM node.

$('ol > li').has('a[href]')
//⇒ only list items that contain a link

hasClass hasClass(name) ⇒ boolean hasClass(name, [name2, ...]) ⇒ boolean

Check if any element of the collection has the specified class name. When multiple class names are given (space-separated), every one of them must be present.

height height() ⇒ number height(value) ⇒ self height(function(index, oldHeight){ ... }) ⇒ self

Get the height of the first element in the collection, or set the height of all elements. Applied to window it returns the viewport height; applied to document it returns the full document height. See also outerHeight for the border-box size.

$('#foo').height()     //⇒ 123
$(window).height()     //⇒ 838 (viewport height)
$(document).height()   //⇒ 22302

hide hide() ⇒ self

Hide the elements by setting their display style property to none. For an animated version, see the fx_methods module.

html html() ⇒ string html(content) ⇒ self html(function(index, oldHtml){ ... }) ⇒ self

Get or set the HTML contents of elements. With no argument, returns the inner HTML of the first element; with content, sets it on all elements (replacing existing content).

// autolink everything that looks like a Twitter username
$('.comment p').html(function (idx, oldHtml) {
  return oldHtml.replace(/(^|\W)@(\w{1,15})/g,
    '$1@<a href="https://twitter.com/$2">$2</a>')
})

index index([element]) ⇒ number

Get the position of an element. When no argument is given, returns the position of the first element among its siblings. When an element is given, returns its position within the current collection (or -1 if not found).

$('li:nth-child(2)').index()  //⇒ 1

indexOf indexOf(element, [fromIndex]) ⇒ number

Get the position of an element inside the current collection, with native Array.prototype.indexOf semantics.

insertAfter insertAfter(target) ⇒ self

Insert elements of the current collection after the target element in the DOM. The inverse of after.

$('<p>Emphasis mine.</p>').insertAfter('blockquote')

insertBefore insertBefore(target) ⇒ self

Insert elements of the current collection before the target element in the DOM. The inverse of before.

$('<p>See the following table:</p>').insertBefore('table')

is is(selector) ⇒ boolean

Check if the first element of the current collection matches the CSS selector.

var input = $('input[type=text]')
input.is('#username')  //⇒ boolean

last last() ⇒ collection

Get the last element of the current collection.

$('li').last()

map map(function(index, item){ ... }) ⇒ collection

Iterate through all elements and collect the return values of the iterator function into a new Mepto collection. Inside the iterator, this refers to the current item. null and undefined results are excluded.

// get text contents of all buttons
$('button').map(function () {
  return $(this).text()
}).get().join(', ')

next next() ⇒ collection next(selector) ⇒ collection

Get the next sibling of each element, optionally filtered by a selector.

$('dl dt').next()  //⇒ the DD elements

not not(selector) ⇒ collection not(collection) ⇒ collection not(function(index){ ... }) ⇒ collection

Filter the current collection to get a new collection of elements that don't match the CSS selector, aren't in the given collection, or for which the function returns a falsy value. The inverse of filter.

$('input').not('[type=hidden]')

offset offset() ⇒ object offset(coordinates) ⇒ self offset(function(index, oldOffset){ ... }) ⇒ self

Get the position of the first element in the document, or set the position of every element relative to the document. The returned object has left, top, width, and height properties. When setting, pass an object with top and left properties (numbers are treated as pixels).

// position a tooltip relative to the document
$('#tooltip').offset({ top: 100, left: 200 })

offsetParent offsetParent() ⇒ collection

Find the first positioned ancestor element of each element in the collection — the element that top and left coordinates are relative to.

outerWidth outerWidth([includeMargin]) ⇒ number outerHeight([includeMargin]) ⇒ number Mepto extra

Get the border-box width or height of the first element (its offsetWidth/offsetHeight). Pass true to include margins. jQuery-compatible additions not present in Zepto.

parent parent([selector]) ⇒ collection

Get immediate parents of each element in the collection, optionally filtered by a selector.

$('input[type=text]').parent()  //⇒ parent form fields

parents parents([selector]) ⇒ collection

Get all ancestors of each element in the collection, optionally filtered by a selector. For the first matching ancestor, use closest instead.

$('.highlight').parents('div')  //⇒ all DIV ancestors

pluck pluck(property) ⇒ array

Read values of a property from each element of the collection, returning a plain array. null and undefined values are filtered out.

$('body > *').pluck('nodeName')  //⇒ [DIV, SCRIPT, P]
$('li').pluck('class')              //⇒ things like ["item", "selected"]

position position() ⇒ object

Get the position of the first element relative to its offset parent. The returned object has top and left properties. Returns undefined for an empty collection.

prepend prepend(content) ⇒ self

Prepend content to the DOM inside each element in the collection. Content can be an HTML string, a DOM node, or an array of nodes.

$('ul').prepend('<li>first list item</li>')

prependTo prependTo(target) ⇒ self

Prepend the elements of the current collection to the target element(s). The inverse of prepend.

$('<li>first list item</li>').prependTo('ul')

prev prev() ⇒ collection prev(selector) ⇒ collection

Get the previous sibling of each element, optionally filtered by a selector.

prop prop(name) ⇒ value prop(name, value) ⇒ self prop(name, function(index, oldValue){ ... }) ⇒ self

Read or set properties of DOM elements. Prefer this over attr for properties like checked or selectedIndex, whose values live on the node rather than in markup.

$('input[type=checkbox]').prop('checked', true)

push push(element, [element2, ...]) ⇒ number

Add elements to the end of the collection in place, with native Array.prototype.push semantics. See also sort and splice.

ready ready(function($){ ... }) ⇒ self

Attach an event handler that is executed when the DOM is ready. The handler receives the $ factory as its first argument.

$(document).ready(function () {
  // $('body') and friends are safe to use here
})

reduce reduce(function(memo, item, index, array){ ... }, [initial]) ⇒ value

Identical to the native Array.prototype.reduce method, iterating over the elements of the collection.

var total = $('input[type=number]').reduce(function (sum, el) {
  return sum + (Number(el.value) || 0)
}, 0)

remove remove() ⇒ self

Remove the elements of the current collection from the document.

$('button').remove()  //⇒ remove all buttons

removeAttr removeAttr(name) ⇒ self

Remove the specified attribute from all elements in the collection. Multiple attribute names can be given in a space-separated string.

removeClass removeClass(name) ⇒ self removeClass(function(index, oldClassName){ ... }) ⇒ self

Remove the specified CSS class name(s) from all elements in the collection. Multiple class names can be given in a space-separated string.

$('.selected').removeClass('selected')
$('#form').removeClass('edit focus')

removeProp removeProp(name) ⇒ self

Deletes the specified property from every element in the collection.

replaceWith replaceWith(content) ⇒ self

Replace each element in the collection with the given content — an HTML string, DOM node, or collection. Returns the original (now detached) elements.

$('.replace').replaceWith('<span>new content</span>')

scrollLeft scrollLeft() ⇒ number scrollLeft(value) ⇒ self

Gets or sets how many pixels the content of the first element (or the window) is scrolled horizontally.

scrollTop scrollTop() ⇒ number scrollTop(value) ⇒ self

Gets or sets how many pixels the content of the first element (or the window) is scrolled vertically.

show show() ⇒ self

Restore the default display property of each element, un-hiding them. For an animated version, see the fx_methods module.

siblings siblings([selector]) ⇒ collection

Get all sibling nodes of each element in the collection, optionally filtered by a selector.

singleClosest singleClosest(selector, [context]) ⇒ collection Mepto extra

Like closest, but only consults the first element of the collection and returns at most one element — mirroring the native Element.closest() semantics. A bridge toward vanilla JS.

size size() ⇒ number

Get the number of elements in this collection. Same as reading the length property.

slice slice(start, [end]) ⇒ collection

Extract a subset of the collection, starting at index start and ending (optionally) before index end. Negative indices count from the end.

sort sort([compareFunction]) ⇒ self

Sort the elements of the collection in place, with native Array.prototype.sort semantics.

splice splice(start, deleteCount, [items...]) ⇒ array

Remove or replace elements of the collection in place, with native Array.prototype.splice semantics.

text text() ⇒ string text(content) ⇒ self text(function(index, oldText){ ... }) ⇒ self

Get or set the text contents of elements. With no argument, returns the concatenated text of all elements; with content, sets the text (escaping any HTML) on all elements.

$('#foo').text('Hello!')
$('#foo').text()  //⇒ "Hello!"

toArray toArray() ⇒ array

Get all elements of the collection as a plain array. Same as calling get() without arguments.

toggle toggle([setting]) ⇒ self

Toggle between showing and hiding each element, based on its current display value. If setting is given, force show (true) or hide (false). For an animated version, see the fx_methods module.

toggleClass toggleClass(names, [when]) ⇒ self toggleClass(function(index, oldClassName){ ... }, [when]) ⇒ self

Toggle the given CSS class name(s) on each element: present names are removed, missing ones are added. If when is given, force adding (true) or removing (false) instead of toggling.

unwrap unwrap() ⇒ self

Remove the parents of each element, effectively putting the elements in place of their parent.

$(document.body).append('<div id=wrapper><p>Content</p></div>')
$('#wrapper p').unwrap().parents()  //⇒ [body, html]

val val() ⇒ string | array val(value) ⇒ self val(function(index, oldValue){ ... }) ⇒ self

Get or set the value of form elements. With no argument, returns the value of the first element — for <select multiple>, an array of the selected values.

$('input:text').val('hello')  // set
$('input:text').val()         // read

width width() ⇒ number width(value) ⇒ self width(function(index, oldWidth){ ... }) ⇒ self

Get the width of the first element in the collection, or set the width of all elements. Applied to window it returns the viewport width; applied to document it returns the full document width. See also outerWidth for the border-box size.

$('#foo').width()    //⇒ 123
$(window).width()    //⇒ 768 (viewport width)
$(document).width()  //⇒ 768

wrap wrap(structure) ⇒ self wrap(function(index){ ... }) ⇒ self

Wrap each element of the collection separately inside the given DOM structure. The structure can be a single element, nested elements, an HTML string, or a function returning one of those.

// wrap each button in a separate span
$('.buttons a').wrap('<span>')

// wrap each code block in a div and pre
$('code').wrap('<div class=highlight><pre /></div>')

wrapAll wrapAll(structure) ⇒ self

Wrap all elements of the collection, together, inside a single structure inserted before the first element.

// wrap all buttons in a single div
$('a.button').wrapAll('<div id=buttons />')

wrapInner wrapInner(structure) ⇒ self wrapInner(function(index){ ... }) ⇒ self

Wrap the contents of each element separately inside the given structure.

$('.nav a').wrapInner('<span>')
$('ol li').wrapInner('<p><em /></p>')

Event handling

$.Event $.Event(type, [properties]) ⇒ event

Create and initialize a DOM event of the specified type. If a properties object is given, use it to extend the new event object. By default, events are set to bubble; this can be turned off by setting bubbles: false.

$.Event('mylib:change', { bubbles: false })

$.proxy $.proxy(fn, context) ⇒ function $.proxy(fn, context, [additionalArguments...]) ⇒ function $.proxy(context, property) ⇒ function $.proxy(context, property, [additionalArguments...]) ⇒ function

Get a function that ensures that the value of this inside the original function is the given context object. Additional arguments are prepended to the arguments the proxy is later called with. In the second form, property names a method on the context object.

var obj = { name: 'mepto' }
var handler = function (greeting) {
  console.log(greeting + ' ' + this.name)
}
$(document).on('click', $.proxy(handler, obj, 'hello from'))

Event object

Mepto event handlers receive a native DOM event, normalized with jQuery-style helpers:

Returning false from a handler is equivalent to calling both preventDefault() and stopPropagation().

on on(type, function(e){ ... }) ⇒ self on(type, [data], function(e){ ... }) ⇒ self on(type, selector, [data], function(e){ ... }) ⇒ self on({ type: handler, type2: handler2, ... }, [selector], [data]) ⇒ self

Add event handlers to the elements of the collection. Multiple event types can be passed in a space-separated string, or as an object mapping event types to handlers. Events can be namespaced ('click.mepto') for selective removal.

When a selector is given, the handler is only invoked when an event from an element matching the selector bubbles up to the element in the collection — this is event delegation, and inside the handler this refers to the matching descendant.

$('#elem').on('click', function (e) {
  // handle clicks on the element
})

// delegate: handles clicks on current and future <li> items
$('#list').on('click', 'li', function (e) {
  console.log('clicked', $(this).text())
})

off off(type, [selector], function(e){ ... }) ⇒ self off({ type: handler, type2: handler2, ... }, [selector]) ⇒ self off(type, [selector]) ⇒ self off() ⇒ self

Detach event handlers added with on. To detach a specific handler, the same function reference must be passed. With no arguments, all handlers are removed; namespaces ('.mepto') let you remove whole groups.

one one(type, [data], function(e){ ... }) ⇒ self one(type, selector, [data], function(e){ ... }) ⇒ self

Add an event handler that only fires once on each element and is then removed. Accepts the same arguments as on.

trigger trigger(event, [args]) ⇒ self

Trigger the specified event on elements of the collection, as if it had occurred naturally: the event bubbles and default actions apply. The event can be a string type or an event object created with $.Event. Extra args are passed to the handler after the event object.

$(document.body).trigger('click')
$(document).trigger('mylib:change', ['first argument', 'second'])

triggerHandler triggerHandler(event, [args]) ⇒ value

Like trigger, but only calls the handlers registered via Mepto: no actual event is dispatched, the event doesn't bubble, and default actions (such as form submission or link navigation) don't occur. Returns the value of the last invoked handler.

Shortcut methods

Shorthand methods for binding the most common event types are available on every collection:

focusin focusout focus blur load resize scroll unload click dblclick
mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave
change select keydown keypress keyup error

Called with a function argument, they bind a handler (like on); called with no arguments, they trigger the event (like trigger):

$('form').submit(function (e) {
  e.preventDefault()
})
$('#save').click()  //⇒ trigger a click

bind / unbind deprecated bind(type, [data], function(e){ ... }) ⇒ self unbind(type, function(e){ ... }) ⇒ self

Deprecated jQuery-style aliases of on and off, kept for compatibility. Use on/off in new code.

delegate / undelegate deprecated delegate(selector, type, function(e){ ... }) ⇒ self undelegate(selector, type, function(e){ ... }) ⇒ self

Deprecated jQuery-style aliases of delegated on and off. Use on(type, selector, fn) in new code.

Note: Zepto's live() and die() were removed in Mepto — use delegated on/off instead.

Ajax requests

$.ajax $.ajax(options) ⇒ XMLHttpRequest

Perform an Ajax request. This is the most generic method; all the Ajax shortcuts below go through it. In Mepto the transport is built on fetch rather than XMLHttpRequest; the returned object is an XHR-shaped shim (with abort(), status, responseText, and getResponseHeader()) that is also a promise.

Options (all optional, defaults in $.ajaxSettings):

Callbacks:

The returned object also implements the promise interface — because the callbacks and deferred modules are always bundled, done, fail, always, and then are available:

$.ajax({
  type: 'POST',
  url: '/api/items',
  data: { name: 'frobnicator' },
  dataType: 'json',
  success: function (data) {
    console.log('created', data)
  }
})

// promise style
$.ajax('/api/items')
  .done(function (data) { console.log(data) })
  .fail(function (xhr, type) { console.error('failed:', type) })

To cancel a request in flight, call abort() on the returned object; the error callback fires with type "abort".

Ajax events

When global: true (the default), Ajax requests trigger these events on the context element (or on document when no context is set). Use them for activity indicators and global error handling:

$(document).on('ajaxStart', function () {
  $('#spinner').show()
}).on('ajaxStop', function () {
  $('#spinner').hide()
})

$.ajaxSettings

Object containing the default settings for $.ajax. Most defaults should be set per-request, but this is the place for app-wide defaults such as timeouts, headers, or disabling global events.

$.ajaxSettings.timeout = 5000

$.get $.get(url, function(data, status, xhr){ ... }) ⇒ XMLHttpRequest $.get(url, [data], [success], [dataType]) ⇒ XMLHttpRequest

Perform an Ajax GET request. Shorthand for $.ajax.

$.get('/whatevs.html', function (response) {
  $(document.body).append(response)
})

$.post $.post(url, [data], function(data, status, xhr){ ... }, [dataType]) ⇒ XMLHttpRequest

Perform an Ajax POST request. When dataType is "json", the response is parsed before being passed to the success callback.

$.post('/form', { email: 'ssoojj@example.com' }, function () {
  console.log('sent')
})

$.getJSON $.getJSON(url, function(data, status, xhr){ ... }) ⇒ XMLHttpRequest $.getJSON(url, [data], [success]) ⇒ XMLHttpRequest

Perform an Ajax GET request and parse the response as JSON.

$.getJSON('/awesome.json', function (data) {
  console.log(data)
})

// fetch JSON data from another domain with JSONP
$.getJSON('//example.com/awesome.json?callback=?', function (remoteData) {
  console.log(remoteData)
})

$.param $.param(object, [traditional]) ⇒ string

Serialize an object into a URL-encoded string for use in Ajax query strings. Nested objects and arrays are serialized recursively unless traditional is true.

$.param({ foo: { one: 1, two: 2 } })
//⇒ "foo[one]=1&foo[two]=2"

$.param({ ids: [1, 2, 3] })
//⇒ "ids[]=1&ids[]=2&ids[]=3"

$.param({ ids: [1, 2, 3] }, true)
//⇒ "ids=1&ids=2&ids=3"

$.ajaxJSONP deprecated $.ajaxJSONP(options) ⇒ mock XMLHttpRequest object

Perform a JSONP request via a dynamically inserted <script> tag. Deprecated: prefer $.ajax with dataType: "jsonp", or CORS-enabled JSON endpoints where the server allows them.

$.active $.active ⇒ number

The number of Ajax requests currently in flight. The ajaxStart/ajaxStop events are derived from this counter.

load load(url, function(data, status, xhr){ ... }) ⇒ self

Set the html contents of the current element(s) to the result of a GET Ajax call to the given URL. Optionally, a CSS selector can be specified in the URL, like so, to use only the matching content:

$('#some_element').load('/foo.html #bar')

If no CSS selector is given, the complete response text is used instead. Note that any examples loaded this way will not execute inline JavaScript — <script> tags are stripped when a selector is used.

Form

serialize serialize() ⇒ string

Serialize form values to a URL-encoded string for use in Ajax post requests. Fields that are disabled, of button/submit/reset/file type, or unchecked radio/checkbox inputs are skipped.

$('form').serialize()
//⇒ "name=mepto&version=2.0&target_browser=modern"

serializeArray serializeArray() ⇒ array

Serialize form values into an array of objects with name and value properties. Disabled controls, button/submit/reset/file inputs, and unchecked checkboxes/radio buttons are skipped. Does not serialize the form itself — select the fields or a form element with fields in it.

$('form').serializeArray()
//⇒ [{ name: 'greeting', value: 'hello' }, { name: 'num', value: 42 }]

submit submit() ⇒ self submit(function(e){ ... }) ⇒ self

Trigger or bind the submit event. When called with a callback, binds it (like on('submit', fn)); with no arguments, triggers the submit event on the first form and, unless it was cancelled, submits the form natively.

$('form').submit(function (e) {
  e.preventDefault()
  $.post('/form', $(this).serialize())
})
Back to top ↑