Minified.js for JavaScript Developers

What is Minified.js?

  • Tiny JavaScript framework
    • Two modules: Web (jQuery-like features) and Util (Utility functions).
    • Modules can be used stand-alone (~4kB) or together (8kB)
    • allows even smaller builds using the Builder tool
  • Complete Feature Set
    • Selectors, HTML and CSS manipulation, animation
    • Events, JSON, Form serialization, HTTP Requests
    • List and string utilities, templates, promises
  • No Magic
    • Aims to be predictable
    • Never changes built-ins, no polyfills, no emulated properties
    • Simple, clean API without surprises

How to include Minified.js into your project

The quickest way to start is to download the distribution and refer to it in a script tag:

<script src="path/to/minified.js"></script>

Instead of loading it with a script tag, you could also use an AMD loader such as RequireJS or Sparkplug.js.

If you would like to optimize the size of your site, you should consider building a custom version and embedding Minified into your JavaScript code.

How to Obtain a Reference to Minified

No matter whether you are including Minified with a script tag or you use a synchronous loader like RequireJS, it is recommended to use the following lines to define the five essential references:

var MINI = require('minified');
var _=MINI._, $=MINI.$, $$=MINI.$$, EE=MINI.EE, HTML=MINI.HTML;
Please note that even if this may look like loading an AMD module, this works even without an AMD loader. Minified provides its own require function if no AMD loader is present.

Running Your Script at the Right Time

When you just include your script at the top of the page, you will not be able to reference HTML elements that are defined down below. A simple solution is to execute the script in a ready-handler like this:

var MINI = require('minified');
var _=MINI._, $=MINI.$, $$=MINI.$$, EE=MINI.EE, HTML=MINI.HTML;

$(function() {
	// PUT YOUR CODE HERE
});

Creating a List of DOM Elements

The first step to doing almost anything with Minified is to create a Minified list, an array-like class where most of Minified's functions are stored.

You can create a Minified list using CSS selectors with the familiar jQuery-syntax:

var MINI = require('minified');
var _=MINI._, $=MINI.$, $$=MINI.$$, EE=MINI.EE, HTML=MINI.HTML;

$(function() {
	var listItems = $('#myList li');
});
With the default Minified build you are using browser's CSS engine directly and have access to all its features. If you are working with a version that comes with IE6/IE7 compatibility, you can only use CSS1 selectors without pseudo-classes.

Here some more examples of valid selectors:

$('#myElement');   
$('.myClass');
$('#divA, #divB, #divC');
$('#top .section li');
$('*'); // all elements

You can also make a Minified list out of a DOM node or a list of DOM nodes. Nested lists will automatically be flattened. Nulls in lists will be omitted.

var singleElement = $(document.getElementById('oldFashioned'));
var threeElements = $([e1, e2, e3]);
var fourElements = $([[e1, e2], [e3, e4]]);
var plus1 = $([$('.myClass'), extraElement]);

Selectors can have a context. If a context is set, you limit the result set to those elements whose parent is one of the context nodes. The context can be specified in the same way as the selector itself, using a selector string, a DOM node or a list of nodes:

var cells = $('td, th', '#myTable'); // all td and th element in #myTable
var cells1 = $('td, th', document.getElementById('myTable')); // same as above

var cells2 = $('td, th', '.specialTable'); // all td and th element in .specialTable elements

To limit the context and use only direct children, instead of all descendants, set the third parameter to true:

var listItems = $('li', 'ol', true); // all list items in ordered lists

Other frameworks have a large selection of pseudo-classes and list-functions, but Minified has only few, powerful functions instead. You should take a look at the documentation for collect, filter and find for more information. Here a small example to give you an idea:

var r = $('#myTable tr')                                                         // all rows in myTable
           .filter(function(elem, index) { return index % 2 == 1; })             // filter: take only odd rows
           .collect(function(elem) { return $('td', elem).sub(-3); })            // use the last three cells per row
           .find(function(elem) { if ($(elem).is('.hit')) return elem; });       // find first cell with class 'hit'

The lists returned by the selectors behave pretty much like arrays. You can access them by index and they have a length property. Please note that you should not modify a list using the index operator ("list[i]") though. The result would be undefined.

This example iterates through a list using a for loop:

