How to... Common Minified Tasks

Overview

  • Work with Selectors and Lists
  • Modify HTML Structure
  • Modify HTML Styles
  • Animation
  • Events
  • Forms and Data
  • Templates and Formats
  • Work with Selectors and Lists

    Find Elements

    Creating a list containing only the element with the id 'a':

    var l = $('#a');
    Creating a list containing only those element that have the class 'b':
    var l = $('.b');
    The default build of Minified uses the browser's built-in engine for selectors. If you chose a build with legacy Internet Explorer compatibility, you are limited to CSS1 selectors.

    API: $().
    JSFiddle Example: Selector

    Find All Child Elements

    Finding all child elements of the element '#parent':

    var l = $('*', '#parent', true);
    The selector '*' is used to select all child elements. The third argument, if true, limits matches to direct children of the context nodes, instead of matching all descendants.
    If you have an existing list, you can alternatively use select():
    var l = myList.select('*', true);

    API: $(), select().
    JSFiddle Example: Child Elements

    Find Child Nodes

    Finding all child nodes of the element '#parent' (ALL nodes, not only the elements):

    var l = $('#parent').collect(function(e) { return e.childNodes; });
    Use collect() to create a list that's derived from another one. Minified has no direct support for getting child nodes, so you need to work with this helper function here.

    API: $(), collect().

    Find Every Second Element

    Finding every second <li> element in '#parent':

    var l = $('#parent li').filter(function(e, index) { return index % 2; });
    The filter() function filters all elements that have an even index.

    API: $(), filter().
    JSFiddle Example: Filter

    Combine Lists

    If you have the Util module, use _():

    var l = _([list1, list2]);
    The Web module's $() is similar:
    var l = $([list1, list2]);
    The difference between both ways is that $() will automatically flatten nested lists and null elements will be removed. _() will not modify the lists but just concatenate them.
    You can also use the same syntax to add elements to the list:
    var l2 = _([list1, element1, element2]);
    or
    var l2 = $([list1, element1, element2]);
    Again, $() will remove null elements from the result, but _() will not.

    API: $().

    Find a Specific Parent

    var specialParent = $(child).up('.special');
    up() creates a list that contains the first node matching the selector while traversing up the element's parent elements.

    API: up().

    Check Whether an Element is a Parent

    var isParent = $(child).up(parent).length > 0;
    The easiest way to find out whether an element is a parent node is to use up() to travel up the parent chain. The parameter specifies that only parent matches. Thus you get an empty list if parent is not the parent of child, or a list containing parent if it is.

    There is an alternative way to do this, by selecting all descendants of the parent, but it is much slower in most situations:

    var isParent = $('*', parent).find(child) != null;

    API: find(), up().

    Get an Element's Next Sibling

    var siblings = myList.next();
    You can use next() to get the next sibling for each element in the list and include them in a new list. It also allows you to specify a selector for the elements and a maximum number of hits.

    API: next().

    Get an Element's Previous Sibling

    var siblings = myList.trav('previousSibling', 1);
    trav() is a generic tree traversal function that can traverse using any property. up() and next() are based on trav().

    API: trav(), up(), next().

    Abort an each() Loop

    Just use find() instead of each(), and return a value to abort:

    $('#parent input').find(function(input, index) { 
        if (input.value == '') {
            alert('You must enter something into all fields');
            return true;
        }
    });

    API: find().

    Modify HTML Structure

    Set Text Content

    $('#myElement').fill("My new text");
    The fill() method replaces an element's content with the given argument. If you pass a string, it will replace the old content with a new text node. You can also use it to add other elements as new content.

    API: fill().
    JSFiddle Example: fill()

    Read Text Content

    var textContent = $('#myElement').text();
    The text() method reads the text content of an HTML node. If you specify a list of nodes, or an element with nested elements, the content will be concatenated.

    API: text().

    Set InnerHTML

    $('.display').ht("My <b>HTML</b>");
    You can use ht() to set the innerHTML property of list members. HT stands for HTML template. It supports the full template() syntax and offers automatic HTML escaping:
    $('.name').ht("{{firstName}} <b>{{lastName}}</b>", {firstName: 'Mike', lastName: 'Bar'});
    Please note that ht() requires the complete Minfied distribution. If you only want to use the Web module, you need to resort to set() or using innerHTML directly:
    $('.display').set("innerHTML", "My <b>HTML</b>");
    $$('#myElement').innerHTML = "My <b>HTML</b>";

    API: ht(), set(), template(), $$().
    JSFiddle Examples: ht(), InnerHTML, Number Formats, Date Formats.

    Append HTML

    $('.myClass').add(HTML("<hr/>My Footer"));
    You can create one or more DOM nodes using HTML(). They can be added using add(), fill(), addFront() and other methods.

    HTML() supports the full template() syntax and and automatically escapes HTML:

    $('li.names').add(HTML(" <li>{{firstName}} {{lastName}}</li>", {firstName: 'Mike', lastName: 'Bar'}));

    Please note that HTML() requires the complete Minfied distribution. If you only want to use the Web module, you need to resort to set() or using innerHTML directly:

    $$('#myElement').innerHTML += "<hr/>My Footer";
    Modifing the innerHTML property like that is only possible when you modify a single element. If your list has more than one element, you need to write a set() callback like this:
    $('.display').set("innerHTML", function(old) {return old + "My <b>HTML</b>"; });

    API: add(), HTML(), set(), $$().
    JSFiddle Examples: HTML(), InnerHTML.

    Create HTML Elements

    var div = EE('div');
    Minified makes it easy to create DOM elements. The line above creates a simple <div> element, wrapped in a list:
    var actualDiv = div[0];
    The reason for the element being in a list is just that you can use the list to add event handlers or modify it in other ways. There is a number of methods to add elements, both in the list-wrapped form as well as the simple reference, to the DOM:
    $('.container').add(div);          // add as last child
    $('.container2').fill(div);        // replace all children
    $('.something').addFront(div);     // add as first child
    $('.something2').addBefore(div);   // add as sibling in front of..
    $('.something3').addAfter(div);    // add as sibling after..
    $('.oldElement').replace(div);     // replace element
    The elements created by EE() can receive an object containing set() arguments to set CSS classes, styles, attributes and properties. You can also either pass a string to set a text node as child, add another element factory with children, or a list that mixes both:
    $('.todo').add(EE('ol', {$: 'groceries'}, [
    	EE('li', 'Milk'),
    	EE('li', {$: 'important'}, 'Bread'},
    	EE('li', ['2x ', EE('a', {'@href': 'http://en.wikipedia.org/wiki/Twinkie'}, 'Twinkies'})])
    ]));
    
    The previous snippet will add the following HTML to all elements with the class .todo:
    <ol class='groceries'>
    	<li>Milk</li>
    	<li class='important'>Bread</li>
    	<li>2x <a href="http://en.wikipedia.org/wiki/Twinkie">Twinkies</a></li>
    </ol>
    

    An alternative to EE() is the HTML() function. It takes a HTML snippet and creates list-wrapped DOM nodes for it:

    $('.something').addFront(HTML('<b>important</b>'));
    HTML() also supports HTML templates with auto-HTML-escaping:
    $('.something').addFront(HTML('<b>{{firstName}} {{lastName}}</b>', {firstName: 'Tim', lastName: 'Taylor'}));

    API: add(), addAfter(), addBefore(), addFront(), EE(), HTML(), fill(), replace(), set().
    JSFiddle Example: EE and add()

    Add HTML Elements or Text

    $('.container').add('Some text');                        // add text node
    $('.container').add(EE('br'));                             // add <br> element
    $('.container').add(HTML('<br>'));                         // alternative syntax
    $('.container').add(document.createElement('br');          // another one
    $('.container').add(['Some text', EE('br'), 'More text']); // add text and elements at once
    
    Beside add(), you can use fill() to replace children or addAfter(), addBefore() and addFront() to position the elements relative to the list elements.

    API: add(), addAfter(), addBefore(), addFront(), EE(), fill(), HTML().
    JSFiddle Example: EE and add()

    Replace HTML Elements

    $('#oldElement').replace(EE('div', 'My new div'));
    replace() replaces the elements of the list with the given text or elements. It supports the same arguments as set().
    If you want to replace the children of an element, instead of the element itself, you can also use fill():
    $('#container').fill("New content.");

    API: add(), fill(), EE(), replace().

    Remove HTML Elements or Nodes

    $('.oldStuff').remove();
    Just use remove() to remove elements from the DOM tree.

    API: remove().

    Remove Children of HTML Elements

    $('.container').fill();
    Call fill() without arguments to remove all content of an element.

    API: fill().

    Get and Set Attributes

    $('a.someLink').set({'@href': 'http://minifiedjs.com'});
    Use set() with a '@'-prefixed name to set attributes. get() reads attributes with the same name syntax:
    var link = $('a.someLink').get('@href');
    For reading data attributes there's the special prefix '%' which makes it a bit shorter:
    var link = $('#myDiv').get('%extra'); // same as get('@data-extra')

    API: get(), set().

    Clone Elements

    var createSheep = $('.sheep').clone();
    clone() creates a copy of the list's elements, their attributes and text nodes. You can add the copy to the HTML document using add() and its variants:
    $('#destination').add(createSheep);

    API: add(), clone(), EE().
    JSFiddle Example: clone()

    Modify HTML Styles

    Add / Remove / Toggle CSS Classes

    $('.myClass').set('-oldClass +newClass toggleClass');
    If you call set() only with a string as argument, it will modify the elements' CSS classes. Several classes can be listed, separated by spaces. The prefix determines what to do:
    • "-" removes the CSS class
    • "+" adds it
    • no prefix toggles

    You can also call set() with the name "$" to do the same. This can be useful to modify several things at the same time:
    $('.myClass').set({$: '-oldClass', $display: 'block');

    Often it is simpler to create a toggle for CSS classes, as you can connect it directly to events:

    var toggle = $('.myClass').toggle('toggleClass');
    $('#toggleButton').on('click', toggle);
    $('#onButton').on('click', toggle, [true]);
    $('#offButton').on('click', toggle, [false]);

    API: set(), toggle().
    JSFiddle Example: CSS Classes

    Check for CSS Classes

    var isMyclass = $('#elem').is('.myclass');
    is() returns true if all list members match the given selector.

    API: is().
    JSFiddle Example: CSS Classes

    Get and Set CSS Style

    $('#someSpan').set({$backgroundColor: '#ff0'});
    Use set() with a '$'-prefixed name to set CSS styles. get() reads the effective CSS style of the first element in the list:
    var color = $('#someSpan').get('$backgroundColor');
    Please note that Minified uses camel case for CSS names, so it is "$backgroundColor", not "$background-color".

    API: get(), set().

    Get and Set Properties

    $('#someTextField').set({value: 'New text...'});
    Use set() with a unprefixed name to set properties. get() reads properties of the first element in the list:
    var value = $('#someTextField').get('value');

    API: get(), set().

    Animation

    Animate Styles and Properties

    $('.moving').animate({$width: '100px'}, 750);
    animate() shares the name/value syntax with set(), but will smoothly transition numbers and colors. You can specify the duration of the animation as well as the interpolation algorithm to be used.

    If you need to transition an object back and forth between two states, it is usually better to animate using toggle()

    var myToggle = $('.moving').toggle({$width: '100px'}, {$width: '200px'}, 750);
    
    $('#widthToggle').on('click', myToggle);
    $('#width100').on('click', myToggle, [false]);
    $('#width200').on('click', myToggle, [true]);
    

    API: animate(), set(), toggle().
    JSFiddle Example: Animation, Toggle

    Chain Animation Steps

    $('.colChanger').animate({$backgroundColor: '#f00'}, 750)
                         .then(function(list) {
    				return $('.colChanger').animate({$backgroundColor: '#0f0'}, 750)
    		     })
                         .then(function(list) {
    				$('.colChanger').animate({$backgroundColor: '#000'}, 750)
    		     });
    
    animate() returns a Promise that can be used to chain animate() invocations, so that you can start another animate() when the previous animation ended.

    API: animate(), Promise, then().
    JSFiddle Example: Animation Chain

    Toggle Styles and Properties

    var myToggle = $('.resizing).toggle({$width: '100px'}, {$width: '200px'}, 750);
    
    $('#widthToggle').on('click', myToggle);
    $('#width100').on('click', myToggle, [false]);
    $('#width200').on('click', myToggle, [true]);
    
    Toggles are functions that can toggle the state of a list's elements between two sets of values. You can go to a specific state by calling the toggle with a boolean, or toggle between the states by calling it either without arguments or with a non-boolean argument. Toggles are animated when you set a duration, but you can also skip the duration to toggle instantly.

    API: toggle().
    JSFiddle Example: Toggle, Fade/Slide Toggle

    Fade in / Fade Out (Animation)

    $('.myElem1').animate({$$fade: 1}, 500); // fade in
    $('.myElem2').animate({$$fade: 0}, 500); // fade out
    var fadeToggle = $('.myElem3').toggle({$$fade: 0}, {$$fade: 1}, 500);
    
    Use the virtual property $$fade to fade elements in and out.

    API: animate(), set(), toggle().
    JSFiddle Example: Fade/Slide Toggle

    Slide in / Slide Out (Animation)

    $('.myElem1').animate({$$slide: 1}, 500); // slide in
    $('.myElem2').animate({$$slide: 0}, 500); // slide out
    var slideToggle = $('.myElem3').toggle({$$slide: 0}, {$$slide: 1}, 500);
    
    Use the virtual property $$slide to slide elements in and out.

    API: animate(), set(), toggle().
    JSFiddle Example: Fade/Slide Toggle

    Create Complex Animations (Loop)

    $.loop(function(t) {
    	$('.swinging').set({$top: (100 + 50*Math.sin(2*Math.PI * t / 5000)) + 'px'});
    });
    For complex animations that can not be expressed with animate(), $.loop() allows you to register a function that will be invoked at a browser-controlled frame-rate. It uses the browser's requestAnimationFrame function if available.

    API: animate(), loop(), set().
    JSFiddle Example: Loop Animation

    Events

    Register / Unregister Event Handlers

    function buttonHandler(e) { 
    	window.alert('Button pressed. Unregister now.');
    	$.off(buttonHandler);
    }
    $('#myButton').on('click', buttonHandler);
    Use on() to register an event handler for one or more events. $.off() unregisters event handlers.
    Please note that on() is a bit different than other libraries' event registration: by default, Minified will disable event forwarding and the event's default action. If you want to allow event processing, you must prefix the event name with a pipe ('|'). A '?' prefix will let the handler decide whether to stop even processing. Return false to stop it.

    API: on(), off().

    Register for Mouseover Events

    function mouseoverHandler(isOver, index) { 
    	if (isOver)
    		console.log('is over element ', index);
    	else
    		console.log('left element ', index);
    }
    $('.activeSpots').onOver(mouseoverHandler);
    It is a bit difficult to set up mouseover events in a way that it works on all browsers, so Minified offers you onOver() as a convenient way to handle mouseover and mouseleave-like events. The handler is called with true if the mouse enters the element, and false when it leaves. onOver() prevents flickering - it is guaranteed that the handler is not called twice with the same value for the same element.
    As a bonus, because of the way the event handler is called, you can pass a toggle directly to onOver():
    $('#mySpot').onOver($('#mySpot').toggle({$color: 'white'}, {$color: 'red'}));

    API: onOver(), toggle().

    Monitor a Text Field

    $('#myNumber').onChange(function(newValue) { 
        $('#output').fill(newValue);
    });
    onChange() allows you to register a callback function that will be called the content of an input field changes. It also works with checkboxes and radio boxes.

    API: onChange().
    JSFiddle Example: onChange()

    Select Bubbled Events (Live/Delegates Events)

    $('#container').on('click', myHandler, 'div.monitored');
    Using an extra selector you can make on() limit events to those that bubbled up from elements described by the selector. This allows you to set up event handlers in parent elements and let events bubble up, so you need less (potentially resource-hungry) event handlers. Also, you may not need to add new event handlers when you add child elements to a monitored parent element, which is mostly useful if you work with innerHTML to add child elements.

    API: on().

    Trigger an Event

    $('#myElement').on('click', myHandler);
    $('#myElement').trigger('click', {msg: 'Just triggered it')});
    You can use trigger() to invoke any event handler previously registered using on(). The handler(s) will receive trigger()'s second parameter as event object.
    trigger() emulates event bubbling, but will not send a DOM event to the browser and thus does not emulate the event default behavior.

    API: on(), trigger().

    Create Custom Events

    $('#myElement').on('myOwnEventType', myHandler);
    $('#myElement').trigger('myOwnEventType', {msg: 'Just triggered it')});
    You can create your own event type by just making up a event type name and register for it using on(). They can then be triggered using trigger().

    API: on(), trigger().

    Forms and Data

    Do HTTP Requests (AJAX / XHR)

    $.request('post', '/example/service', {param1: 'hello', param2: 5})
        .then(function success(result) {
        	$('#result').fill(result);
        })
        .error(function(status, statusText, responseText) {
    		$('#result').fill('Got an error.');
    	});;
    $.request() executes HTTP requests asynchronously. You have to specify the method and URL to use, as well as data to send. For GET requests the data is either a map of parameters or a string to append to the URL. For POST requests, it can either be a map of form parameters, a string or XML. The result of the request is returned as a Promise.

    API: request(), Promise.
    JSFiddle Example: Request / JSON

    Read and Send a Form

    var result = $.request('post', '/example/service', $('#myForm').values());
    values() reads a HTML form and returns its data in a format that it can be send using a POST request with $.request(). Unlike real form submission, the browser will not leave the page when you use values().

    API: request(), values().

    Use JSON

    var jsonString = $.toJSON({a:1, b: 'test', c: [1, 2]});
    var obj = $.parseJSON(jsonString);
    $.toJSON() and $.parseJSON() convert between JSON strings and JavaScript structures. If you want to send JSON in an HTTP request, just convert the JavaScript structure to a string using $.toJSON(). To evaluate a JSON response, use $.parseJSON() for the conversion.

    API: parseJSON(), toJSON(), request().
    JSFiddle Example: Request / JSON

    Call a Rest-style URL

    $.request() only supports URL-parameters out of the box, but not parameters baked into the URL. If you need them, _.format() comes in handy:

    var url = _.format('http://myservice/weather/{{zip}}/dur/{{days}}/', {zip: 90210, days: 3}, escape);
    var response = $.request('get', url, {language: 'EN'});
    
    The example above creates a dynamic URL using _.format() and JavaScript's built-in escape function for URL escaping. It also adds a regular URL parameter language in the $.request() invokation. The URL to be invoked by $.request() is:
    http://myservice/weather/90210/dur/3/?language=EN

    API: _.format(), $.request().

    Read / Write / Delete Cookies

    $.setCookie('counter', (parseInt($.getCookie('counter')) || 0) + 1, 14); // 14 days valid 
    
    $.getCookie() and $.setCookie() allow you to read and write cookies. To delete a cookie, set an expiration date in the past like this:
    $.setCookie('numberOfVisits', '', -1);

    API: getCookie(), setCookie.

    Formats and Templates

    Format a Number

    var n1 = _.formatValue('#.###', Math.PI); // n1 == '3.142'
    var n2 = _.formatValue('0.00', 4.2);      // n2 == '4.20'
    var n3 = _.formatValue('0000', 51.7);     // n3 == '0052'
    var n4 = _.formatValue('###.###.###,0', 8426.47);  // n4 == '8.426,5'
    
    _.formatValue() formats a number into a string using the given format. '#' is used as a placeholder for optional digits, and '0' is a placeholder for digits that are required. As decimal separator and for grouping you can either use ',' or '.', as required for internationalization.

    API: _.formatValue().
    JSFiddle Example: Number Formats

    Format a Date

    var d1 = _.formatValue('YY/MM/dd', new Date()); // e.g. '13/10/21'
    var d2 = _.formatValue('HH:mm:ss', new Date()); // e.g. '21:30:02'
    var d3 = _.formatValue('n MM y', new Date());   // e.g. 'Oct 21 2013'
    var d4 = _.formatValue('yyyy-MM-ddTHH:mm:ss.SS z', new Date());  // e.g. '2013-10-21T21:30:02.977 +0200'
    
    _.formatValue() formats a Date into a string using the given format. Please consult the API docs for the meaning of the placeholders.

    API: _.formatValue().
    JSFiddle Example: Date Formats

    Parse a Date

    var d1 = _.formatValue('YY/MM/dd', '13/10/21');
    
    _.parseDate() parses the date in a string using a date format string that describes it. The format syntax is shared with _.formatDate(). Please consult the API docs for the meaning of the placeholders.

    API: _.formatValue(), _.parseValue().
    JSFiddle Example: Date Formats

    Create a Template

    var tpl = _.template('{{if title}}{{title}} {{/if}}{{firstName}} {{lastName}}');
    var fullName1 = tpl({title: 'Dr', firstName: 'Yevgeniy', lastName: 'Petrov'});
    var fullName2 = tpl({firstName: 'Libby', lastName: 'Kegler'});
    
    _.template() creates a template function that can be called with the template's arguments to create a string. Often it is more convenient to use _.format() which uses the same syntax but does not require the extra-step of invoking the template:
    var fullName = _.format('{{if title}}{{title}} {{/if}}{{firstName}} {{lastName}}', 
            {title: 'Dr', firstName: 'Yevgeniy', lastName: 'Petrov'});
    
    Minified caches all templates that it creates. Unless you create a very large number of templates, there is no noticable performance difference between _.template() and _.format().

    Minified has a few additional functions that work with templates:

    • formatHtml() adds HTML-escaping to _.format().
    • ht() replaces the HTML of DOM elements with the template's output.
    • HTML() creates DOM elements with a template.

    API: _.format(), _.formatHtml(), ht(), HTML(), _.template().

    Extend Minified

    Create New Modules

    define('makeGreen', function(require) {
        var MINI = require('minified'), $ = MINI.$; // private ref to Minified
        return function(list) {
            $(list).set({$color: '#0f0', $backgroundColor: '#050'});
        });
     });
     
     var makeGreen = require('makeGreen');
     makeGreen('.notGreenEnough');
     
    Minified publishes a simple define() function in the default context. It is backward-compatible to AMD, so your module will also be a valid AMD module, but does not support most of AMD's features. define() 'publishes' a reference that can later be obtained using require(). The callback given to define() will be called once to obtain the module.

    API: define(), require().

    Add Methods to Lists

    MINI.M.prototype.children = function() { return $('*', this, true); };
    var children = $('#parent').children();
    Minified's internal class for lists is exposed as MINI.M. This allows you to add new methods or modify existing methods.

    API: MINI.M.

    Add Functions to $ and _

    MINI.$.goTo = function(url) { window.location = url; };
    MINI._.isShorterThan = function(s, n) { return s == null || s.length < n; };
    
    if (_.isShorterThan(userInput, 5))
    	$.goTo('error.html');
    
    The objects exposed by Minified can easily be modified. There is only one instance and really no magic involved. Just extend them as you wish.

    Add prefixes to get() and set()

    MINI.getter['>'] = function(list, name) {
    	return list[0].getAttributeNS('http://www.w3.org/1999/xlink', name);
    };
    MINI.setter['>'] = function(list, name, value) {
    	list.each(function(obj, index) {
    		var v;
    		if (_.isFunction(value))
    			v = value(obj.getAttributeNS('http://www.w3.org/1999/xlink', name), index, obj);
    		else 
    			v = value;
    		if (v == null)
    			obj.removeAttributeNS('http://www.w3.org/1999/xlink', name);
    		else
    			obj.setAttributeNS('http://www.w3.org/1999/xlink', name, v);
    	});
    };
    
    MINI.getter and MINI.setter can be used to add additional prefixes for get() and set().

    API: MINI.getter, MINI.setter.

    Missing Something?

    Looking for something but can't find it here? Please write a mail to tim@tjansen.de ('Minified' in the subject to gets you past the spam filter).