Tuesday, October 25, 2016

Sort DOM elements by jQuery

HTML:

<ul class="alphaList">
  <li>apples</li>
  <li>cats</li>
  <li>bears</li>
</ul>


JavaScript/jQuery:

var elems = $('.alphalist li').detach().sort(function (a, b) {
  return ($(a).text() < $(b).text() ? -1
        : $(a).text() > $(b).text() ? 1 : 0);
   });
$('.alphalist').append(elems);


Note: jQuery detach() gets (removing) elements from DOM.

Thursday, March 10, 2016

jQuery Custom Events

Custom events allow data interchange between different modules or classes running in the current page.
These events are delivered as a broadcast. They are invoked with a "trigger" method, and catched with the "on" method.
Parameters are optional. If there are more than one, these have to be embedded in an array, yet the target methods must declare those parameters individually.