var list = $('input'); 
for (var i = 0; i < list.length ; i++)
    list[i].value = '';
Alternatively, you could use the Minified's each() function:
var list = $('input'); 
list.each(function(element, index) {
    element.value = '';
});

A special variant of the selector function $() is $$(). It works like $(), but returns only the first element of the list instead of the complete list. If the list is empty, it returns undefined.

var parent1 = $$('#myElement').parentNode;
var parent2 = $('#myElement')[0].parentNode;     // same result: $$() is just short for $()[0]

Creating Generic Minfied lists

Minified has two constructors for Minified lists. The previous sections showed $(), which is designed to create lists of DOM nodes and is contained in the Web module. The Util module contains a second constructor, _(). It supports varargs, does not remove nulls and flattens only the first level of lists. Selectors are not supported by _().

_(1, 2, 3, 4, 5);         // list contains numbers 1 to 5   
_([1, 2, 3, 4, 5]);       // same content!    
_([1, 2], [3, 4], 5);     // same content!!
_([[1, 2], [3, 4], [5]]); // different content: contains three arrays [1,2], [3,4] and [5]!
No matter whether you use the $() constructor or _(), you will always get the same type of list and have access to all list methods that are available in the distribution that you use.

Universal get() and set()

Whereas other frameworks have a number of different functions to access properties, attributes and CSS styles, Minified has only two: get() and set(). You define what data you access by prefixing the property name. Many other features, from animation to element creation, are built on the same property syntax.

The easiest data to access is a regular JavaScript property. You pass the plain property name to get or set it:

var oldGreeting = $('.greeting').get('innerHTML'); // value of list's first element!
alert(oldGreeting);
$('.greeting').set('innerHTML', 'Hello'); // sets innerHTML for all list elements!

For attributes, prefix the name with a '@':

var oldValue = $('input').get('@value');
$('input').set('@value', 'Hello');

To set or get a CSS style, prefix the name with a '$' and specify it in camelCase:

var oldColor = $('.greeting').get('$backgroundColor');
$('.greeting').set('$backgroundColor', 'blue');

It is possible, of course, set more than one property at once using a map:

$('.greeting').set({innerHTML: 'Hello', 
                    '@title': 'Greeting',
                    $marginTop: '10px'});

You can retrieve a map of values by specifying a list or map of names:

var margins = $('.greeting').get(['$marginTop', '$marginRight', '$marginBottom', '$marginLeft']);

Minified also uses set() to modify CSS classes. If you need to overwrite the existing classes, you could always set them with the className property of the element. For more complex operations, set() provides you with the name $. But since it is the most important set() operation, you can omit it and write:

$('.cnt').set('+highlighted -plain'); // add / remove CSS class
The argument is a space-separated list of class names. Those prefixed with '+' will be added and names prefixed with '-' will be removed. A class name without prefix will be toggled:
$('.cnt').set('selection'); // toggle CSS class

The name $ only becomes important if you want to set CSS classes and other properties at the same time:

$('#msg').set({innerHTML: 'none', 
               $: 'selection -special +none'}); // toggle 'selection', remove 'special', add 'none'

Minified has several 'virtual' properties, for example $$fade and $$slide. They are mostly useful for animation (see below), but can be used by get() and set() as well. $$fade is a number between 0 and 1 that specifies the opacity of an element, allowing you to fade elements in and out. $$slide is a number between 0 and 1 that represents the vertical size of an element relative to its 'natural' size, so you can slide elements in and out.

$('#dialog').set({$$fade: 0.5,    // half-transparent
                  $$slide: 0.5}); // only upper half shown 

Instead of just setting the value with set(), the old value value can be modified with a callback:

$('#e1').set('innerHTML', function(oldValue, index, obj) { return oldValue.replace(/hello/i, 'Hi'); });

The most powerful method of the set() family is animate(). animate() will find out the old values using get(), and then start an animation loop to transition to the given destination values. The following example moves elements from position 0px to 80px in 750 milliseconds:

$('.moving').set({$left: '0px'})
            .animate({$left: '80px'}, 750);

Using $$fade and $$slide you can make elements appear and disappear:

$('.fading').animate({$$fade: 0}, 1000);
Please see the animate() documentation for details, as animate() has a number of additional features.

Creating and Modifying HTML

