scrollfloater.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. // Copyright 2008 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Class for making an element detach and float to remain visible
  16. * even when the viewport has been scrolled.
  17. * <p>
  18. * The element remains at its normal position in the layout until scrolling
  19. * would cause its top edge to scroll off the top of the viewport; at that
  20. * point, the element is replaced with an invisible placeholder (to keep the
  21. * layout stable), reattached in the dom tree to a new parent (the body element
  22. * by default), and set to "fixed" positioning (emulated for IE < 7) so that it
  23. * remains at its original X position while staying fixed to the top of the
  24. * viewport in the Y dimension.
  25. * <p>
  26. * When the window is scrolled up past the point where the original element
  27. * would be fully visible again, the element snaps back into place, replacing
  28. * the placeholder.
  29. *
  30. * @see ../demos/scrollfloater.html
  31. *
  32. * Adapted from http://go/elementfloater.js
  33. */
  34. goog.provide('goog.ui.ScrollFloater');
  35. goog.provide('goog.ui.ScrollFloater.EventType');
  36. goog.require('goog.array');
  37. goog.require('goog.asserts');
  38. goog.require('goog.dom');
  39. goog.require('goog.dom.TagName');
  40. goog.require('goog.dom.classlist');
  41. goog.require('goog.events.EventType');
  42. goog.require('goog.style');
  43. goog.require('goog.ui.Component');
  44. goog.require('goog.userAgent');
  45. /**
  46. * Creates a ScrollFloater; see file overview for details.
  47. *
  48. * @param {Element=} opt_parentElement Where to attach the element when it's
  49. * floating. Default is the document body. If the floating element
  50. * contains form inputs, it will be necessary to attach it to the
  51. * corresponding form element, or to an element in the DOM subtree under
  52. * the form element.
  53. * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
  54. * @constructor
  55. * @extends {goog.ui.Component}
  56. */
  57. goog.ui.ScrollFloater = function(opt_parentElement, opt_domHelper) {
  58. // If a parentElement is supplied, we want to use its domHelper,
  59. // ignoring the caller-supplied one.
  60. var domHelper = opt_parentElement ? goog.dom.getDomHelper(opt_parentElement) :
  61. opt_domHelper;
  62. goog.ui.ScrollFloater.base(this, 'constructor', domHelper);
  63. /**
  64. * The element to which the scroll-floated element will be attached
  65. * when it is floating.
  66. * @type {Element}
  67. * @private
  68. */
  69. this.parentElement_ =
  70. opt_parentElement || this.getDomHelper().getDocument().body;
  71. /**
  72. * The original styles applied to the element before it began floating;
  73. * used to restore those styles when the element stops floating.
  74. * @type {Object}
  75. * @private
  76. */
  77. this.originalStyles_ = {};
  78. /**
  79. * A vertical offset from which to start floating the element. This is
  80. * useful in cases when there are 'position:fixed' elements covering up
  81. * part of the viewport.
  82. * @type {number}
  83. * @private
  84. */
  85. this.viewportTopOffset_ = 0;
  86. /**
  87. * An element used to define the boundaries within which the floater can
  88. * be positioned.
  89. * @type {Element}
  90. * @private
  91. */
  92. this.containerElement_ = null;
  93. /**
  94. * Container element's bounding rectangle.
  95. * @type {goog.math.Rect}
  96. * @private
  97. */
  98. this.containerBounds_ = null;
  99. /**
  100. * Element's original bounding rectangle.
  101. * @type {goog.math.Rect}
  102. * @private
  103. */
  104. this.originalBounds_ = null;
  105. /**
  106. * Element's top offset when it's not floated or pinned.
  107. * @type {number}
  108. * @private
  109. */
  110. this.originalTopOffset_ = 0;
  111. /**
  112. * Element's left offset when it's not floated or pinned.
  113. * @type {number}
  114. * @private
  115. */
  116. this.originalLeftOffset_ = 0;
  117. /**
  118. * The placeholder element dropped in to hold the layout for
  119. * the floated element.
  120. * @type {Element}
  121. * @private
  122. */
  123. this.placeholder_ = null;
  124. /**
  125. * Whether scrolling is enabled for this element; true by default.
  126. * The {@link #setScrollingEnabled} method can be used to change this value.
  127. * @type {boolean}
  128. * @private
  129. */
  130. this.scrollingEnabled_ = true;
  131. /**
  132. * A flag indicating whether this instance is currently pinned to the bottom
  133. * of the container element.
  134. * @type {boolean}
  135. * @private
  136. */
  137. this.pinned_ = false;
  138. /**
  139. * A flag indicating whether this instance is currently floating.
  140. * @type {boolean}
  141. * @private
  142. */
  143. this.floating_ = false;
  144. };
  145. goog.inherits(goog.ui.ScrollFloater, goog.ui.Component);
  146. /**
  147. * Events dispatched by this component.
  148. * @enum {string}
  149. */
  150. goog.ui.ScrollFloater.EventType = {
  151. /**
  152. * Dispatched when the component starts floating. The event is
  153. * cancellable.
  154. */
  155. FLOAT: 'float',
  156. /**
  157. * Dispatched when the component returns to its original state.
  158. * The event is cancellable.
  159. */
  160. DOCK: 'dock',
  161. /**
  162. * Dispatched when the component gets pinned to the bottom of the
  163. * container element. This event is cancellable.
  164. */
  165. PIN: 'pin'
  166. };
  167. /**
  168. * The element can float at different positions on the page.
  169. * @enum {number}
  170. * @private
  171. */
  172. goog.ui.ScrollFloater.FloatMode_ = {
  173. TOP: 0,
  174. BOTTOM: 1
  175. };
  176. /**
  177. * The style properties which are stored when we float an element, so they
  178. * can be restored when it 'docks' again.
  179. * @type {Array<string>}
  180. * @private
  181. */
  182. goog.ui.ScrollFloater.STORED_STYLE_PROPS_ =
  183. ['position', 'top', 'left', 'width', 'cssFloat'];
  184. /**
  185. * The style elements managed for the placeholder object.
  186. * @type {Array<string>}
  187. * @private
  188. */
  189. goog.ui.ScrollFloater.PLACEHOLDER_STYLE_PROPS_ = [
  190. 'position', 'top', 'left', 'display', 'cssFloat', 'marginTop', 'marginLeft',
  191. 'marginRight', 'marginBottom'
  192. ];
  193. /**
  194. * The class name applied to the floating element.
  195. * @type {string}
  196. * @private
  197. */
  198. goog.ui.ScrollFloater.CSS_CLASS_ = goog.getCssName('goog-scrollfloater');
  199. /**
  200. * Delegates dom creation to superclass, then constructs and
  201. * decorates required DOM elements.
  202. * @override
  203. */
  204. goog.ui.ScrollFloater.prototype.createDom = function() {
  205. goog.ui.ScrollFloater.base(this, 'createDom');
  206. this.decorateInternal(this.getElement());
  207. };
  208. /**
  209. * Decorates the floated element with the standard ScrollFloater CSS class.
  210. * @param {Element} element The element to decorate.
  211. * @override
  212. */
  213. goog.ui.ScrollFloater.prototype.decorateInternal = function(element) {
  214. goog.ui.ScrollFloater.base(this, 'decorateInternal', element);
  215. goog.asserts.assert(element);
  216. goog.dom.classlist.add(element, goog.ui.ScrollFloater.CSS_CLASS_);
  217. };
  218. /** @override */
  219. goog.ui.ScrollFloater.prototype.enterDocument = function() {
  220. goog.ui.ScrollFloater.base(this, 'enterDocument');
  221. if (!this.placeholder_) {
  222. this.placeholder_ = this.getDomHelper().createDom(
  223. goog.dom.TagName.DIV, {'style': 'visibility:hidden'});
  224. }
  225. this.update();
  226. this.setScrollingEnabled(this.scrollingEnabled_);
  227. var win = this.getDomHelper().getWindow();
  228. this.getHandler()
  229. .listen(win, goog.events.EventType.SCROLL, this.handleScroll_)
  230. .listen(win, goog.events.EventType.RESIZE, this.update);
  231. };
  232. /**
  233. * Forces the component to update the cached element positions and sizes and
  234. * to re-evaluate whether the the component should be docked, floated or
  235. * pinned.
  236. */
  237. goog.ui.ScrollFloater.prototype.update = function() {
  238. if (!this.isInDocument()) {
  239. return;
  240. }
  241. // These values can only be calculated when the element is in its original
  242. // state, so we dock first, and then re-evaluate.
  243. this.dock_();
  244. if (this.containerElement_) {
  245. this.containerBounds_ = goog.style.getBounds(this.containerElement_);
  246. }
  247. var pageOffset_ = goog.style.getPageOffset(this.getElement());
  248. this.originalBounds_ = goog.style.getBounds(this.getElement());
  249. this.originalTopOffset_ = pageOffset_.y;
  250. this.originalLeftOffset_ = pageOffset_.x;
  251. this.handleScroll_();
  252. };
  253. /** @override */
  254. goog.ui.ScrollFloater.prototype.disposeInternal = function() {
  255. goog.ui.ScrollFloater.base(this, 'disposeInternal');
  256. this.placeholder_ = null;
  257. };
  258. /**
  259. * Sets whether the element should be floated if it scrolls out of view.
  260. * @param {boolean} enable Whether floating is enabled for this element.
  261. */
  262. goog.ui.ScrollFloater.prototype.setScrollingEnabled = function(enable) {
  263. this.scrollingEnabled_ = enable;
  264. if (enable) {
  265. this.applyIeBgHack_();
  266. this.handleScroll_();
  267. } else {
  268. this.dock_();
  269. }
  270. };
  271. /**
  272. * @return {boolean} Whether the component is enabled for scroll-floating.
  273. */
  274. goog.ui.ScrollFloater.prototype.isScrollingEnabled = function() {
  275. return this.scrollingEnabled_;
  276. };
  277. /**
  278. * @return {boolean} Whether the component is currently scroll-floating.
  279. */
  280. goog.ui.ScrollFloater.prototype.isFloating = function() {
  281. return this.floating_;
  282. };
  283. /**
  284. * @return {boolean} Whether the component is currently pinned to the bottom
  285. * of the container.
  286. */
  287. goog.ui.ScrollFloater.prototype.isPinned = function() {
  288. return this.pinned_;
  289. };
  290. /**
  291. * @param {number} offset A vertical offset from the top of the viewport, from
  292. * which to start floating the element. Default is 0. This is useful in cases
  293. * when there are 'position:fixed' elements covering up part of the viewport.
  294. */
  295. goog.ui.ScrollFloater.prototype.setViewportTopOffset = function(offset) {
  296. this.viewportTopOffset_ = offset;
  297. this.update();
  298. };
  299. /**
  300. * @param {Element} container An element used to define the boundaries within
  301. * which the floater can be positioned. If not specified, scrolling the page
  302. * down far enough may result in the floated element extending past the
  303. * containing element as it is being scrolled out of the viewport. In some
  304. * cases, such as a list with a sticky header, this may be undesirable. If
  305. * the container element is specified and the floated element extends past
  306. * the bottom of the container, the element will be pinned to the bottom of
  307. * the container.
  308. */
  309. goog.ui.ScrollFloater.prototype.setContainerElement = function(container) {
  310. this.containerElement_ = container;
  311. this.update();
  312. };
  313. /**
  314. * When a scroll event occurs, compares the element's position to the current
  315. * document scroll position, and stops or starts floating behavior if needed.
  316. * @param {goog.events.Event=} opt_e The event, which is ignored.
  317. * @private
  318. */
  319. goog.ui.ScrollFloater.prototype.handleScroll_ = function(opt_e) {
  320. if (this.scrollingEnabled_) {
  321. var scrollTop = this.getDomHelper().getDocumentScroll().y;
  322. if (this.originalBounds_.top - scrollTop >= this.viewportTopOffset_) {
  323. this.dock_();
  324. return;
  325. }
  326. var effectiveElementHeight =
  327. this.originalBounds_.height + this.viewportTopOffset_;
  328. // If the element extends past the container, we need to pin it instead.
  329. if (this.containerElement_) {
  330. var containerBottom =
  331. this.containerBounds_.top + this.containerBounds_.height;
  332. if (scrollTop > containerBottom - effectiveElementHeight) {
  333. this.pin_();
  334. return;
  335. }
  336. }
  337. var windowHeight = this.getDomHelper().getViewportSize().height;
  338. // If the element is shorter than the window or the user uses IE < 7,
  339. // float it at the top.
  340. if (this.needsIePositionHack_() || effectiveElementHeight < windowHeight) {
  341. this.float_(goog.ui.ScrollFloater.FloatMode_.TOP);
  342. return;
  343. }
  344. // If the element is taller than the window and is extending past the
  345. // bottom, allow it scroll with the page until the bottom of the element is
  346. // fully visible.
  347. if (this.originalBounds_.height + this.originalTopOffset_ >
  348. windowHeight + scrollTop) {
  349. this.dock_();
  350. } else {
  351. // Pin the element to the bottom of the page since the user has scrolled
  352. // past it.
  353. this.float_(goog.ui.ScrollFloater.FloatMode_.BOTTOM);
  354. }
  355. }
  356. };
  357. /**
  358. * Pins the element to the bottom of the container, making as much of the
  359. * element visible as possible without extending past it.
  360. * @private
  361. */
  362. goog.ui.ScrollFloater.prototype.pin_ = function() {
  363. if (this.floating_ && !this.dock_()) {
  364. return;
  365. }
  366. // Ignore if the component is pinned or the PIN event is cancelled.
  367. if (this.pinned_ ||
  368. !this.dispatchEvent(goog.ui.ScrollFloater.EventType.PIN)) {
  369. return;
  370. }
  371. var elem = this.getElement();
  372. this.storeOriginalStyles_();
  373. elem.style.position = 'relative';
  374. elem.style.top = this.containerBounds_.height - this.originalBounds_.height -
  375. this.originalBounds_.top + this.containerBounds_.top + 'px';
  376. this.pinned_ = true;
  377. };
  378. /**
  379. * Begins floating behavior, making the element position:fixed (or IE hacked
  380. * equivalent) and inserting a placeholder where it used to be to keep the
  381. * layout from shifting around. For IE < 7 users, we only support floating at
  382. * the top.
  383. * @param {goog.ui.ScrollFloater.FloatMode_} floatMode The position at which we
  384. * should float.
  385. * @private
  386. */
  387. goog.ui.ScrollFloater.prototype.float_ = function(floatMode) {
  388. var isTop = floatMode == goog.ui.ScrollFloater.FloatMode_.TOP;
  389. if (this.pinned_ && !this.dock_()) {
  390. return;
  391. }
  392. // Ignore if the FLOAT event is cancelled.
  393. if (!this.dispatchEvent(goog.ui.ScrollFloater.EventType.FLOAT)) {
  394. return;
  395. }
  396. // If the component is already floating, only update the left position.
  397. var newWindowLeftOffset_ = goog.dom.getDocumentScroll().x;
  398. if (this.floating_) {
  399. this.updateFloatingLeftPosition_();
  400. return;
  401. }
  402. var elem = /** @type {!HTMLElement} */ (this.getElement());
  403. // Read properties of element before modifying it.
  404. var originalLeft_ = goog.style.getPageOffsetLeft(elem);
  405. var originalWidth_ = goog.style.getContentBoxSize(elem).width;
  406. this.storeOriginalStyles_();
  407. goog.style.setSize(this.placeholder_, elem.offsetWidth, elem.offsetHeight);
  408. // Make element float.
  409. goog.style.setStyle(elem, {
  410. 'left': (originalLeft_ - newWindowLeftOffset_) + 'px',
  411. 'width': originalWidth_ + 'px',
  412. 'cssFloat': 'none'
  413. });
  414. // If parents are the same, avoid detaching and reattaching elem.
  415. // This prevents Flash embeds from being reloaded, for example.
  416. if (elem.parentNode == this.parentElement_) {
  417. elem.parentNode.insertBefore(this.placeholder_, elem);
  418. } else {
  419. elem.parentNode.replaceChild(this.placeholder_, elem);
  420. this.parentElement_.appendChild(elem);
  421. }
  422. // Versions of IE below 7-in-standards-mode don't handle 'position: fixed',
  423. // so we must emulate it using an IE-specific idiom for JS-based calculated
  424. // style values. These users will only ever float at the top (bottom floating
  425. // not supported.) Also checked in handleScroll_.
  426. if (this.needsIePositionHack_()) {
  427. elem.style.position = 'absolute';
  428. elem.style.setExpression(
  429. 'top', 'document.compatMode=="CSS1Compat"?' +
  430. 'documentElement.scrollTop:document.body.scrollTop');
  431. } else {
  432. elem.style.position = 'fixed';
  433. if (isTop) {
  434. elem.style.top = this.viewportTopOffset_ + 'px';
  435. elem.style.bottom = 'auto';
  436. } else {
  437. elem.style.top = 'auto';
  438. elem.style.bottom = '0';
  439. }
  440. }
  441. this.floating_ = true;
  442. };
  443. /**
  444. * Stops floating behavior, returning element to its original state.
  445. * @return {boolean} True if the the element has been docked. False if the
  446. * element is already docked or the event was cancelled.
  447. * @private
  448. */
  449. goog.ui.ScrollFloater.prototype.dock_ = function() {
  450. // Ignore if the component is docked or the DOCK event is cancelled.
  451. if (!(this.floating_ || this.pinned_) ||
  452. !this.dispatchEvent(goog.ui.ScrollFloater.EventType.DOCK)) {
  453. return false;
  454. }
  455. var elem = this.getElement();
  456. if (this.floating_) {
  457. this.restoreOriginalStyles_();
  458. if (this.needsIePositionHack_()) {
  459. elem.style.removeExpression('top');
  460. }
  461. // If placeholder_ was inserted and didn't replace elem then elem has
  462. // the right parent already, no need to replace (which removes elem before
  463. // inserting it).
  464. if (this.placeholder_.parentNode == this.parentElement_) {
  465. this.placeholder_.parentNode.removeChild(this.placeholder_);
  466. } else {
  467. this.placeholder_.parentNode.replaceChild(elem, this.placeholder_);
  468. }
  469. }
  470. if (this.pinned_) {
  471. this.restoreOriginalStyles_();
  472. }
  473. this.floating_ = this.pinned_ = false;
  474. return true;
  475. };
  476. /**
  477. * Handle horizontal scroll events by updating the left offset position. This
  478. * cannot change the floating or docked state and is only valid while the
  479. * element is floating.
  480. * @private
  481. */
  482. goog.ui.ScrollFloater.prototype.updateFloatingLeftPosition_ = function() {
  483. goog.asserts.assert(this.floating_);
  484. var newWindowLeftOffset_ = goog.dom.getDocumentScroll().x;
  485. goog.style.setStyle(
  486. this.getElement(),
  487. {'left': (this.originalLeftOffset_ - newWindowLeftOffset_) + 'px'});
  488. };
  489. /**
  490. * @private
  491. */
  492. goog.ui.ScrollFloater.prototype.storeOriginalStyles_ = function() {
  493. var elem = this.getElement();
  494. this.originalStyles_ = {};
  495. // Store styles while not floating so we can restore them when the
  496. // element stops floating.
  497. goog.array.forEach(
  498. goog.ui.ScrollFloater.STORED_STYLE_PROPS_, function(property) {
  499. this.originalStyles_[property] = elem.style[property];
  500. }, this);
  501. // Copy relevant styles to placeholder so it will be laid out the same
  502. // as the element that's about to be floated.
  503. goog.array.forEach(
  504. goog.ui.ScrollFloater.PLACEHOLDER_STYLE_PROPS_, function(property) {
  505. this.placeholder_.style[property] = elem.style[property] ||
  506. goog.style.getCascadedStyle(elem, property) ||
  507. goog.style.getComputedStyle(elem, property);
  508. }, this);
  509. };
  510. /**
  511. * @private
  512. */
  513. goog.ui.ScrollFloater.prototype.restoreOriginalStyles_ = function() {
  514. var elem = this.getElement();
  515. for (var prop in this.originalStyles_) {
  516. elem.style[prop] = this.originalStyles_[prop];
  517. }
  518. };
  519. /**
  520. * Determines whether we need to apply the position hack to emulated position:
  521. * fixed on this browser.
  522. * @return {boolean} Whether the current browser needs the position hack.
  523. * @private
  524. */
  525. goog.ui.ScrollFloater.prototype.needsIePositionHack_ = function() {
  526. return goog.userAgent.IE &&
  527. !(goog.userAgent.isVersionOrHigher('7') &&
  528. this.getDomHelper().isCss1CompatMode());
  529. };
  530. /**
  531. * Sets some magic CSS properties that make float-scrolling work smoothly
  532. * in IE6 (and IE7 in quirks mode). Without this hack, the floating element
  533. * will appear jumpy when you scroll the document. This involves modifying
  534. * the background of the HTML element (or BODY in quirks mode). If there's
  535. * already a background image in use this is not required.
  536. * For further reading, see
  537. * http://annevankesteren.nl/2005/01/position-fixed-in-ie
  538. * @private
  539. */
  540. goog.ui.ScrollFloater.prototype.applyIeBgHack_ = function() {
  541. if (this.needsIePositionHack_()) {
  542. var doc = this.getDomHelper().getDocument();
  543. var topLevelElement = goog.style.getClientViewportElement(doc);
  544. if (topLevelElement.currentStyle.backgroundImage == 'none') {
  545. // Using an https URL if the current windowbp is https avoids an IE
  546. // "This page contains a mix of secure and nonsecure items" warning.
  547. topLevelElement.style.backgroundImage =
  548. this.getDomHelper().getWindow().location.protocol == 'https:' ?
  549. 'url(https:///)' :
  550. 'url(about:blank)';
  551. topLevelElement.style.backgroundAttachment = 'fixed';
  552. }
  553. }
  554. };