morphext.js
91 lines
| 1 | /*! |
| 2 | * morphext - Text Rotating Plugin for jQuery |
| 3 | * https://github.com/ferbueno/morphext |
| 4 | * |
| 5 | * Built on jQuery Boilerplate |
| 6 | * http://jqueryboilerplate.com/ |
| 7 | */ |
| 8 | |
| 9 | (function ($) { |
| 10 | "use strict"; |
| 11 | |
| 12 | const pluginName = "morphext", |
| 13 | defaults = { |
| 14 | animation: "bounce", |
| 15 | speed: 2000, |
| 16 | autoInit: true, |
| 17 | phrases: [], |
| 18 | animateCssVersion: "4.1.1", |
| 19 | autoAttachAnimateCss: true, |
| 20 | }; |
| 21 | |
| 22 | function Plugin(element) { |
| 23 | this.element = $(element); |
| 24 | this._settings = $.extend( |
| 25 | {}, |
| 26 | defaults, |
| 27 | JSON.parse(this.element.attr("data-morphext-options")) |
| 28 | ); |
| 29 | this._defaults = defaults; |
| 30 | this._init(); |
| 31 | } |
| 32 | |
| 33 | Plugin.prototype = { |
| 34 | _init: function () { |
| 35 | this.element.addClass("morphext"); |
| 36 | |
| 37 | // Attach AnimateCSS |
| 38 | if (this._settings.autoAttachAnimateCss) { |
| 39 | const animateCssPath = `https://cdnjs.cloudflare.com/ajax/libs/animate.css/${this._settings.animateCssVersion}/animate.min.css`; |
| 40 | if (!$(`link[href='${animateCssPath}']`).length) { |
| 41 | $(`<link href="${animateCssPath}" rel="stylesheet">`).appendTo("head"); |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | this._index = 0; |
| 46 | this.animate(); |
| 47 | this.start(); |
| 48 | }, |
| 49 | animate: function () { |
| 50 | // Calculate the index |
| 51 | this._index = this._index % this._settings.phrases.length; |
| 52 | |
| 53 | // Create the span element |
| 54 | const innserSpan = document.createElement("span"); |
| 55 | |
| 56 | // Using plain vanilla to shorten method |
| 57 | innserSpan.classList.add( |
| 58 | "morphext__animated", |
| 59 | "animate__animated", |
| 60 | `animate__${this._settings.animation}` |
| 61 | ); |
| 62 | |
| 63 | // Add next phrase |
| 64 | $(innserSpan).text(this._settings.phrases[this._index]); |
| 65 | |
| 66 | // Attach the new element to the parent |
| 67 | this.element.html($(innserSpan).prop('outerHTML')); |
| 68 | |
| 69 | // Set next index |
| 70 | this._index += 1; |
| 71 | }, |
| 72 | start: function () { |
| 73 | var $that = this; |
| 74 | this._interval = setInterval(function () { |
| 75 | $that.animate(); |
| 76 | }, this._settings.speed); |
| 77 | }, |
| 78 | stop: function () { |
| 79 | this._interval = clearInterval(this._interval); |
| 80 | }, |
| 81 | }; |
| 82 | |
| 83 | $.fn[pluginName] = function (options) { |
| 84 | return this.each(function () { |
| 85 | if (!$.data(this, "plugin_" + pluginName)) { |
| 86 | $.data(this, "plugin_" + pluginName, new Plugin(this, options)); |
| 87 | } |
| 88 | }); |
| 89 | }; |
| 90 | })(jQuery); |
| 91 |