iOS Style Text Selection Plugin with jQuery

File Size: 3.28 KB
Views Total: 2609
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
iOS Style Text Selection Plugin with jQuery

iOS style text selection with custom handles built using jQuery, jQuery Lettering.js plugin and plain HTML & CSS.

How to use it:

1. Include the necessary jQuery JavaScript library on your webpage.

<script src="//code.jquery.com/jquery-2.2.0.min.js"></script>

2. The core JavaScript function.

(function($) {
  $.fn.selectBars = function(affectedText, targetText, selectionChangeEventHandler) {
      var isDragging = false;
      var draggingHandle = null;

      $(affectedText + ":contains('" + targetText + "')").html(function(_, html) {
          return html.replace(targetText, '<span class="sel-handle sel-s"></span><span class="sel-mid">' + targetText + '</span><span class="sel-handle sel-e"></span>');
      });

      $(affectedText).attr('data-selected', targetText);
      selectionChangeEventHandler.call(this);

      $(affectedText).lettering('letters');

      //start dragging
      $(affectedText).on('mousedown', '.sel-handle', function() {
          draggingHandle = $(this);
          isDragging = true;
      });

      //end the dragging
      $(document).mouseup(function() {
          isDragging = false;
      });

      //detect range change
      $('.char').mouseover(function() {
          //check to ensure order and dragging
          if (isDragging && !(draggingHandle.attr('class') == $('.sel-e').attr('class') && $(this).nextAll('.sel-s').length !== 0) && !(draggingHandle.attr('class') == $('.sel-s').attr('class') && $(this).prevAll('.sel-e').length !== 0)) {

              draggingHandle.remove();
              $(this).before(draggingHandle);
              $('.sel-mid').contents().unwrap();
              $('.sel-s').each(function() {
                  $(affectedText).attr('data-selected', $(this).nextUntil(".sel-e").text());
                  selectionChangeEventHandler.call(this);
                  $(this).nextUntil(".sel-e").wrapAll('<span class="sel-mid" />');
              });

              //text selection magic =)
              $(affectedText).append('<input style="display: hidden"/>');
              $('input').focus();
              $(affectedText + ' input').remove();
          }
      });
  };
}(jQuery));

3. The custom build of jQuery Lettering.js plugin.

(function(e) {
  var i = e.fn.lettering = function(d, f) {
          var b = e.extend({}, m, j[d] || d || j.letters, f);
          return this.each(function() {
              b.prep && b.prep(this);
              k.call(this, b);
              if (b.num) {
                  e(this).find(b.tag + '.' + b.cl.replace(/\s/g, '.')).addClass(function(a) {
                      return b.cl + (a + 1)
                  })
              }
          })
      },
      k = function(a) {
          var d = this,
              f = d.nodeType,
              b = a.split ? e(d).text().split(a.split) : f == 3 ? d.nodeValue.split('') : f == 1 ? d.childNodes : [],
              g, h = [],
              l = b.length;
          while (l--) {
              var c = b[l];
              if (c) {
                  if (typeof c == 'string') {
                      g = '';
                      if (a.addAttr) {
                          c = a.matAttr ? a.mapAttr.call(c) : c;
                          g = ' data-cont="' + (c == '"' ? '&quot;' : c) + '"'
                      }
                      h.push('<span class="' + a.cl + '"' + g + '>' + c + '</span>' + (a.after || ''))
                  } else {
                      k.call(c, a)
                  }
              }
          }
          h.length && e(d)[a.split ? 'html' : 'replaceWith'](h.reverse().join(''))
      },
      j = i.presets = {
          letters: {},
          kern: {
              addAttr: !0,
              num: !1
          },
          words: {
              split: /\s+/,
              cl: 'word',
              after: ' '
          },
          lines: {
              cl: 'line',
              prep: function(a) {
                  this.split = '|' + (new Date()).getTime() + '|';
                  e(a).find('br').replaceWith(this.split)
              }
          }
      },
      m = i.defaults = {
          tag: 'span',
          cl: 'char',
          num: !0
      }
})(jQuery);

4. Call the function on the text wrapper and set the selected text.

// selectBars(affectedText, targetText, selectionChangeEventHandler)
$(".text-wrapper").selectBars('.text-wrapper', 'ipsum', function(){
  // do something
});

5. Customize the handles with your own CSS styles.

.sel-mid { background-color: lightblue; }

.sel-handle {
  cursor: ew-resize;
  color: tomato;
  width: 1px;
  display: inline-block;
  overflow: visible;
  background-color: tomato;
  height: 18px;
  vertical-align: top;
  position: relative;
}

.sel-handle:before {
  content: '';
  display: block;
  background-color: tomato;
  width: 7px;
  height: 7px;
  position: absolute;
  left: -3px;
  top: -3px;
  border-radius: 100%;
}

This awesome jQuery plugin is developed by mattsich. For more Advanced Usages, please check the demo page or visit the official website.