jquery-utils.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import $ from 'jquery';
  2. import getSlug from 'speakingurl';
  3. // jQuery no parents filter
  4. $.expr[':']['noparents'] = $.expr.createPseudo((text) => (element) => $(element).parents(text).length < 1);
  5. // Slugify
  6. // CommonJS and ES6 version of https://github.com/madflow/jquery-slugify
  7. $.fn.slugify = (source, options) => {
  8. return this.each((element) => {
  9. let target = $(element);
  10. let source = $(source);
  11. target.on('keyup change', () => {
  12. target.data('locked', target.val() !== '' && target.val() !== undefined);
  13. });
  14. source.on('keyup change', () => {
  15. if (target.data('locked') === true) { return true; }
  16. let isInput = target.is('input') || target.is('textarea');
  17. target[isInput ? 'val' : 'text']($.slugify(source.val(), options));
  18. });
  19. });
  20. };
  21. // Static method.
  22. $.slugify = (sourceString, options) => {
  23. options = $.extend({}, $.slugify.options, options);
  24. options.lang = options.lang || $('html').prop('lang');
  25. if (typeof options.preSlug === 'function') {
  26. sourceString = options.preSlug(sourceString);
  27. }
  28. sourceString = options.slugFunc(sourceString, options);
  29. if (typeof options.postSlug === 'function') {
  30. sourceString = options.postSlug(sourceString);
  31. }
  32. return sourceString;
  33. };
  34. // Default plugin options
  35. $.slugify.options = {
  36. preSlug: null,
  37. postSlug: null,
  38. slugFunc: (input, opts) => getSlug(input, opts)
  39. };