jquery.marquee.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /**
  2. * jQuery.marquee - scrolling text like old marquee element
  3. * @author Aamir Afridi - aamirafridi(at)gmail(dot)com / http://aamirafridi.com/jquery/jquery-marquee-plugin
  4. */;
  5. (function($) {
  6. $.fn.marquee = function(options) {
  7. return this.each(function() {
  8. // Extend the options if any provided
  9. var o = $.extend({}, $.fn.marquee.defaults, options),
  10. $this = $(this),
  11. $marqueeWrapper, containerWidth, animationCss, verticalDir, elWidth,
  12. loopCount = 3,
  13. playState = 'animation-play-state',
  14. css3AnimationIsSupported = false,
  15. // Private methods
  16. _prefixedEvent = function(element, type, callback) {
  17. var pfx = ["webkit", "moz", "MS", "o", ""];
  18. for (var p = 0; p < pfx.length; p++) {
  19. if (!pfx[p]) type = type.toLowerCase();
  20. element.addEventListener(pfx[p] + type, callback, false);
  21. }
  22. },
  23. _objToString = function(obj) {
  24. var tabjson = [];
  25. for (var p in obj) {
  26. if (obj.hasOwnProperty(p)) {
  27. tabjson.push(p + ':' + obj[p]);
  28. }
  29. }
  30. tabjson.push();
  31. return '{' + tabjson.join(',') + '}';
  32. },
  33. _startAnimationWithDelay = function() {
  34. $this.timer = setTimeout(animate, o.delayBeforeStart);
  35. },
  36. // Public methods
  37. methods = {
  38. pause: function() {
  39. if (css3AnimationIsSupported && o.allowCss3Support) {
  40. $marqueeWrapper.css(playState, 'paused');
  41. } else {
  42. // pause using pause plugin
  43. if ($.fn.pause) {
  44. $marqueeWrapper.pause();
  45. }
  46. }
  47. // save the status
  48. $this.data('runningStatus', 'paused');
  49. // fire event
  50. $this.trigger('paused');
  51. },
  52. resume: function() {
  53. // resume using css3
  54. if (css3AnimationIsSupported && o.allowCss3Support) {
  55. $marqueeWrapper.css(playState, 'running');
  56. } else {
  57. // resume using pause plugin
  58. if ($.fn.resume) {
  59. $marqueeWrapper.resume();
  60. }
  61. }
  62. // save the status
  63. $this.data('runningStatus', 'resumed');
  64. // fire event
  65. $this.trigger('resumed');
  66. },
  67. toggle: function() {
  68. methods[$this.data('runningStatus') == 'resumed' ? 'pause' : 'resume']();
  69. },
  70. destroy: function() {
  71. // Clear timer
  72. clearTimeout($this.timer);
  73. // Unbind all events
  74. $this.find("*").addBack().off();
  75. // Just unwrap the elements that has been added using this plugin
  76. $this.html($this.find('.js-marquee:first').html());
  77. }
  78. };
  79. // Check for methods
  80. if (typeof options === 'string') {
  81. if ($.isFunction(methods[options])) {
  82. // Following two IF statements to support public methods
  83. if (!$marqueeWrapper) {
  84. $marqueeWrapper = $this.find('.js-marquee-wrapper');
  85. }
  86. if ($this.data('css3AnimationIsSupported') === true) {
  87. css3AnimationIsSupported = true;
  88. }
  89. methods[options]();
  90. }
  91. return;
  92. }
  93. /* Check if element has data attributes. They have top priority
  94. For details https://twitter.com/aamirafridi/status/403848044069679104 - Can't find a better solution :/
  95. jQuery 1.3.2 doesn't support $.data().KEY hence writting the following */
  96. var dataAttributes = {},
  97. attr;
  98. $.each(o, function(key, value) {
  99. // Check if element has this data attribute
  100. attr = $this.attr('data-' + key);
  101. if (typeof attr !== 'undefined') {
  102. // Now check if value is boolean or not
  103. switch (attr) {
  104. case 'true':
  105. attr = true;
  106. break;
  107. case 'false':
  108. attr = false;
  109. break;
  110. }
  111. o[key] = attr;
  112. }
  113. });
  114. // Reintroduce speed as an option. It calculates duration as a factor of the container width
  115. // measured in pixels per second.
  116. if (o.speed) {
  117. o.duration = parseInt($this.width(), 10) / o.speed * 1000;
  118. }
  119. // Shortcut to see if direction is upward or downward
  120. verticalDir = o.direction == 'up' || o.direction == 'down';
  121. // no gap if not duplicated
  122. o.gap = o.duplicated ? parseInt(o.gap) : 0;
  123. // wrap inner content into a div
  124. $this.wrapInner('<div class="js-marquee"></div>');
  125. // Make copy of the element
  126. var $el = $this.find('.js-marquee').css({
  127. 'margin-right': o.gap,
  128. 'float': 'left'
  129. });
  130. if (o.duplicated) {
  131. $el.clone(true).appendTo($this);
  132. }
  133. // wrap both inner elements into one div
  134. $this.wrapInner('<div style="width:100000px" class="js-marquee-wrapper"></div>');
  135. // Save the reference of the wrapper
  136. $marqueeWrapper = $this.find('.js-marquee-wrapper');
  137. // If direction is up or down, get the height of main element
  138. if (verticalDir) {
  139. var containerHeight = $this.height();
  140. $marqueeWrapper.removeAttr('style');
  141. $this.height(containerHeight);
  142. // Change the CSS for js-marquee element
  143. $this.find('.js-marquee').css({
  144. 'float': 'none',
  145. 'margin-bottom': o.gap,
  146. 'margin-right': 0
  147. });
  148. // Remove bottom margin from 2nd element if duplicated
  149. if (o.duplicated) $this.find('.js-marquee:last').css({
  150. 'margin-bottom': 0
  151. });
  152. var elHeight = $this.find('.js-marquee:first').height() + o.gap;
  153. // adjust the animation duration according to the text length
  154. if (o.startVisible && !o.duplicated) {
  155. // Compute the complete animation duration and save it for later reference
  156. // formula is to: (Height of the text node + height of the main container / Height of the main container) * duration;
  157. o._completeDuration = ((parseInt(elHeight, 10) + parseInt(containerHeight, 10)) / parseInt(containerHeight, 10)) * o.duration;
  158. // formula is to: (Height of the text node / height of the main container) * duration
  159. o.duration = (parseInt(elHeight, 10) / parseInt(containerHeight, 10)) * o.duration;
  160. } else {
  161. // formula is to: (Height of the text node + height of the main container / Height of the main container) * duration;
  162. o.duration = ((parseInt(elHeight, 10) + parseInt(containerHeight, 10)) / parseInt(containerHeight, 10)) * o.duration;
  163. }
  164. } else {
  165. // Save the width of the each element so we can use it in animation
  166. elWidth = $this.find('.js-marquee:first').width() + o.gap;
  167. // container width
  168. containerWidth = $this.width();
  169. // adjust the animation duration according to the text length
  170. if (o.startVisible && !o.duplicated) {
  171. // Compute the complete animation duration and save it for later reference
  172. // formula is to: (Width of the text node + width of the main container / Width of the main container) * duration;
  173. o._completeDuration = ((parseInt(elWidth, 10) + parseInt(containerWidth, 10)) / parseInt(containerWidth, 10)) * o.duration;
  174. // (Width of the text node / width of the main container) * duration
  175. o.duration = (parseInt(elWidth, 10) / parseInt(containerWidth, 10)) * o.duration;
  176. } else {
  177. // formula is to: (Width of the text node + width of the main container / Width of the main container) * duration;
  178. o.duration = ((parseInt(elWidth, 10) + parseInt(containerWidth, 10)) / parseInt(containerWidth, 10)) * o.duration;
  179. }
  180. }
  181. // if duplicated then reduce the duration
  182. if (o.duplicated) {
  183. o.duration = o.duration / 2;
  184. }
  185. if (o.allowCss3Support) {
  186. var
  187. elm = document.body || document.createElement('div'),
  188. animationName = 'marqueeAnimation-' + Math.floor(Math.random() * 10000000),
  189. domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
  190. animationString = 'animation',
  191. animationCss3Str = '',
  192. keyframeString = '';
  193. // Check css3 support
  194. if (elm.style.animation !== undefined) {
  195. keyframeString = '@keyframes ' + animationName + ' ';
  196. css3AnimationIsSupported = true;
  197. }
  198. if (css3AnimationIsSupported === false) {
  199. for (var i = 0; i < domPrefixes.length; i++) {
  200. if (elm.style[domPrefixes[i] + 'AnimationName'] !== undefined) {
  201. var prefix = '-' + domPrefixes[i].toLowerCase() + '-';
  202. animationString = prefix + animationString;
  203. playState = prefix + playState;
  204. keyframeString = '@' + prefix + 'keyframes ' + animationName + ' ';
  205. css3AnimationIsSupported = true;
  206. break;
  207. }
  208. }
  209. }
  210. if (css3AnimationIsSupported) {
  211. animationCss3Str = animationName + ' ' + o.duration / 1000 + 's ' + o.delayBeforeStart / 1000 + 's infinite ' + o.css3easing;
  212. $this.data('css3AnimationIsSupported', true);
  213. }
  214. }
  215. var _rePositionVertically = function() {
  216. $marqueeWrapper.css('transform', 'translateY(' + (o.direction == 'up' ? containerHeight + 'px' : '-' + elHeight + 'px') + ')');
  217. },
  218. _rePositionHorizontally = function() {
  219. $marqueeWrapper.css('transform', 'translateX(' + (o.direction == 'left' ? containerWidth + 'px' : '-' + elWidth + 'px') + ')');
  220. };
  221. // if duplicated option is set to true than position the wrapper
  222. if (o.duplicated) {
  223. if (verticalDir) {
  224. if (o.startVisible) {
  225. $marqueeWrapper.css('transform', 'translateY(0)');
  226. } else {
  227. $marqueeWrapper.css('transform', 'translateY(' + (o.direction == 'up' ? containerHeight + 'px' : '-' + ((elHeight * 2) - o.gap) + 'px') + ')');
  228. }
  229. } else {
  230. if (o.startVisible) {
  231. $marqueeWrapper.css('transform', 'translateX(0)');
  232. } else {
  233. $marqueeWrapper.css('transform', 'translateX(' + (o.direction == 'left' ? containerWidth + 'px' : '-' + ((elWidth * 2) - o.gap) + 'px') + ')');
  234. }
  235. }
  236. // If the text starts out visible we can skip the two initial loops
  237. if (!o.startVisible) {
  238. loopCount = 1;
  239. }
  240. } else if (o.startVisible) {
  241. // We only have two different loops if marquee is duplicated and starts visible
  242. loopCount = 2;
  243. } else {
  244. if (verticalDir) {
  245. _rePositionVertically();
  246. } else {
  247. _rePositionHorizontally();
  248. }
  249. }
  250. // Animate recursive method
  251. var animate = function() {
  252. if (o.duplicated) {
  253. // When duplicated, the first loop will be scroll longer so double the duration
  254. if (loopCount === 1) {
  255. o._originalDuration = o.duration;
  256. if (verticalDir) {
  257. o.duration = o.direction == 'up' ? o.duration + (containerHeight / ((elHeight) / o.duration)) : o.duration * 2;
  258. } else {
  259. o.duration = o.direction == 'left' ? o.duration + (containerWidth / ((elWidth) / o.duration)) : o.duration * 2;
  260. }
  261. // Adjust the css3 animation as well
  262. if (animationCss3Str) {
  263. animationCss3Str = animationName + ' ' + o.duration / 1000 + 's ' + o.delayBeforeStart / 1000 + 's ' + o.css3easing;
  264. }
  265. loopCount++;
  266. }
  267. // On 2nd loop things back to normal, normal duration for the rest of animations
  268. else if (loopCount === 2) {
  269. o.duration = o._originalDuration;
  270. // Adjust the css3 animation as well
  271. if (animationCss3Str) {
  272. animationName = animationName + '0';
  273. keyframeString = $.trim(keyframeString) + '0 ';
  274. animationCss3Str = animationName + ' ' + o.duration / 1000 + 's 0s infinite ' + o.css3easing;
  275. }
  276. loopCount++;
  277. }
  278. }
  279. if (verticalDir) {
  280. if (o.duplicated) {
  281. // Adjust the starting point of animation only when first loops finishes
  282. if (loopCount > 2) {
  283. $marqueeWrapper.css('transform', 'translateY(' + (o.direction == 'up' ? 0 : '-' + elHeight + 'px') + ')');
  284. }
  285. animationCss = {
  286. 'transform': 'translateY(' + (o.direction == 'up' ? '-' + elHeight + 'px' : 0) + ')'
  287. };
  288. } else if (o.startVisible) {
  289. // This loop moves the marquee out of the container
  290. if (loopCount === 2) {
  291. // Adjust the css3 animation as well
  292. if (animationCss3Str) {
  293. animationCss3Str = animationName + ' ' + o.duration / 1000 + 's ' + o.delayBeforeStart / 1000 + 's ' + o.css3easing;
  294. }
  295. animationCss = {
  296. 'transform': 'translateY(' + (o.direction == 'up' ? '-' + elHeight + 'px' : containerHeight + 'px') + ')'
  297. };
  298. loopCount++;
  299. } else if (loopCount === 3) {
  300. // Set the duration for the animation that will run forever
  301. o.duration = o._completeDuration;
  302. // Adjust the css3 animation as well
  303. if (animationCss3Str) {
  304. animationName = animationName + '0';
  305. keyframeString = $.trim(keyframeString) + '0 ';
  306. animationCss3Str = animationName + ' ' + o.duration / 1000 + 's 0s infinite ' + o.css3easing;
  307. }
  308. _rePositionVertically();
  309. }
  310. } else {
  311. _rePositionVertically();
  312. animationCss = {
  313. 'transform': 'translateY(' + (o.direction == 'up' ? '-' + ($marqueeWrapper.height()) + 'px' : containerHeight + 'px') + ')'
  314. };
  315. }
  316. } else {
  317. if (o.duplicated) {
  318. // Adjust the starting point of animation only when first loops finishes
  319. if (loopCount > 2) {
  320. $marqueeWrapper.css('transform', 'translateX(' + (o.direction == 'left' ? 0 : '-' + elWidth + 'px') + ')');
  321. }
  322. animationCss = {
  323. 'transform': 'translateX(' + (o.direction == 'left' ? '-' + elWidth + 'px' : 0) + ')'
  324. };
  325. } else if (o.startVisible) {
  326. // This loop moves the marquee out of the container
  327. if (loopCount === 2) {
  328. // Adjust the css3 animation as well
  329. if (animationCss3Str) {
  330. animationCss3Str = animationName + ' ' + o.duration / 1000 + 's ' + o.delayBeforeStart / 1000 + 's ' + o.css3easing;
  331. }
  332. animationCss = {
  333. 'transform': 'translateX(' + (o.direction == 'left' ? '-' + elWidth + 'px' : containerWidth + 'px') + ')'
  334. };
  335. loopCount++;
  336. } else if (loopCount === 3) {
  337. // Set the duration for the animation that will run forever
  338. o.duration = o._completeDuration;
  339. // Adjust the css3 animation as well
  340. if (animationCss3Str) {
  341. animationName = animationName + '0';
  342. keyframeString = $.trim(keyframeString) + '0 ';
  343. animationCss3Str = animationName + ' ' + o.duration / 1000 + 's 0s infinite ' + o.css3easing;
  344. }
  345. _rePositionHorizontally();
  346. }
  347. } else {
  348. _rePositionHorizontally();
  349. animationCss = {
  350. 'transform': 'translateX(' + (o.direction == 'left' ? '-' + elWidth + 'px' : containerWidth + 'px') + ')'
  351. };
  352. }
  353. }
  354. // fire event
  355. $this.trigger('beforeStarting');
  356. // If css3 support is available than do it with css3, otherwise use jQuery as fallback
  357. if (css3AnimationIsSupported) {
  358. // Add css3 animation to the element
  359. $marqueeWrapper.css(animationString, animationCss3Str);
  360. var keyframeCss = keyframeString + ' { 100% ' + _objToString(animationCss) + '}',
  361. $styles = $marqueeWrapper.find('style');
  362. // Now add the keyframe animation to the marquee element
  363. if ($styles.length !== 0) {
  364. // Bug fixed for jQuery 1.3.x - Instead of using .last(), use following
  365. $styles.filter(":last").html(keyframeCss);
  366. } else {
  367. $('head').append('<style>' + keyframeCss + '</style>');
  368. }
  369. // Animation iteration event
  370. _prefixedEvent($marqueeWrapper[0], "AnimationIteration", function() {
  371. $this.trigger('finished');
  372. });
  373. // Animation stopped
  374. _prefixedEvent($marqueeWrapper[0], "AnimationEnd", function() {
  375. animate();
  376. $this.trigger('finished');
  377. });
  378. } else {
  379. // Start animating
  380. $marqueeWrapper.animate(animationCss, o.duration, o.easing, function() {
  381. // fire event
  382. $this.trigger('finished');
  383. // animate again
  384. if (o.pauseOnCycle) {
  385. _startAnimationWithDelay();
  386. } else {
  387. animate();
  388. }
  389. });
  390. }
  391. // save the status
  392. $this.data('runningStatus', 'resumed');
  393. };
  394. // bind pause and resume events
  395. $this.on('pause', methods.pause);
  396. $this.on('resume', methods.resume);
  397. if (o.pauseOnHover) {
  398. $this.on('mouseenter', methods.pause);
  399. $this.on('mouseleave', methods.resume);
  400. }
  401. // If css3 animation is supported than call animate method at once
  402. if (css3AnimationIsSupported && o.allowCss3Support) {
  403. animate();
  404. } else {
  405. // Starts the recursive method
  406. _startAnimationWithDelay();
  407. }
  408. });
  409. }; // End of Plugin
  410. // Public: plugin defaults options
  411. $.fn.marquee.defaults = {
  412. // If you wish to always animate using jQuery
  413. allowCss3Support: true,
  414. // works when allowCss3Support is set to true - for full list see http://www.w3.org/TR/2013/WD-css3-transitions-20131119/#transition-timing-function
  415. css3easing: 'linear',
  416. // requires jQuery easing plugin. Default is 'linear'
  417. easing: 'linear',
  418. // pause time before the next animation turn in milliseconds
  419. delayBeforeStart: 1000,
  420. // 'left', 'right', 'up' or 'down'
  421. direction: 'left',
  422. // true or false - should the marquee be duplicated to show an effect of continues flow
  423. duplicated: false,
  424. // duration in milliseconds of the marquee in milliseconds
  425. duration: 5000,
  426. // Speed allows you to set a relatively constant marquee speed regardless of the width of the containing element. Speed is measured in pixels per second.
  427. speed: 0,
  428. // gap in pixels between the tickers
  429. gap: 20,
  430. // on cycle pause the marquee
  431. pauseOnCycle: false,
  432. // on hover pause the marquee - using jQuery plugin https://github.com/tobia/Pause
  433. pauseOnHover: false,
  434. // the marquee is visible initially positioned next to the border towards it will be moving
  435. startVisible: false
  436. };
  437. })(jQuery);