Thursday, October 5, 2017

CLEditor, paste as plain text

CLEditor is an open source jQuery plug-in which provides a lightweight, full featured, cross browser, extensible, WYSIWYG HTML editor that can be easily added into any web site.

In order to prevent users to paste content with formatted text, and instead, get only its text the following chunk of cross-browser code:


var _$ta = $('textarea.richText').cleditor({ 
            // options
           }),
    _clEdit = _$ta.cleditor()[0];

$(_clEdit.$frame[0].contentWindow.document)
       .on('rightclick', function (e) {
             e.preventDefault();
       })
       .on('paste', function (e) { // Paste as plain text
           var content = '';
           e.preventDefault();
           if (e.originalEvent.clipboardData) {
               content = (e.originalEvent 
                   || e).clipboardData.getData('text/plain');
           }
           else if (window.clipboardData) {
               content = window.clipboardData.getData('Text');
           }
           content = content.replace(/\n/g, "<br />");
           _clEdit.execCommand('inserthtml', content);
        });

Wednesday, September 27, 2017

Get int or float number from a string

Number("this a test (12.75%)".match(/\d*\.*\d+/g)[0]); // Output: 12.75

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.