The most important methods for modifying HTML are fill() and add(). fill() replaces the element's children with the given nodes, and add() just adds them as children.

If you call fill() without arguments, it removes all children from the list elements:

$('.myClass').fill();   // remove all children

Call fill() or add() with a string to create a new text node and add it:

$('.greetings').fill("Hello");        // Replace children with text "Hello"
$('.greetings').add("and Goodbye");  // add a second text node

If you want to add a new element, you can use either EE() or HTML() to create it. EE() creates a list containing an element. Optionally they can also add children to the new element, as well as attributes and everything else that is supported by set().

var MINI = require('minified');
var $=MINI.$, EE=MINI.EE, HTML=MINI.HTML;

$('#header').fill(EE('h2', 'My Title'));                                  // creates <h2>MyTitle</h2>
$('#linkContainer').fill(EE('a', {'@href': 'http://acme.com'}, "ACME"));  // creates <a href="http://acme.com">ACME</a>
$('#header').add([EE('br'), "Single line", EE('br')]);                    // add <br/>Single line<br/>
$('#list').fill(EE('ul', [                        // <ul>
            EE('li', {$: 'first'}, "First item"), // <li class="first">First Item</li>
            EE('li', "Second item"),              // <li>Second Item</li>
            EE('li', "Third item"),               // <li>Third Item</li>
]));                                              // </ul>
HTML() does the same, but uses a HTML string to create the elements:
var MINI = require('minified');
var $=MINI.$, EE=MINI.EE, HTML=MINI.HTML;

$('#header').fill(HTML('<h2>My Title</h2>'));
$('#linkContainer').fill(HTML('<a href="http://acme.com">ACME</a>'));
$('#header').add([HTML('<br/>'), "Single line", HTML('<br/>')]);
$('#list').fill(HTML('<ul>'+
            '<li class="first">First item</li>'+
            '<li>Second item</li>'+
            '<li>Third item</li>'+
'</ul>'));
HTML can not only handle HTML strings, but supports Minified templates:
var nameList = ['Joe', 'James', 'Jim', 'Jumbo'];
$('#list').fill(HTML('<ul>'+
                     '{{each names}}<li>{{this}}</li>{{/each}}'+
                     '</ul>', {names: nameList}));
Please refer to the template() API documentation for the full template syntax.

Beside fill() and add(), there are a few more functions for adding or removing nodes:

$('#d').addFront('Read this first!');         // add as first child
$('#e').addAfter([EE('hr'), 'My Footer']);    // add directly after #e
$('#f').addBefore(HTML('<h1>My Title</h1>')); // add in front of #f
$('#oldH2').replace(EE('h2', 'New Title'));   // replace #oldH2 with the new <h2>
$('#oldH3').remove();                         // remove #oldH3 without substitution

Events

Events in Minified may a bit different than what you are used to. At first sight it looks very familiar:

$('#submitButton').on('click', function() {
	alert('Button pressed!');
});
What you don't see here is that Minified will always disable the default behavior and prevent bubbling by default, by calling the browser's preventDefault() and stopPropagation() functions or their respective Internet Explorer equivalents. This means that if you add an event handler to a form submit button, the button will not submit the form anymore, unless you explicitly allow it. Similarly, a click handler on a link would prevent the link from changing the page.

If you want to keep the browser's default action or allow bubbling, you have two options. Either you prefix the event name with a '|' (pipe) :

$('#submitButton').on('|click', function() {
	alert('Button pressed, will submit now!');
});

Or you can keep the default behavior by prefixing the name with a '?' (question mark) and let the handler return true:

$('#submitButton').on('?click', function() {
	return confirm('Button pressed, really submit?');
});

By default, Minified will supply two arguments to the event handler:

$('#myDiv').on('click', function(e, index) {
	console.log('Clicked x=' + xe.pageX, 'y=' + xe.pageY, 'button='+xe.right?'right':'left');
});
The first argument is the unmodified event object, as provided by the browser. The second argument contains the index of the element in the list for which the event handler has been called. In the previous example, it was always 0. But consider this:
$('ol.myList li').on('click', function(e, index) {
	console.log('Clicked on list item no', index, ' with content:', this.text());
});
The index often makes it easy to identify which element has been clicked when you set an event handler for a whole list. this refers to a Minified list that contains the event source as its only element.

