You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

694 lines
21 KiB

  1. /* ******************************
  2. Semantic Module: Popup
  3. Author: Jack Lukic
  4. Notes: May 30, 2013
  5. Simple plug-in to display popups
  6. ****************************** */
  7. ;(function ($, window, document, undefined) {
  8. $.fn.popup = function(parameters) {
  9. var
  10. $allModules = $(this),
  11. settings = ( $.isPlainObject(parameters) )
  12. ? $.extend(true, {}, $.fn.popup.settings, parameters)
  13. : $.fn.popup.settings,
  14. moduleSelector = $allModules.selector || '',
  15. time = new Date().getTime(),
  16. performance = [],
  17. query = arguments[0],
  18. methodInvoked = (typeof query == 'string'),
  19. queryArguments = [].slice.call(arguments, 1),
  20. invokedResponse
  21. ;
  22. $allModules
  23. .each(function() {
  24. var
  25. $module = $(this),
  26. $window = $(window),
  27. $offsetParent = $module.offsetParent(),
  28. $popup = (settings.inline)
  29. ? $module.next(settings.selector.popup)
  30. : $window.children(settings.selector.popup).last(),
  31. searchDepth = 0,
  32. eventNamespace = '.' + settings.namespace,
  33. moduleNamespace = settings.namespace + '-module',
  34. selector = settings.selector,
  35. className = settings.className,
  36. error = settings.error,
  37. metadata = settings.metadata,
  38. namespace = settings.namespace,
  39. element = this,
  40. instance = $module.data(moduleNamespace),
  41. module
  42. ;
  43. module = {
  44. // binds events
  45. initialize: function() {
  46. module.debug('Initializing module', $module);
  47. if(settings.on == 'hover') {
  48. $module
  49. .on('mouseenter' + eventNamespace, module.event.mouseenter)
  50. .on('mouseleave' + eventNamespace, module.event.mouseleave)
  51. ;
  52. }
  53. else {
  54. $module
  55. .on(settings.on + '' + eventNamespace, module.event[settings.on])
  56. ;
  57. }
  58. $window
  59. .on('resize' + eventNamespace, module.event.resize)
  60. ;
  61. module.instantiate();
  62. },
  63. instantiate: function() {
  64. module.verbose('Storing instance of module', module);
  65. instance = module;
  66. $module
  67. .data(moduleNamespace, instance)
  68. ;
  69. },
  70. refresh: function() {
  71. $popup = (settings.inline)
  72. ? $module.next(selector.popup)
  73. : $window.children(selector.popup).last()
  74. ;
  75. $offsetParent = $module.offsetParent();
  76. },
  77. destroy: function() {
  78. module.debug('Destroying previous module');
  79. $module
  80. .off(eventNamespace)
  81. .removeData(moduleNamespace)
  82. ;
  83. },
  84. event: {
  85. mouseenter: function(event) {
  86. var element = this;
  87. module.timer = setTimeout(function() {
  88. $.proxy(module.toggle, element)();
  89. if( $(element).hasClass(className.visible) ) {
  90. event.stopPropagation();
  91. }
  92. }, settings.delay);
  93. },
  94. mouseleave: function() {
  95. clearTimeout(module.timer);
  96. if( $module.is(':visible') ) {
  97. module.hide();
  98. }
  99. },
  100. click: function(event) {
  101. $.proxy(module.toggle, this)();
  102. if( $(this).hasClass(className.visible) ) {
  103. event.stopPropagation();
  104. }
  105. },
  106. resize: function() {
  107. if( $popup.is(':visible') ) {
  108. module.position();
  109. }
  110. }
  111. },
  112. // generates popup html from metadata
  113. create: function() {
  114. module.debug('Creating pop-up html');
  115. var
  116. html = $module.data(metadata.html) || settings.html,
  117. variation = $module.data(metadata.variation) || settings.variation,
  118. title = $module.data(metadata.title) || settings.title,
  119. content = $module.data(metadata.content) || $module.attr('title') || settings.content
  120. ;
  121. if(html || content || title) {
  122. if(!html) {
  123. html = settings.template({
  124. title : title,
  125. content : content
  126. });
  127. }
  128. $popup = $('<div/>')
  129. .addClass(className.popup)
  130. .addClass(variation)
  131. .html(html)
  132. ;
  133. if(settings.inline) {
  134. module.verbose('Inserting popup element inline');
  135. $popup
  136. .insertAfter($module)
  137. ;
  138. }
  139. else {
  140. module.verbose('Appending popup element to body');
  141. $popup
  142. .appendTo( $('body') )
  143. ;
  144. }
  145. $.proxy(settings.onInit, $popup)();
  146. }
  147. else {
  148. module.error(error.content);
  149. }
  150. },
  151. remove: function() {
  152. module.debug('Removing popup');
  153. $popup
  154. .remove()
  155. ;
  156. },
  157. get: {
  158. offstagePosition: function() {
  159. var
  160. boundary = {
  161. top : $(window).scrollTop(),
  162. bottom : $(window).scrollTop() + $(window).height(),
  163. left : 0,
  164. right : $(window).width()
  165. },
  166. popup = {
  167. width : $popup.width(),
  168. height : $popup.outerHeight(),
  169. position : $popup.offset()
  170. },
  171. offstage = {},
  172. offstagePositions = []
  173. ;
  174. if(popup.position) {
  175. offstage = {
  176. top : (popup.position.top < boundary.top),
  177. bottom : (popup.position.top + popup.height > boundary.bottom),
  178. right : (popup.position.left + popup.width > boundary.right),
  179. left : (popup.position.left < boundary.left)
  180. };
  181. }
  182. // return only boundaries that have been surpassed
  183. $.each(offstage, function(direction, isOffstage) {
  184. if(isOffstage) {
  185. offstagePositions.push(direction);
  186. }
  187. });
  188. return (offstagePositions.length > 0)
  189. ? offstagePositions.join(' ')
  190. : false
  191. ;
  192. },
  193. nextPosition: function(position) {
  194. switch(position) {
  195. case 'top left':
  196. position = 'bottom left';
  197. break;
  198. case 'bottom left':
  199. position = 'top right';
  200. break;
  201. case 'top right':
  202. position = 'bottom right';
  203. break;
  204. case 'bottom right':
  205. position = 'top center';
  206. break;
  207. case 'top center':
  208. position = 'bottom center';
  209. break;
  210. case 'bottom center':
  211. position = 'right center';
  212. break;
  213. case 'right center':
  214. position = 'left center';
  215. break;
  216. case 'left center':
  217. position = 'top center';
  218. break;
  219. }
  220. return position;
  221. }
  222. },
  223. // determines popup state
  224. toggle: function() {
  225. $module = $(this);
  226. module.debug('Toggling pop-up');
  227. // refresh state of module
  228. module.refresh();
  229. if( !$module.hasClass(className.visible) ) {
  230. module.hideAll();
  231. module.show();
  232. }
  233. else {
  234. module.hide();
  235. }
  236. },
  237. position: function(position, arrowOffset) {
  238. var
  239. windowWidth = $(window).width(),
  240. windowHeight = $(window).height(),
  241. width = $module.outerWidth(),
  242. height = $module.outerHeight(),
  243. popupWidth = $popup.width(),
  244. popupHeight = $popup.outerHeight(),
  245. offset = (settings.inline)
  246. ? $module.position()
  247. : $module.offset(),
  248. parentWidth = (settings.inline)
  249. ? $offsetParent.outerWidth()
  250. : $window.outerWidth(),
  251. parentHeight = (settings.inline)
  252. ? $offsetParent.outerHeight()
  253. : $window.outerHeight(),
  254. positioning,
  255. offstagePosition
  256. ;
  257. position = position || $module.data(metadata.position) || settings.position;
  258. arrowOffset = arrowOffset || $module.data(metadata.arrowOffset) || settings.arrowOffset;
  259. module.debug('Calculating offset for position', position);
  260. switch(position) {
  261. case 'top left':
  262. positioning = {
  263. top : 'auto',
  264. bottom : parentHeight - offset.top + settings.distanceAway,
  265. left : offset.left + arrowOffset
  266. };
  267. break;
  268. case 'top center':
  269. positioning = {
  270. bottom : parentHeight - offset.top + settings.distanceAway,
  271. left : offset.left + (width / 2) - (popupWidth / 2) + arrowOffset,
  272. top : 'auto',
  273. right : 'auto'
  274. };
  275. break;
  276. case 'top right':
  277. positioning = {
  278. bottom : parentHeight - offset.top + settings.distanceAway,
  279. right : parentWidth - offset.left - width - arrowOffset,
  280. top : 'auto',
  281. left : 'auto'
  282. };
  283. break;
  284. case 'left center':
  285. positioning = {
  286. top : offset.top + (height / 2) - (popupHeight / 2),
  287. right : parentWidth - offset.left + settings.distanceAway - arrowOffset,
  288. left : 'auto',
  289. bottom : 'auto'
  290. };
  291. break;
  292. case 'right center':
  293. positioning = {
  294. top : offset.top + (height / 2) - (popupHeight / 2),
  295. left : offset.left + width + settings.distanceAway + arrowOffset,
  296. bottom : 'auto',
  297. right : 'auto'
  298. };
  299. break;
  300. case 'bottom left':
  301. positioning = {
  302. top : offset.top + height + settings.distanceAway,
  303. left : offset.left + arrowOffset,
  304. bottom : 'auto',
  305. right : 'auto'
  306. };
  307. break;
  308. case 'bottom center':
  309. positioning = {
  310. top : offset.top + height + settings.distanceAway,
  311. left : offset.left + (width / 2) - (popupWidth / 2) + arrowOffset,
  312. bottom : 'auto',
  313. right : 'auto'
  314. };
  315. break;
  316. case 'bottom right':
  317. positioning = {
  318. top : offset.top + height + settings.distanceAway,
  319. right : parentWidth - offset.left - width - arrowOffset,
  320. left : 'auto',
  321. bottom : 'auto'
  322. };
  323. break;
  324. }
  325. // true width on popup, avoid rounding error
  326. $.extend(positioning, {
  327. width: $popup.width() + 1
  328. });
  329. // tentatively place on stage
  330. $popup
  331. .removeAttr('style')
  332. .removeClass('top right bottom left center')
  333. .css(positioning)
  334. .addClass(position)
  335. .addClass(className.loading)
  336. ;
  337. // check if is offstage
  338. offstagePosition = module.get.offstagePosition();
  339. // recursively find new positioning
  340. if(offstagePosition) {
  341. module.debug('Element is outside boundaries ', offstagePosition);
  342. if(searchDepth < settings.maxSearchDepth) {
  343. position = module.get.nextPosition(position);
  344. searchDepth++;
  345. module.debug('Trying new position: ', position);
  346. return module.position(position);
  347. }
  348. else {
  349. module.error(error.recursion);
  350. searchDepth = 0;
  351. return false;
  352. }
  353. }
  354. else {
  355. module.debug('Position is on stage', position);
  356. searchDepth = 0;
  357. return true;
  358. }
  359. },
  360. show: function() {
  361. module.debug('Showing pop-up');
  362. if($popup.size() === 0) {
  363. module.create();
  364. }
  365. module.position();
  366. $module
  367. .addClass(className.visible)
  368. ;
  369. $popup
  370. .removeClass(className.loading)
  371. ;
  372. if(settings.animation == 'pop' && $.fn.popIn !== undefined) {
  373. $popup
  374. .stop()
  375. .popIn(settings.duration, settings.easing)
  376. ;
  377. }
  378. else {
  379. $popup
  380. .stop()
  381. .fadeIn(settings.duration, settings.easing)
  382. ;
  383. }
  384. if(settings.on == 'click' && settings.clicktoClose) {
  385. module.debug('Binding popup close event');
  386. $(document)
  387. .on('click.' + namespace, module.gracefully.hide)
  388. ;
  389. }
  390. $.proxy(settings.onShow, $popup)();
  391. },
  392. hideAll: function() {
  393. $(selector.popup)
  394. .filter(':visible')
  395. .stop()
  396. .fadeOut(200)
  397. .prev($module)
  398. .removeClass(className.visible)
  399. ;
  400. },
  401. hide: function() {
  402. $module
  403. .removeClass(className.visible)
  404. ;
  405. if($popup.is(':visible') ) {
  406. module.debug('Hiding pop-up');
  407. if(settings.animation == 'pop' && $.fn.popOut !== undefined) {
  408. $popup
  409. .stop()
  410. .popOut(settings.duration, settings.easing, function() {
  411. $popup.hide();
  412. })
  413. ;
  414. }
  415. else {
  416. $popup
  417. .stop()
  418. .fadeOut(settings.duration, settings.easing)
  419. ;
  420. }
  421. }
  422. if(settings.on == 'click' && settings.clicktoClose) {
  423. $(document)
  424. .off('click.' + namespace)
  425. ;
  426. }
  427. $.proxy(settings.onHide, $popup)();
  428. if(!settings.inline) {
  429. module.remove();
  430. }
  431. },
  432. gracefully: {
  433. hide: function(event) {
  434. // don't close on clicks inside popup
  435. if( $(event.target).closest(selector.popup).size() === 0) {
  436. module.hide();
  437. }
  438. }
  439. },
  440. setting: function(name, value) {
  441. if(value !== undefined) {
  442. if( $.isPlainObject(name) ) {
  443. $.extend(true, settings, name);
  444. }
  445. else {
  446. settings[name] = value;
  447. }
  448. }
  449. else {
  450. return settings[name];
  451. }
  452. },
  453. internal: function(name, value) {
  454. if(value !== undefined) {
  455. if( $.isPlainObject(name) ) {
  456. $.extend(true, module, name);
  457. }
  458. else {
  459. module[name] = value;
  460. }
  461. }
  462. else {
  463. return module[name];
  464. }
  465. },
  466. debug: function() {
  467. if(settings.debug) {
  468. if(settings.performance) {
  469. module.performance.log(arguments);
  470. }
  471. else {
  472. module.debug = Function.prototype.bind.call(console.info, console, settings.moduleName + ':');
  473. }
  474. }
  475. },
  476. verbose: function() {
  477. if(settings.verbose && settings.debug) {
  478. if(settings.performance) {
  479. module.performance.log(arguments);
  480. }
  481. else {
  482. module.verbose = Function.prototype.bind.call(console.info, console, settings.moduleName + ':');
  483. }
  484. }
  485. },
  486. error: function() {
  487. module.error = Function.prototype.bind.call(console.warn, console, settings.moduleName + ':');
  488. },
  489. performance: {
  490. log: function(message) {
  491. var
  492. currentTime,
  493. executionTime,
  494. previousTime
  495. ;
  496. if(settings.performance) {
  497. currentTime = new Date().getTime();
  498. previousTime = time || currentTime;
  499. executionTime = currentTime - previousTime;
  500. time = currentTime;
  501. performance.push({
  502. 'Element' : element,
  503. 'Name' : message[0],
  504. 'Arguments' : [].slice.call(message, 1) || '',
  505. 'Execution Time' : executionTime
  506. });
  507. }
  508. clearTimeout(module.performance.timer);
  509. module.performance.timer = setTimeout(module.performance.display, 100);
  510. },
  511. display: function() {
  512. var
  513. title = settings.moduleName + ':',
  514. totalTime = 0
  515. ;
  516. time = false;
  517. clearTimeout(module.performance.timer);
  518. $.each(performance, function(index, data) {
  519. totalTime += data['Execution Time'];
  520. });
  521. title += ' ' + totalTime + 'ms';
  522. if(moduleSelector) {
  523. title += ' \'' + moduleSelector + '\'';
  524. }
  525. if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
  526. console.groupCollapsed(title);
  527. if(console.table) {
  528. console.table(performance);
  529. }
  530. else {
  531. $.each(performance, function(index, data) {
  532. console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
  533. });
  534. }
  535. console.groupEnd();
  536. }
  537. performance = [];
  538. }
  539. },
  540. invoke: function(query, passedArguments, context) {
  541. var
  542. maxDepth,
  543. found
  544. ;
  545. passedArguments = passedArguments || queryArguments;
  546. context = element || context;
  547. if(typeof query == 'string' && instance !== undefined) {
  548. query = query.split(/[\. ]/);
  549. maxDepth = query.length - 1;
  550. $.each(query, function(depth, value) {
  551. if( $.isPlainObject( instance[value] ) && (depth != maxDepth) ) {
  552. instance = instance[value];
  553. }
  554. else if( instance[value] !== undefined ) {
  555. found = instance[value];
  556. }
  557. else {
  558. module.error(error.method);
  559. }
  560. });
  561. }
  562. if ( $.isFunction( found ) ) {
  563. return found.apply(context, passedArguments);
  564. }
  565. return found || false;
  566. }
  567. };
  568. if(methodInvoked) {
  569. if(instance === undefined) {
  570. module.initialize();
  571. }
  572. invokedResponse = module.invoke(query);
  573. }
  574. else {
  575. if(instance !== undefined) {
  576. module.destroy();
  577. }
  578. module.initialize();
  579. }
  580. })
  581. ;
  582. return (invokedResponse)
  583. ? invokedResponse
  584. : this
  585. ;
  586. };
  587. $.fn.popup.settings = {
  588. moduleName : 'Popup',
  589. debug : true,
  590. verbose : true,
  591. performance : true,
  592. namespace : 'popup',
  593. onInit : function(){},
  594. onShow : function(){},
  595. onHide : function(){},
  596. variation : '',
  597. content : false,
  598. html : false,
  599. title : false,
  600. on : 'hover',
  601. clicktoClose : true,
  602. position : 'top center',
  603. delay : 150,
  604. inline : true,
  605. duration : 250,
  606. easing : 'easeOutQuint',
  607. animation : 'pop',
  608. distanceAway : 0,
  609. arrowOffset : 0,
  610. maxSearchDepth : 10,
  611. error: {
  612. content : 'Your popup has no content specified',
  613. method : 'The method you called is not defined.',
  614. recursion : 'Popup attempted to reposition element to fit, but could not find an adequate position.'
  615. },
  616. metadata: {
  617. arrowOffset : 'arrowOffset',
  618. content : 'content',
  619. html : 'html',
  620. position : 'position',
  621. title : 'title',
  622. variation : 'variation'
  623. },
  624. className : {
  625. popup : 'ui popup',
  626. visible : 'visible',
  627. loading : 'loading'
  628. },
  629. selector : {
  630. popup : '.ui.popup'
  631. },
  632. template: function(text) {
  633. var html = '';
  634. if(typeof text !== undefined) {
  635. if(typeof text.title !== undefined && text.title) {
  636. html += '<div class="header">' + text.title + '</div class="header">';
  637. }
  638. if(typeof text.content !== undefined && text.content) {
  639. html += '<div class="content">' + text.content + '</div>';
  640. }
  641. }
  642. return html;
  643. }
  644. };
  645. })( jQuery, window , document );