Often all you want to do when an event has been fired is to call the right function with the corresponding arguments. Minified makes this easy by allowing you to customize the arguments being passed to an event handler:

function setZoomLevel(percentage) {
   // ...
}
$('#smallButton').on('click', setZoomLevel, [50]);
$('#normalButton').on('click', setZoomLevel, [100]);
$('#largeButton').on('click', setZoomLevel, [150]);

As you have seen above, it's pretty common to register for 'click' events. That's why there is a special method just for the click event:

$('#smallButton').onClick(setZoomLevel, [50]);

There are several additional 'smart' events that may be useful to to you:

  • onChange() notifies you when the value of an input field or checkbox changes.
  • onOver() tracks whether the mouse is hovering over an element.
  • onFocus() tracks whether an element has the focus.

Event handlers can be removed using the function off(). off() is a global function that removes the handler function from all events and all elements it has been registered for.

$.off(setZoomLevel);

Toggles

A toggle is a function that can switch between two states. The states are defined as two set() maps. The following example creates a toggle that changes the background color of the <body> element:

var light = $('body').toggle(
 {$backgroundColor: '#000'},   // state 1
 {$backgroundColor: '#fff'}    // state 2
);
Upon creation, the toggle sets the first state. When you call the toggle function with a boolean true as argument, it switches to the second state and sets the background color accordingly. Call it with false and it switches to the first one. If you call it without arguments (or any other argument than a boolean true or false), the toggle function will toggle between the first and second state.
light();       // toggle background color
light(true);   // turn on the light  (state 2)
light(false);  // turn the light off (state 1)

So if you want to toggle the background color by clicking on a button, you only need to add the toggle function as event handler:

$('#switch').onClick(light);

By passing boolean arguments to the toggle function you can define a specific state for an event:

$('#switchOn') .onClick(light, [true]);
$('#switchOff').onClick(light, [false]);

Toggles can also be animated. Just pass the duration as additional parameter:

var dimmer = $('body').toggle(
 {$backgroundColor: '#000'},  // light off
 {$backgroundColor: '#fff'},  // light on
 750                          // 750ms
);

All properties supported by set() can be toggled, including CSS classes:

var highlighter = $('.marked').toggle(
  {$: '-highlighted'},
  {$: '+highlighted'}
);

You can also use the abbreviated set() syntax for CSS classes:

var highlighter2 = $('.marked').toggle('-highlighted', '+highlighted');
But because toggling CSS classes is so common, there is an even shorter syntax to create a toggle that's identical to the previous toggle:
var highlighter3 = $('.marked').toggle('highlighted');  // toggle CSS class 'highlighted'

HTTP Requests

Minified provides you with a friendly XmlHTTPRequest wrapper that includes Internet Explorer backward compatibility. The function $.request() can be used for GET, POST and all other asynchronous HTTP requests:

$.request('get', 'http://example.org/weatherService', {zip: 90210})
 .then(function success(txt) {
        alert("Got from service: " + txt);
    },
    function error(status, statusText, responseText) {
        alert("Error accessing service.");
    });
The third argument is a map containing parameters that, when set, will be automatically added as URL parameters. So the actual URL being called in the previous example is http://example.org/weatherService?zip=90210.
$.request() returns a Promise that you can use to register handlers for success and error.

POST requests are very similar and use the same syntax. The main difference is that the map in the third argument will now be used in the POST's body and not in the URL:

$.request('post', 'http://example.org/weatherService', {zip: 90210})
 .then(function success(txt) {
        alert("Got from service: " + txt);
    },
    function error(status, statusText, responseText) {
        alert("Error accessing service.");
    });

POST also allows you to specify an XML document or a string as data. The latter option can be used for transmitting JSON objects. The next example transmits the data in JSON form to the imaginary service and then treats the result also as JSON object:

$.request('post', 'http://example.org/weatherService', 
    $.toJSON({zip: 90210}))
  .then(function success(txt) {
        var data = $.parseJSON(txt);
        alert("Today's temperature: " + data.today.temperature);
    },
    function error(status, statusText, responseText) {
        alert("Error accessing service.");
    });

End

I hope this tutorial was helpful for you to get started with Minified development. If you want to read more, I would suggest the How-To or to look through the JSFiddle Examples.

back to Minified documentation.