├── .gitignore ├── .jshintrc ├── .travis.yml ├── Gruntfile.js ├── LICENSE ├── README.md ├── bower.json ├── dist ├── element-resize-detector.js └── element-resize-detector.min.js ├── examples ├── detached.html ├── index.html ├── inline.html ├── padding-fontsize.html └── perf.html ├── karma.conf.js ├── package-lock.json ├── package.json ├── specrunner.html ├── src ├── browser-detector.js ├── collection-utils.js ├── detection-strategy │ ├── object.js │ └── scroll.js ├── element-resize-detector.js ├── element-utils.js ├── id-generator.js ├── id-handler.js ├── listener-handler.js ├── reporter.js └── state-handler.js └── test └── element-resize-detector_test.js /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | 3 | # Logs 4 | logs 5 | *.log 6 | 7 | # Runtime data 8 | pids 9 | *.pid 10 | *.seed 11 | 12 | # Directory for instrumented libs generated by jscoverage/JSCover 13 | lib-cov 14 | 15 | # Coverage directory used by tools like istanbul 16 | coverage 17 | 18 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 19 | .grunt 20 | 21 | # Compiled binary addons (http://nodejs.org/api/addons.html) 22 | build/Release 23 | 24 | # Dependency directory 25 | # Commenting this out is preferred by some people, see 26 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- 27 | node_modules 28 | 29 | # Users Environment Variables 30 | .lock-wscript 31 | 32 | build/ 33 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "expr": true, 3 | "nonbsp": true, 4 | "trailing": true, 5 | "indent": 4, 6 | "quotmark": "double", 7 | "eqeqeq": true, 8 | "curly": true, 9 | "forin": true, 10 | "immed": true, 11 | "newcap": true, 12 | "noempty": true, 13 | "nonew": true, 14 | "undef": true, 15 | "strict": true, 16 | "globalstrict": true, 17 | "browser": true, 18 | "globals": { 19 | "require": false, 20 | "module": false, 21 | "exports": true 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "lts/*" 4 | script: 5 | "npm run-script test-ci" -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | /* global process:false */ 2 | 3 | "use strict"; 4 | 5 | var _ = require("lodash"); 6 | 7 | module.exports = function(grunt) { 8 | require("load-grunt-tasks")(grunt); 9 | 10 | var config = { 11 | pkg: grunt.file.readJSON("package.json"), 12 | banner: "/*!\n" + 13 | " * element-resize-detector <%= pkg.version %>\n" + 14 | " * Copyright (c) 2016 Lucas Wiener\n" + 15 | " * <%= pkg.homepage %>\n" + 16 | " * Licensed under <%= pkg.license %>\n" + 17 | " */\n", 18 | jshint: { 19 | src: { 20 | src: ["src/**/*.js", "*.js"] 21 | }, 22 | test: { 23 | src: "test/**/*.js" 24 | }, 25 | options: { 26 | jshintrc: true 27 | } 28 | }, 29 | browserify: { 30 | dev: { 31 | src: ["src/element-resize-detector.js"], 32 | dest: "build/element-resize-detector.js", 33 | options: { 34 | browserifyOptions: { 35 | standalone: "elementResizeDetectorMaker", 36 | debug: true 37 | } 38 | } 39 | }, 40 | dist: { 41 | src: ["src/element-resize-detector.js"], 42 | dest: "dist/element-resize-detector.js", 43 | options: { 44 | browserifyOptions: { 45 | standalone: "elementResizeDetectorMaker" 46 | } 47 | } 48 | } 49 | }, 50 | usebanner: { 51 | dist: { 52 | options: { 53 | position: "top", 54 | banner: "<%= banner %>" 55 | }, 56 | files: { 57 | src: "dist/**/*" 58 | } 59 | } 60 | }, 61 | uglify: { 62 | dist: { 63 | files: { 64 | "dist/element-resize-detector.min.js": "dist/element-resize-detector.js" 65 | } 66 | } 67 | }, 68 | karma: { 69 | local: { 70 | configFile: "karma.conf.js", 71 | options: { 72 | browsers: [ 73 | "Chrome", 74 | "Safari", 75 | "Firefox", 76 | //"IE8 - Win7", 77 | //"IE10 - Win7", 78 | //"IE11 - Win8.1" 79 | ], 80 | singleRun: true 81 | } 82 | } 83 | } 84 | }; 85 | 86 | grunt.initConfig(config); 87 | 88 | grunt.registerTask("build:dev", ["browserify:dev"]); 89 | grunt.registerTask("build:dist", ["browserify:dist"]); 90 | 91 | grunt.registerTask("build", ["build:dev"]); 92 | grunt.registerTask("dist", ["build:dist", "uglify:dist", "usebanner:dist"]); 93 | 94 | grunt.registerTask("test:style", ["jshint"]); 95 | grunt.registerTask("test", ["test:style", "build:dev", "karma:local"]); 96 | 97 | grunt.registerTask("ci", ["test:style"]); 98 | 99 | grunt.registerTask("default", ["test"]); 100 | }; 101 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Lucas Wiener 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # element-resize-detector 2 | Optimized cross-browser resize listener for elements. Up to 37x faster than related approaches (read section 5 of the [article](http://arxiv.org/pdf/1511.01223v1.pdf)). 3 | 4 | ``` 5 | npm install element-resize-detector 6 | ``` 7 | 8 | ## Usage 9 | Include the script in the browser: 10 | ```html 11 | 12 | ``` 13 | This will create a global function `elementResizeDetectorMaker`, which is the maker function that makes an element resize detector instance. 14 | 15 | You can also `require` it like so: 16 | ```js 17 | var elementResizeDetectorMaker = require("element-resize-detector"); 18 | ``` 19 | 20 | ### Create instance 21 | ```js 22 | // With default options (will use the object-based approach). 23 | var erd = elementResizeDetectorMaker(); 24 | 25 | // With the ultra fast scroll-based approach. 26 | // This is the recommended strategy. 27 | var erdUltraFast = elementResizeDetectorMaker({ 28 | strategy: "scroll" //<- For ultra performance. 29 | }); 30 | ``` 31 | 32 | There is also an `callOnAdd` option, which determines if listeners should be called when they are getting added. Default is true. If true, the listener is guaranteed to be called when it has been added. If false, the listener will not be guarenteed to be called when it has been added (does not prevent it from being called). 33 | 34 | ## API 35 | 36 | ### listenTo(element, listener) or listenTo(options, element, listener) 37 | Listens to the element for resize events and calls the listener function with the element as argument on resize events. Options passed to the function will override the instance options. 38 | 39 | **Example usage:** 40 | 41 | ```js 42 | erd.listenTo(document.getElementById("test"), function(element) { 43 | var width = element.offsetWidth; 44 | var height = element.offsetHeight; 45 | console.log("Size: " + width + "x" + height); 46 | }); 47 | ``` 48 | 49 | ### removeListener(element, listener) 50 | Removes the listener from the element. 51 | 52 | ### removeAllListeners(element) 53 | Removes all listeners from the element, but does not completely remove the detector. Use this function if you may add listeners later and don't want the detector to have to initialize again. 54 | 55 | ### uninstall(element) 56 | Completely removes the detector and all listeners. 57 | 58 | ### initDocument(document) 59 | If you need to listen to elements inside another document (such as an iframe), you need to init that document with this function. Otherwise the library won't be able to detect when elements are attached to the document. So for an iframe, simpy invoke ``erd.initDocument(iframe.contentDocument);`` when the iframe is mounted on the DOM for the first time. The document from which the element resize detector instance is created will be initialized automatically. Notice that a new document is created when an iframe loads its content. So for iframes, be sure you invoke this function for each `onLoad` iframe event. 60 | 61 | ## Caveats 62 | 63 | 1. If the element has `position: static` it will be changed to `position: relative`. Any unintentional `top/right/bottom/left/z-index` styles will therefore be applied and absolute positioned children will be positioned relative to the element. 64 | 2. A hidden element will be injected as a direct child to the element. 65 | 66 | ## Credits 67 | Big thanks to [Evry](https://www.evry.com/) sponsoring this project. 68 | 69 | This library is using the two approaches (scroll and object) as first described at [http://www.backalleycoder.com/2013/03/18/cross-browser-event-based-element-resize-detection/](http://www.backalleycoder.com/2013/03/18/cross-browser-event-based-element-resize-detection/). 70 | 71 | The scroll based approach implementation was based on Marc J's implementation [https://github.com/marcj/css-element-queries/blob/master/src/ResizeSensor.js](https://github.com/marcj/css-element-queries/blob/master/src/ResizeSensor.js). 72 | 73 | Please note that both approaches have been heavily reworked for better performance and robustness. 74 | 75 | ## Changelog 76 | 77 | #### 1.2.4 78 | 79 | * Harden onExpandScroll and onShrinkScroll handlers. See #132 80 | 81 | 82 | #### 1.2.3 83 | 84 | * Fix problems with object approach in FF. Revert #122. 85 | 86 | 87 | #### 1.2.2 88 | 89 | * Fixes scroll strategy to account for elements within shadow root. See #127. 90 | * Fix potential contenteditable bugs with object approach. See #122. 91 | 92 | #### 1.2.1 93 | 94 | A release that includes 1.1.15 and 1.1.16 with 1.2.0. 95 | 96 | #### 1.2.0 97 | 98 | * Add new method ``initDocument(document)`` which is needed when listening to detached elements in other documents, such as iframes. 99 | * Add a new optional option that adds `important!` to most style properties, to avoid CSS overriding. Disabled by default. 100 | * Fix an issue with the object approach in IE8. See #95. 101 | * Fix uninstall issue with object approach. See #102. 102 | * Fixed errornous optimization that prevented scrollbar repositioning for really fast x -> y -> x resizes. 103 | 104 | #### 1.1.16 105 | 106 | * Fix bug that could happen during uninstall when waiting for unrendered objects. See #117. 107 | 108 | #### 1.1.15 109 | 110 | * ADA compliance fix for object approach. See #105. 111 | 112 | #### 1.1.14 113 | 114 | * Explicit use of window.getComputedStyle everywhere. 115 | 116 | #### 1.1.13 117 | 118 | * Only notify listeners when actual size change happened (in the rare case when multiple scroll events happens for the same resize). See #86. 119 | 120 | #### 1.1.12 121 | 122 | * Fixed an issue with embedded WebView's on Android and iOS (when getComputedStyle.width = null). See #74. 123 | * Fixed an issue with unrendered iframe in FireFox. See #68. 124 | 125 | #### 1.1.11 126 | 127 | * Cleaned up the development build tools. 128 | * Updated dev dependencies. 129 | * Fixed an issue when uninstalling an element, and then calling listenTo in the middle of an old resize event. See #61. 130 | 131 | #### 1.1.10 132 | 133 | * Fixed so that injected scroll elements are `flex: none`. See #64. 134 | * Fixed so that injected object element is not focusable. See #67. 135 | 136 | #### 1.1.9 137 | 138 | * Fixed uninstall issue when `callOnAdd` being true. Also now removing `onAnimationStart` listener when uninstalling. See #49. 139 | 140 | #### 1.1.8 141 | 142 | * Fixed a compatability issue with `options.idHandler.get`. 143 | 144 | #### 1.1.7 145 | 146 | * Fixed some rare issues with uninstalling elements while preparing/resizing. 147 | 148 | #### 1.1.6 149 | 150 | * Fixed an issue with the resize detector changing the dimensions of the target element in some browsers (e.g., IE and FireFox). 151 | 152 | #### 1.1.5 153 | 154 | * Fixed an issue with having parent elements `dir=RTL`. 155 | 156 | #### 1.1.4 157 | 158 | * Added extra safety styles to injected elements to make them more resilient to global CSS affecting them. 159 | 160 | #### 1.1.3 161 | 162 | * Now `uninstall` supports being called with elements that haven't been initialized. `uninstall` simply ignores non-erd elements. 163 | * `uninstall` now also supports a collection of elements. 164 | 165 | #### 1.1.2 166 | 167 | * Fixed so that `uninstall` may be called directly after a `listenTo` call. 168 | * Fixed a typo in the readme. 169 | * Fixed an invalid test. 170 | 171 | #### 1.1.1 172 | 173 | * Using `window.getComputedStyle` instead of relying on the method being available in the global scope. This enables this library to be used in simulated browser environments such as jsdom. 174 | 175 | #### 1.1.0 176 | 177 | * Supporting inline elements 178 | * Event-based solution for detecting attached/rendered events so that detached/unrendered elements can be listened to without polling 179 | * Now all changes that affects the offset size of an element are properly detected (such as padding and font-size). 180 | * Scroll is stabilized, and is the preferred strategy to use. The object strategy will be deprecated (and is currently only used for some legacy browsers such as IE9 and Opera 12). 181 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "element-resize-detector", 3 | "description": "Resize event emitter for elements.", 4 | "main": "dist/element-resize-detector.js", 5 | "authors": [ 6 | "Lucas Wiener " 7 | ], 8 | "license": "MIT", 9 | "keywords": [ 10 | "element", 11 | "resize" 12 | ], 13 | "homepage": "https://github.com/wnr/element-resize-detector", 14 | "moduleType": [], 15 | "ignore": [ 16 | "**/.*", 17 | "node_modules", 18 | "bower_components", 19 | "test", 20 | "tests" 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /dist/element-resize-detector.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * element-resize-detector 1.2.4 3 | * Copyright (c) 2016 Lucas Wiener 4 | * https://github.com/wnr/element-resize-detector 5 | * Licensed under MIT 6 | */ 7 | 8 | !function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.elementResizeDetectorMaker=a()}}(function(){return function(){function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){return e(b[g][1][a]||a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;gf?f=a:a4?a:void 0}())},d.isLegacyOpera=function(){return!!window.opera}},{}],4:[function(a,b,c){"use strict";(b.exports={}).forEach=function(a,b){for(var c=0;c div::-webkit-scrollbar { "+c(["display: none"])+" }\n\n",g+="."+f+" { "+c(["-webkit-animation-duration: 0.1s","animation-duration: 0.1s","-webkit-animation-name: "+e,"animation-name: "+e])+" }\n",g+="@-webkit-keyframes "+e+" { 0% { opacity: 1; } 50% { opacity: 0; } 100% { opacity: 1; } }\n",g+="@keyframes "+e+" { 0% { opacity: 1; } 50% { opacity: 0; } 100% { opacity: 1; } }",function(c,d){d=d||function(b){a.head.appendChild(b)};var e=a.createElement("style");e.innerHTML=c,e.id=b,d(e)}(g)}}function f(a){a.className+=" "+t+"_animation_active"}function g(a,b,c){if(a.addEventListener)a.addEventListener(b,c);else{if(!a.attachEvent)return n.error("[scroll] Don't know how to add event listeners.");a.attachEvent("on"+b,c)}}function h(a,b,c){if(a.removeEventListener)a.removeEventListener(b,c);else{if(!a.detachEvent)return n.error("[scroll] Don't know how to remove event listeners.");a.detachEvent("on"+b,c)}}function i(a){return p(a).container.childNodes[0].childNodes[0].childNodes[0]}function j(a){return p(a).container.childNodes[0].childNodes[0].childNodes[1]}function k(a,b){if(!p(a).listeners.push)throw new Error("Cannot add listener to an element that is not detectable.");p(a).listeners.push(b)}function l(a,b,e){function h(){if(a.debug){var c=Array.prototype.slice.call(arguments);if(c.unshift(q.get(b),"Scroll: "),n.log.apply)n.log.apply(null,c);else for(var d=0;d 2 | 3 | 4 | 5 | 6 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 129 | 130 | 131 | -------------------------------------------------------------------------------- /examples/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 37 | 38 | 39 |
40 |
41 |
42 | x 43 |
44 |
45 |
46 | 47 | 48 | 49 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /examples/inline.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 |
15 |
16 | elementResizeDetector width px 17 |
18 | 21 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /examples/padding-fontsize.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 21 | 22 | 23 | 24 |
25 |

erd is watching this element

26 | 27 |
28 | 29 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /examples/perf.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 41 | 42 | 43 | 44 |
45 |
46 | 47 | 48 | 49 | 50 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | // Karma configuration 4 | 5 | module.exports = function(config) { 6 | config.set({ 7 | 8 | // base path that will be used to resolve all patterns (eg. files, exclude) 9 | basePath: "", 10 | 11 | 12 | // frameworks to use 13 | // available frameworks: https://npmjs.org/browse/keyword/karma-adapter 14 | frameworks: ["jasmine"], 15 | 16 | 17 | // list of files / patterns to load in the browser 18 | files: [ 19 | "node_modules/jquery/dist/jquery.min.js", 20 | { pattern: "node_modules/jquery/dist/jquery.min.map", watched: false, included: false, served: true }, 21 | "node_modules/lodash/lodash.min.js", 22 | "build/element-resize-detector.js", 23 | "js/*_test.js", 24 | "test/*_test.js" 25 | ], 26 | 27 | 28 | // list of files to exclude 29 | exclude: [ 30 | ], 31 | 32 | 33 | // preprocess matching files before serving them to the browser 34 | // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor 35 | preprocessors: { 36 | }, 37 | 38 | 39 | // test results reporter to use 40 | // possible values: 'dots', 'progress' 41 | // available reporters: https://npmjs.org/browse/keyword/karma-reporter 42 | reporters: ["progress"], 43 | 44 | 45 | // web server port 46 | port: 9876, 47 | 48 | 49 | // enable / disable colors in the output (reporters and logs) 50 | colors: true, 51 | 52 | 53 | // level of logging 54 | // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG 55 | logLevel: config.LOG_INFO, 56 | 57 | 58 | // enable / disable watching file and executing tests whenever any file changes 59 | autoWatch: false, 60 | 61 | 62 | // start these browsers 63 | // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher 64 | browsers: [ 65 | // "Chrome" 66 | //, "IE8 - Win7", "IE10 - Win7", "IE11 - Win8.1" 67 | ], 68 | 69 | 70 | // Continuous Integration mode 71 | // if true, Karma captures browsers, runs the tests and exits 72 | singleRun: false 73 | }); 74 | }; 75 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "element-resize-detector", 3 | "version": "1.2.4", 4 | "description": "Resize event emitter for elements.", 5 | "homepage": "https://github.com/wnr/element-resize-detector", 6 | "repository": { 7 | "type": "git", 8 | "url": "git://github.com/wnr/element-resize-detector.git" 9 | }, 10 | "main": "src/element-resize-detector.js", 11 | "private": false, 12 | "license": "MIT", 13 | "dependencies": { 14 | "batch-processor": "1.0.0" 15 | }, 16 | "devDependencies": { 17 | "grunt": "1.0.1", 18 | "grunt-banner": "0.6.0", 19 | "grunt-browserify": "5.2.0", 20 | "grunt-contrib-jshint": "1.1.0", 21 | "grunt-contrib-uglify": "2.3.0", 22 | "grunt-karma": "2.0.0", 23 | "jasmine-core": "2.9.0", 24 | "jquery": "3.1.1", 25 | "karma": "1.7.1", 26 | "karma-chrome-launcher": "2.2.0", 27 | "karma-firefox-launcher": "1.1.0", 28 | "karma-jasmine": "1.1.1", 29 | "karma-safari-launcher": "1.0.0", 30 | "load-grunt-tasks": "3.5.2", 31 | "lodash": "4.17.4" 32 | }, 33 | "scripts": { 34 | "build": "grunt build", 35 | "dist": "grunt dist", 36 | "test": "grunt test", 37 | "test-ci": "grunt ci" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /specrunner.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Spec Runner 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/browser-detector.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var detector = module.exports = {}; 4 | 5 | detector.isIE = function(version) { 6 | function isAnyIeVersion() { 7 | var agent = navigator.userAgent.toLowerCase(); 8 | return agent.indexOf("msie") !== -1 || agent.indexOf("trident") !== -1 || agent.indexOf(" edge/") !== -1; 9 | } 10 | 11 | if(!isAnyIeVersion()) { 12 | return false; 13 | } 14 | 15 | if(!version) { 16 | return true; 17 | } 18 | 19 | //Shamelessly stolen from https://gist.github.com/padolsey/527683 20 | var ieVersion = (function(){ 21 | var undef, 22 | v = 3, 23 | div = document.createElement("div"), 24 | all = div.getElementsByTagName("i"); 25 | 26 | do { 27 | div.innerHTML = ""; 28 | } 29 | while (all[0]); 30 | 31 | return v > 4 ? v : undef; 32 | }()); 33 | 34 | return version === ieVersion; 35 | }; 36 | 37 | detector.isLegacyOpera = function() { 38 | return !!window.opera; 39 | }; 40 | -------------------------------------------------------------------------------- /src/collection-utils.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var utils = module.exports = {}; 4 | 5 | /** 6 | * Loops through the collection and calls the callback for each element. if the callback returns truthy, the loop is broken and returns the same value. 7 | * @public 8 | * @param {*} collection The collection to loop through. Needs to have a length property set and have indices set from 0 to length - 1. 9 | * @param {function} callback The callback to be called for each element. The element will be given as a parameter to the callback. If this callback returns truthy, the loop is broken and the same value is returned. 10 | * @returns {*} The value that a callback has returned (if truthy). Otherwise nothing. 11 | */ 12 | utils.forEach = function(collection, callback) { 13 | for(var i = 0; i < collection.length; i++) { 14 | var result = callback(collection[i]); 15 | if(result) { 16 | return result; 17 | } 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /src/detection-strategy/object.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Resize detection strategy that injects objects to elements in order to detect resize events. 3 | * Heavily inspired by: http://www.backalleycoder.com/2013/03/18/cross-browser-event-based-element-resize-detection/ 4 | */ 5 | 6 | "use strict"; 7 | 8 | var browserDetector = require("../browser-detector"); 9 | 10 | module.exports = function(options) { 11 | options = options || {}; 12 | var reporter = options.reporter; 13 | var batchProcessor = options.batchProcessor; 14 | var getState = options.stateHandler.getState; 15 | 16 | if(!reporter) { 17 | throw new Error("Missing required dependency: reporter."); 18 | } 19 | 20 | /** 21 | * Adds a resize event listener to the element. 22 | * @public 23 | * @param {element} element The element that should have the listener added. 24 | * @param {function} listener The listener callback to be called for each resize event of the element. The element will be given as a parameter to the listener callback. 25 | */ 26 | function addListener(element, listener) { 27 | function listenerProxy() { 28 | listener(element); 29 | } 30 | 31 | if(browserDetector.isIE(8)) { 32 | //IE 8 does not support object, but supports the resize event directly on elements. 33 | getState(element).object = { 34 | proxy: listenerProxy 35 | }; 36 | element.attachEvent("onresize", listenerProxy); 37 | } else { 38 | var object = getObject(element); 39 | 40 | if(!object) { 41 | throw new Error("Element is not detectable by this strategy."); 42 | } 43 | 44 | object.contentDocument.defaultView.addEventListener("resize", listenerProxy); 45 | } 46 | } 47 | 48 | function buildCssTextString(rules) { 49 | var seperator = options.important ? " !important; " : "; "; 50 | 51 | return (rules.join(seperator) + seperator).trim(); 52 | } 53 | 54 | /** 55 | * Makes an element detectable and ready to be listened for resize events. Will call the callback when the element is ready to be listened for resize changes. 56 | * @private 57 | * @param {object} options Optional options object. 58 | * @param {element} element The element to make detectable 59 | * @param {function} callback The callback to be called when the element is ready to be listened for resize changes. Will be called with the element as first parameter. 60 | */ 61 | function makeDetectable(options, element, callback) { 62 | if (!callback) { 63 | callback = element; 64 | element = options; 65 | options = null; 66 | } 67 | 68 | options = options || {}; 69 | var debug = options.debug; 70 | 71 | function injectObject(element, callback) { 72 | var OBJECT_STYLE = buildCssTextString(["display: block", "position: absolute", "top: 0", "left: 0", "width: 100%", "height: 100%", "border: none", "padding: 0", "margin: 0", "opacity: 0", "z-index: -1000", "pointer-events: none"]); 73 | 74 | //The target element needs to be positioned (everything except static) so the absolute positioned object will be positioned relative to the target element. 75 | 76 | // Position altering may be performed directly or on object load, depending on if style resolution is possible directly or not. 77 | var positionCheckPerformed = false; 78 | 79 | // The element may not yet be attached to the DOM, and therefore the style object may be empty in some browsers. 80 | // Since the style object is a reference, it will be updated as soon as the element is attached to the DOM. 81 | var style = window.getComputedStyle(element); 82 | var width = element.offsetWidth; 83 | var height = element.offsetHeight; 84 | 85 | getState(element).startSize = { 86 | width: width, 87 | height: height 88 | }; 89 | 90 | function mutateDom() { 91 | function alterPositionStyles() { 92 | if(style.position === "static") { 93 | element.style.setProperty("position", "relative", options.important ? "important" : ""); 94 | 95 | var removeRelativeStyles = function(reporter, element, style, property) { 96 | function getNumericalValue(value) { 97 | return value.replace(/[^-\d\.]/g, ""); 98 | } 99 | 100 | var value = style[property]; 101 | 102 | if(value !== "auto" && getNumericalValue(value) !== "0") { 103 | reporter.warn("An element that is positioned static has style." + property + "=" + value + " which is ignored due to the static positioning. The element will need to be positioned relative, so the style." + property + " will be set to 0. Element: ", element); 104 | element.style.setProperty(property, "0", options.important ? "important" : ""); 105 | } 106 | }; 107 | 108 | //Check so that there are no accidental styles that will make the element styled differently now that is is relative. 109 | //If there are any, set them to 0 (this should be okay with the user since the style properties did nothing before [since the element was positioned static] anyway). 110 | removeRelativeStyles(reporter, element, style, "top"); 111 | removeRelativeStyles(reporter, element, style, "right"); 112 | removeRelativeStyles(reporter, element, style, "bottom"); 113 | removeRelativeStyles(reporter, element, style, "left"); 114 | } 115 | } 116 | 117 | function onObjectLoad() { 118 | // The object has been loaded, which means that the element now is guaranteed to be attached to the DOM. 119 | if (!positionCheckPerformed) { 120 | alterPositionStyles(); 121 | } 122 | 123 | /*jshint validthis: true */ 124 | 125 | function getDocument(element, callback) { 126 | //Opera 12 seem to call the object.onload before the actual document has been created. 127 | //So if it is not present, poll it with an timeout until it is present. 128 | //TODO: Could maybe be handled better with object.onreadystatechange or similar. 129 | if(!element.contentDocument) { 130 | var state = getState(element); 131 | if (state.checkForObjectDocumentTimeoutId) { 132 | window.clearTimeout(state.checkForObjectDocumentTimeoutId); 133 | } 134 | state.checkForObjectDocumentTimeoutId = setTimeout(function checkForObjectDocument() { 135 | state.checkForObjectDocumentTimeoutId = 0; 136 | getDocument(element, callback); 137 | }, 100); 138 | 139 | return; 140 | } 141 | 142 | callback(element.contentDocument); 143 | } 144 | 145 | //Mutating the object element here seems to fire another load event. 146 | //Mutating the inner document of the object element is fine though. 147 | var objectElement = this; 148 | 149 | //Create the style element to be added to the object. 150 | getDocument(objectElement, function onObjectDocumentReady(objectDocument) { 151 | //Notify that the element is ready to be listened to. 152 | callback(element); 153 | }); 154 | } 155 | 156 | // The element may be detached from the DOM, and some browsers does not support style resolving of detached elements. 157 | // The alterPositionStyles needs to be delayed until we know the element has been attached to the DOM (which we are sure of when the onObjectLoad has been fired), if style resolution is not possible. 158 | if (style.position !== "") { 159 | alterPositionStyles(style); 160 | positionCheckPerformed = true; 161 | } 162 | 163 | //Add an object element as a child to the target element that will be listened to for resize events. 164 | var object = document.createElement("object"); 165 | object.style.cssText = OBJECT_STYLE; 166 | object.tabIndex = -1; 167 | object.type = "text/html"; 168 | object.setAttribute("aria-hidden", "true"); 169 | object.onload = onObjectLoad; 170 | 171 | //Safari: This must occur before adding the object to the DOM. 172 | //IE: Does not like that this happens before, even if it is also added after. 173 | if(!browserDetector.isIE()) { 174 | object.data = "about:blank"; 175 | } 176 | 177 | if (!getState(element)) { 178 | // The element has been uninstalled before the actual loading happened. 179 | return; 180 | } 181 | 182 | element.appendChild(object); 183 | getState(element).object = object; 184 | 185 | //IE: This must occur after adding the object to the DOM. 186 | if(browserDetector.isIE()) { 187 | object.data = "about:blank"; 188 | } 189 | } 190 | 191 | if(batchProcessor) { 192 | batchProcessor.add(mutateDom); 193 | } else { 194 | mutateDom(); 195 | } 196 | } 197 | 198 | if(browserDetector.isIE(8)) { 199 | //IE 8 does not support objects properly. Luckily they do support the resize event. 200 | //So do not inject the object and notify that the element is already ready to be listened to. 201 | //The event handler for the resize event is attached in the utils.addListener instead. 202 | callback(element); 203 | } else { 204 | injectObject(element, callback); 205 | } 206 | } 207 | 208 | /** 209 | * Returns the child object of the target element. 210 | * @private 211 | * @param {element} element The target element. 212 | * @returns The object element of the target. 213 | */ 214 | function getObject(element) { 215 | return getState(element).object; 216 | } 217 | 218 | function uninstall(element) { 219 | if (!getState(element)) { 220 | return; 221 | } 222 | 223 | var object = getObject(element); 224 | 225 | if (!object) { 226 | return; 227 | } 228 | 229 | if (browserDetector.isIE(8)) { 230 | element.detachEvent("onresize", object.proxy); 231 | } else { 232 | element.removeChild(object); 233 | } 234 | 235 | if (getState(element).checkForObjectDocumentTimeoutId) { 236 | window.clearTimeout(getState(element).checkForObjectDocumentTimeoutId); 237 | } 238 | 239 | delete getState(element).object; 240 | } 241 | 242 | return { 243 | makeDetectable: makeDetectable, 244 | addListener: addListener, 245 | uninstall: uninstall 246 | }; 247 | }; 248 | -------------------------------------------------------------------------------- /src/detection-strategy/scroll.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Resize detection strategy that injects divs to elements in order to detect resize events on scroll events. 3 | * Heavily inspired by: https://github.com/marcj/css-element-queries/blob/master/src/ResizeSensor.js 4 | */ 5 | 6 | "use strict"; 7 | 8 | var forEach = require("../collection-utils").forEach; 9 | 10 | module.exports = function(options) { 11 | options = options || {}; 12 | var reporter = options.reporter; 13 | var batchProcessor = options.batchProcessor; 14 | var getState = options.stateHandler.getState; 15 | var hasState = options.stateHandler.hasState; 16 | var idHandler = options.idHandler; 17 | 18 | if (!batchProcessor) { 19 | throw new Error("Missing required dependency: batchProcessor"); 20 | } 21 | 22 | if (!reporter) { 23 | throw new Error("Missing required dependency: reporter."); 24 | } 25 | 26 | //TODO: Could this perhaps be done at installation time? 27 | var scrollbarSizes = getScrollbarSizes(); 28 | 29 | var styleId = "erd_scroll_detection_scrollbar_style"; 30 | var detectionContainerClass = "erd_scroll_detection_container"; 31 | 32 | function initDocument(targetDocument) { 33 | // Inject the scrollbar styling that prevents them from appearing sometimes in Chrome. 34 | // The injected container needs to have a class, so that it may be styled with CSS (pseudo elements). 35 | injectScrollStyle(targetDocument, styleId, detectionContainerClass); 36 | } 37 | 38 | initDocument(window.document); 39 | 40 | function buildCssTextString(rules) { 41 | var seperator = options.important ? " !important; " : "; "; 42 | 43 | return (rules.join(seperator) + seperator).trim(); 44 | } 45 | 46 | function getScrollbarSizes() { 47 | var width = 500; 48 | var height = 500; 49 | 50 | var child = document.createElement("div"); 51 | child.style.cssText = buildCssTextString(["position: absolute", "width: " + width*2 + "px", "height: " + height*2 + "px", "visibility: hidden", "margin: 0", "padding: 0"]); 52 | 53 | var container = document.createElement("div"); 54 | container.style.cssText = buildCssTextString(["position: absolute", "width: " + width + "px", "height: " + height + "px", "overflow: scroll", "visibility: none", "top: " + -width*3 + "px", "left: " + -height*3 + "px", "visibility: hidden", "margin: 0", "padding: 0"]); 55 | 56 | container.appendChild(child); 57 | 58 | document.body.insertBefore(container, document.body.firstChild); 59 | 60 | var widthSize = width - container.clientWidth; 61 | var heightSize = height - container.clientHeight; 62 | 63 | document.body.removeChild(container); 64 | 65 | return { 66 | width: widthSize, 67 | height: heightSize 68 | }; 69 | } 70 | 71 | function injectScrollStyle(targetDocument, styleId, containerClass) { 72 | function injectStyle(style, method) { 73 | method = method || function (element) { 74 | targetDocument.head.appendChild(element); 75 | }; 76 | 77 | var styleElement = targetDocument.createElement("style"); 78 | styleElement.innerHTML = style; 79 | styleElement.id = styleId; 80 | method(styleElement); 81 | return styleElement; 82 | } 83 | 84 | if (!targetDocument.getElementById(styleId)) { 85 | var containerAnimationClass = containerClass + "_animation"; 86 | var containerAnimationActiveClass = containerClass + "_animation_active"; 87 | var style = "/* Created by the element-resize-detector library. */\n"; 88 | style += "." + containerClass + " > div::-webkit-scrollbar { " + buildCssTextString(["display: none"]) + " }\n\n"; 89 | style += "." + containerAnimationActiveClass + " { " + buildCssTextString(["-webkit-animation-duration: 0.1s", "animation-duration: 0.1s", "-webkit-animation-name: " + containerAnimationClass, "animation-name: " + containerAnimationClass]) + " }\n"; 90 | style += "@-webkit-keyframes " + containerAnimationClass + " { 0% { opacity: 1; } 50% { opacity: 0; } 100% { opacity: 1; } }\n"; 91 | style += "@keyframes " + containerAnimationClass + " { 0% { opacity: 1; } 50% { opacity: 0; } 100% { opacity: 1; } }"; 92 | injectStyle(style); 93 | } 94 | } 95 | 96 | function addAnimationClass(element) { 97 | element.className += " " + detectionContainerClass + "_animation_active"; 98 | } 99 | 100 | function addEvent(el, name, cb) { 101 | if (el.addEventListener) { 102 | el.addEventListener(name, cb); 103 | } else if(el.attachEvent) { 104 | el.attachEvent("on" + name, cb); 105 | } else { 106 | return reporter.error("[scroll] Don't know how to add event listeners."); 107 | } 108 | } 109 | 110 | function removeEvent(el, name, cb) { 111 | if (el.removeEventListener) { 112 | el.removeEventListener(name, cb); 113 | } else if(el.detachEvent) { 114 | el.detachEvent("on" + name, cb); 115 | } else { 116 | return reporter.error("[scroll] Don't know how to remove event listeners."); 117 | } 118 | } 119 | 120 | function getExpandElement(element) { 121 | return getState(element).container.childNodes[0].childNodes[0].childNodes[0]; 122 | } 123 | 124 | function getShrinkElement(element) { 125 | return getState(element).container.childNodes[0].childNodes[0].childNodes[1]; 126 | } 127 | 128 | /** 129 | * Adds a resize event listener to the element. 130 | * @public 131 | * @param {element} element The element that should have the listener added. 132 | * @param {function} listener The listener callback to be called for each resize event of the element. The element will be given as a parameter to the listener callback. 133 | */ 134 | function addListener(element, listener) { 135 | var listeners = getState(element).listeners; 136 | 137 | if (!listeners.push) { 138 | throw new Error("Cannot add listener to an element that is not detectable."); 139 | } 140 | 141 | getState(element).listeners.push(listener); 142 | } 143 | 144 | /** 145 | * Makes an element detectable and ready to be listened for resize events. Will call the callback when the element is ready to be listened for resize changes. 146 | * @private 147 | * @param {object} options Optional options object. 148 | * @param {element} element The element to make detectable 149 | * @param {function} callback The callback to be called when the element is ready to be listened for resize changes. Will be called with the element as first parameter. 150 | */ 151 | function makeDetectable(options, element, callback) { 152 | if (!callback) { 153 | callback = element; 154 | element = options; 155 | options = null; 156 | } 157 | 158 | options = options || {}; 159 | 160 | function debug() { 161 | if (options.debug) { 162 | var args = Array.prototype.slice.call(arguments); 163 | args.unshift(idHandler.get(element), "Scroll: "); 164 | if (reporter.log.apply) { 165 | reporter.log.apply(null, args); 166 | } else { 167 | for (var i = 0; i < args.length; i++) { 168 | reporter.log(args[i]); 169 | } 170 | } 171 | } 172 | } 173 | 174 | function isDetached(element) { 175 | function isInDocument(element) { 176 | var isInShadowRoot = element.getRootNode && element.getRootNode().contains(element); 177 | return element === element.ownerDocument.body || element.ownerDocument.body.contains(element) || isInShadowRoot; 178 | } 179 | 180 | if (!isInDocument(element)) { 181 | return true; 182 | } 183 | 184 | // FireFox returns null style in hidden iframes. See https://github.com/wnr/element-resize-detector/issues/68 and https://bugzilla.mozilla.org/show_bug.cgi?id=795520 185 | if (window.getComputedStyle(element) === null) { 186 | return true; 187 | } 188 | 189 | return false; 190 | } 191 | 192 | function isUnrendered(element) { 193 | // Check the absolute positioned container since the top level container is display: inline. 194 | var container = getState(element).container.childNodes[0]; 195 | var style = window.getComputedStyle(container); 196 | return !style.width || style.width.indexOf("px") === -1; //Can only compute pixel value when rendered. 197 | } 198 | 199 | function getStyle() { 200 | // Some browsers only force layouts when actually reading the style properties of the style object, so make sure that they are all read here, 201 | // so that the user of the function can be sure that it will perform the layout here, instead of later (important for batching). 202 | var elementStyle = window.getComputedStyle(element); 203 | var style = {}; 204 | style.position = elementStyle.position; 205 | style.width = element.offsetWidth; 206 | style.height = element.offsetHeight; 207 | style.top = elementStyle.top; 208 | style.right = elementStyle.right; 209 | style.bottom = elementStyle.bottom; 210 | style.left = elementStyle.left; 211 | style.widthCSS = elementStyle.width; 212 | style.heightCSS = elementStyle.height; 213 | return style; 214 | } 215 | 216 | function storeStartSize() { 217 | var style = getStyle(); 218 | getState(element).startSize = { 219 | width: style.width, 220 | height: style.height 221 | }; 222 | debug("Element start size", getState(element).startSize); 223 | } 224 | 225 | function initListeners() { 226 | getState(element).listeners = []; 227 | } 228 | 229 | function storeStyle() { 230 | debug("storeStyle invoked."); 231 | if (!getState(element)) { 232 | debug("Aborting because element has been uninstalled"); 233 | return; 234 | } 235 | 236 | var style = getStyle(); 237 | getState(element).style = style; 238 | } 239 | 240 | function storeCurrentSize(element, width, height) { 241 | getState(element).lastWidth = width; 242 | getState(element).lastHeight = height; 243 | } 244 | 245 | function getExpandChildElement(element) { 246 | return getExpandElement(element).childNodes[0]; 247 | } 248 | 249 | function getWidthOffset() { 250 | return 2 * scrollbarSizes.width + 1; 251 | } 252 | 253 | function getHeightOffset() { 254 | return 2 * scrollbarSizes.height + 1; 255 | } 256 | 257 | function getExpandWidth(width) { 258 | return width + 10 + getWidthOffset(); 259 | } 260 | 261 | function getExpandHeight(height) { 262 | return height + 10 + getHeightOffset(); 263 | } 264 | 265 | function getShrinkWidth(width) { 266 | return width * 2 + getWidthOffset(); 267 | } 268 | 269 | function getShrinkHeight(height) { 270 | return height * 2 + getHeightOffset(); 271 | } 272 | 273 | function positionScrollbars(element, width, height) { 274 | var expand = getExpandElement(element); 275 | var shrink = getShrinkElement(element); 276 | var expandWidth = getExpandWidth(width); 277 | var expandHeight = getExpandHeight(height); 278 | var shrinkWidth = getShrinkWidth(width); 279 | var shrinkHeight = getShrinkHeight(height); 280 | expand.scrollLeft = expandWidth; 281 | expand.scrollTop = expandHeight; 282 | shrink.scrollLeft = shrinkWidth; 283 | shrink.scrollTop = shrinkHeight; 284 | } 285 | 286 | function injectContainerElement() { 287 | var container = getState(element).container; 288 | 289 | if (!container) { 290 | container = document.createElement("div"); 291 | container.className = detectionContainerClass; 292 | container.style.cssText = buildCssTextString(["visibility: hidden", "display: inline", "width: 0px", "height: 0px", "z-index: -1", "overflow: hidden", "margin: 0", "padding: 0"]); 293 | getState(element).container = container; 294 | addAnimationClass(container); 295 | element.appendChild(container); 296 | 297 | var onAnimationStart = function () { 298 | getState(element).onRendered && getState(element).onRendered(); 299 | }; 300 | 301 | addEvent(container, "animationstart", onAnimationStart); 302 | 303 | // Store the event handler here so that they may be removed when uninstall is called. 304 | // See uninstall function for an explanation why it is needed. 305 | getState(element).onAnimationStart = onAnimationStart; 306 | } 307 | 308 | return container; 309 | } 310 | 311 | function injectScrollElements() { 312 | function alterPositionStyles() { 313 | var style = getState(element).style; 314 | 315 | if(style.position === "static") { 316 | element.style.setProperty("position", "relative",options.important ? "important" : ""); 317 | 318 | var removeRelativeStyles = function(reporter, element, style, property) { 319 | function getNumericalValue(value) { 320 | return value.replace(/[^-\d\.]/g, ""); 321 | } 322 | 323 | var value = style[property]; 324 | 325 | if(value !== "auto" && getNumericalValue(value) !== "0") { 326 | reporter.warn("An element that is positioned static has style." + property + "=" + value + " which is ignored due to the static positioning. The element will need to be positioned relative, so the style." + property + " will be set to 0. Element: ", element); 327 | element.style[property] = 0; 328 | } 329 | }; 330 | 331 | //Check so that there are no accidental styles that will make the element styled differently now that is is relative. 332 | //If there are any, set them to 0 (this should be okay with the user since the style properties did nothing before [since the element was positioned static] anyway). 333 | removeRelativeStyles(reporter, element, style, "top"); 334 | removeRelativeStyles(reporter, element, style, "right"); 335 | removeRelativeStyles(reporter, element, style, "bottom"); 336 | removeRelativeStyles(reporter, element, style, "left"); 337 | } 338 | } 339 | 340 | function getLeftTopBottomRightCssText(left, top, bottom, right) { 341 | left = (!left ? "0" : (left + "px")); 342 | top = (!top ? "0" : (top + "px")); 343 | bottom = (!bottom ? "0" : (bottom + "px")); 344 | right = (!right ? "0" : (right + "px")); 345 | 346 | return ["left: " + left, "top: " + top, "right: " + right, "bottom: " + bottom]; 347 | } 348 | 349 | debug("Injecting elements"); 350 | 351 | if (!getState(element)) { 352 | debug("Aborting because element has been uninstalled"); 353 | return; 354 | } 355 | 356 | alterPositionStyles(); 357 | 358 | var rootContainer = getState(element).container; 359 | 360 | if (!rootContainer) { 361 | rootContainer = injectContainerElement(); 362 | } 363 | 364 | // Due to this WebKit bug https://bugs.webkit.org/show_bug.cgi?id=80808 (currently fixed in Blink, but still present in WebKit browsers such as Safari), 365 | // we need to inject two containers, one that is width/height 100% and another that is left/top -1px so that the final container always is 1x1 pixels bigger than 366 | // the targeted element. 367 | // When the bug is resolved, "containerContainer" may be removed. 368 | 369 | // The outer container can occasionally be less wide than the targeted when inside inline elements element in WebKit (see https://bugs.webkit.org/show_bug.cgi?id=152980). 370 | // This should be no problem since the inner container either way makes sure the injected scroll elements are at least 1x1 px. 371 | 372 | var scrollbarWidth = scrollbarSizes.width; 373 | var scrollbarHeight = scrollbarSizes.height; 374 | var containerContainerStyle = buildCssTextString(["position: absolute", "flex: none", "overflow: hidden", "z-index: -1", "visibility: hidden", "width: 100%", "height: 100%", "left: 0px", "top: 0px"]); 375 | var containerStyle = buildCssTextString(["position: absolute", "flex: none", "overflow: hidden", "z-index: -1", "visibility: hidden"].concat(getLeftTopBottomRightCssText(-(1 + scrollbarWidth), -(1 + scrollbarHeight), -scrollbarHeight, -scrollbarWidth))); 376 | var expandStyle = buildCssTextString(["position: absolute", "flex: none", "overflow: scroll", "z-index: -1", "visibility: hidden", "width: 100%", "height: 100%"]); 377 | var shrinkStyle = buildCssTextString(["position: absolute", "flex: none", "overflow: scroll", "z-index: -1", "visibility: hidden", "width: 100%", "height: 100%"]); 378 | var expandChildStyle = buildCssTextString(["position: absolute", "left: 0", "top: 0"]); 379 | var shrinkChildStyle = buildCssTextString(["position: absolute", "width: 200%", "height: 200%"]); 380 | 381 | var containerContainer = document.createElement("div"); 382 | var container = document.createElement("div"); 383 | var expand = document.createElement("div"); 384 | var expandChild = document.createElement("div"); 385 | var shrink = document.createElement("div"); 386 | var shrinkChild = document.createElement("div"); 387 | 388 | // Some browsers choke on the resize system being rtl, so force it to ltr. https://github.com/wnr/element-resize-detector/issues/56 389 | // However, dir should not be set on the top level container as it alters the dimensions of the target element in some browsers. 390 | containerContainer.dir = "ltr"; 391 | 392 | containerContainer.style.cssText = containerContainerStyle; 393 | containerContainer.className = detectionContainerClass; 394 | container.className = detectionContainerClass; 395 | container.style.cssText = containerStyle; 396 | expand.style.cssText = expandStyle; 397 | expandChild.style.cssText = expandChildStyle; 398 | shrink.style.cssText = shrinkStyle; 399 | shrinkChild.style.cssText = shrinkChildStyle; 400 | 401 | expand.appendChild(expandChild); 402 | shrink.appendChild(shrinkChild); 403 | container.appendChild(expand); 404 | container.appendChild(shrink); 405 | containerContainer.appendChild(container); 406 | rootContainer.appendChild(containerContainer); 407 | 408 | function onExpandScroll() { 409 | var state = getState(element); 410 | if (state && state.onExpand) { 411 | state.onExpand(); 412 | } else { 413 | debug("Aborting expand scroll handler: element has been uninstalled"); 414 | } 415 | } 416 | 417 | function onShrinkScroll() { 418 | var state = getState(element); 419 | if (state && state.onShrink) { 420 | state.onShrink(); 421 | } else { 422 | debug("Aborting shrink scroll handler: element has been uninstalled"); 423 | } 424 | } 425 | 426 | addEvent(expand, "scroll", onExpandScroll); 427 | addEvent(shrink, "scroll", onShrinkScroll); 428 | 429 | // Store the event handlers here so that they may be removed when uninstall is called. 430 | // See uninstall function for an explanation why it is needed. 431 | getState(element).onExpandScroll = onExpandScroll; 432 | getState(element).onShrinkScroll = onShrinkScroll; 433 | } 434 | 435 | function registerListenersAndPositionElements() { 436 | function updateChildSizes(element, width, height) { 437 | var expandChild = getExpandChildElement(element); 438 | var expandWidth = getExpandWidth(width); 439 | var expandHeight = getExpandHeight(height); 440 | expandChild.style.setProperty("width", expandWidth + "px", options.important ? "important" : ""); 441 | expandChild.style.setProperty("height", expandHeight + "px", options.important ? "important" : ""); 442 | } 443 | 444 | function updateDetectorElements(done) { 445 | var width = element.offsetWidth; 446 | var height = element.offsetHeight; 447 | 448 | // Check whether the size has actually changed since last time the algorithm ran. If not, some steps may be skipped. 449 | var sizeChanged = width !== getState(element).lastWidth || height !== getState(element).lastHeight; 450 | 451 | debug("Storing current size", width, height); 452 | 453 | // Store the size of the element sync here, so that multiple scroll events may be ignored in the event listeners. 454 | // Otherwise the if-check in handleScroll is useless. 455 | storeCurrentSize(element, width, height); 456 | 457 | // Since we delay the processing of the batch, there is a risk that uninstall has been called before the batch gets to execute. 458 | // Since there is no way to cancel the fn executions, we need to add an uninstall guard to all fns of the batch. 459 | 460 | batchProcessor.add(0, function performUpdateChildSizes() { 461 | if (!sizeChanged) { 462 | return; 463 | } 464 | 465 | if (!getState(element)) { 466 | debug("Aborting because element has been uninstalled"); 467 | return; 468 | } 469 | 470 | if (!areElementsInjected()) { 471 | debug("Aborting because element container has not been initialized"); 472 | return; 473 | } 474 | 475 | if (options.debug) { 476 | var w = element.offsetWidth; 477 | var h = element.offsetHeight; 478 | 479 | if (w !== width || h !== height) { 480 | reporter.warn(idHandler.get(element), "Scroll: Size changed before updating detector elements."); 481 | } 482 | } 483 | 484 | updateChildSizes(element, width, height); 485 | }); 486 | 487 | batchProcessor.add(1, function updateScrollbars() { 488 | // This function needs to be invoked event though the size is unchanged. The element could have been resized very quickly and then 489 | // been restored to the original size, which will have changed the scrollbar positions. 490 | 491 | if (!getState(element)) { 492 | debug("Aborting because element has been uninstalled"); 493 | return; 494 | } 495 | 496 | if (!areElementsInjected()) { 497 | debug("Aborting because element container has not been initialized"); 498 | return; 499 | } 500 | 501 | positionScrollbars(element, width, height); 502 | }); 503 | 504 | if (sizeChanged && done) { 505 | batchProcessor.add(2, function () { 506 | if (!getState(element)) { 507 | debug("Aborting because element has been uninstalled"); 508 | return; 509 | } 510 | 511 | if (!areElementsInjected()) { 512 | debug("Aborting because element container has not been initialized"); 513 | return; 514 | } 515 | 516 | done(); 517 | }); 518 | } 519 | } 520 | 521 | function areElementsInjected() { 522 | return !!getState(element).container; 523 | } 524 | 525 | function notifyListenersIfNeeded() { 526 | function isFirstNotify() { 527 | return getState(element).lastNotifiedWidth === undefined; 528 | } 529 | 530 | debug("notifyListenersIfNeeded invoked"); 531 | 532 | var state = getState(element); 533 | 534 | // Don't notify if the current size is the start size, and this is the first notification. 535 | if (isFirstNotify() && state.lastWidth === state.startSize.width && state.lastHeight === state.startSize.height) { 536 | return debug("Not notifying: Size is the same as the start size, and there has been no notification yet."); 537 | } 538 | 539 | // Don't notify if the size already has been notified. 540 | if (state.lastWidth === state.lastNotifiedWidth && state.lastHeight === state.lastNotifiedHeight) { 541 | return debug("Not notifying: Size already notified"); 542 | } 543 | 544 | 545 | debug("Current size not notified, notifying..."); 546 | state.lastNotifiedWidth = state.lastWidth; 547 | state.lastNotifiedHeight = state.lastHeight; 548 | forEach(getState(element).listeners, function (listener) { 549 | listener(element); 550 | }); 551 | } 552 | 553 | function handleRender() { 554 | debug("startanimation triggered."); 555 | 556 | if (isUnrendered(element)) { 557 | debug("Ignoring since element is still unrendered..."); 558 | return; 559 | } 560 | 561 | debug("Element rendered."); 562 | var expand = getExpandElement(element); 563 | var shrink = getShrinkElement(element); 564 | if (expand.scrollLeft === 0 || expand.scrollTop === 0 || shrink.scrollLeft === 0 || shrink.scrollTop === 0) { 565 | debug("Scrollbars out of sync. Updating detector elements..."); 566 | updateDetectorElements(notifyListenersIfNeeded); 567 | } 568 | } 569 | 570 | function handleScroll() { 571 | debug("Scroll detected."); 572 | 573 | if (isUnrendered(element)) { 574 | // Element is still unrendered. Skip this scroll event. 575 | debug("Scroll event fired while unrendered. Ignoring..."); 576 | return; 577 | } 578 | 579 | updateDetectorElements(notifyListenersIfNeeded); 580 | } 581 | 582 | debug("registerListenersAndPositionElements invoked."); 583 | 584 | if (!getState(element)) { 585 | debug("Aborting because element has been uninstalled"); 586 | return; 587 | } 588 | 589 | getState(element).onRendered = handleRender; 590 | getState(element).onExpand = handleScroll; 591 | getState(element).onShrink = handleScroll; 592 | 593 | var style = getState(element).style; 594 | updateChildSizes(element, style.width, style.height); 595 | } 596 | 597 | function finalizeDomMutation() { 598 | debug("finalizeDomMutation invoked."); 599 | 600 | if (!getState(element)) { 601 | debug("Aborting because element has been uninstalled"); 602 | return; 603 | } 604 | 605 | var style = getState(element).style; 606 | storeCurrentSize(element, style.width, style.height); 607 | positionScrollbars(element, style.width, style.height); 608 | } 609 | 610 | function ready() { 611 | callback(element); 612 | } 613 | 614 | function install() { 615 | debug("Installing..."); 616 | initListeners(); 617 | storeStartSize(); 618 | 619 | batchProcessor.add(0, storeStyle); 620 | batchProcessor.add(1, injectScrollElements); 621 | batchProcessor.add(2, registerListenersAndPositionElements); 622 | batchProcessor.add(3, finalizeDomMutation); 623 | batchProcessor.add(4, ready); 624 | } 625 | 626 | debug("Making detectable..."); 627 | 628 | if (isDetached(element)) { 629 | debug("Element is detached"); 630 | 631 | injectContainerElement(); 632 | 633 | debug("Waiting until element is attached..."); 634 | 635 | getState(element).onRendered = function () { 636 | debug("Element is now attached"); 637 | install(); 638 | }; 639 | } else { 640 | install(); 641 | } 642 | } 643 | 644 | function uninstall(element) { 645 | var state = getState(element); 646 | 647 | if (!state) { 648 | // Uninstall has been called on a non-erd element. 649 | return; 650 | } 651 | 652 | // Uninstall may have been called in the following scenarios: 653 | // (1) Right between the sync code and async batch (here state.busy = true, but nothing have been registered or injected). 654 | // (2) In the ready callback of the last level of the batch by another element (here, state.busy = true, but all the stuff has been injected). 655 | // (3) After the installation process (here, state.busy = false and all the stuff has been injected). 656 | // So to be on the safe side, let's check for each thing before removing. 657 | 658 | // We need to remove the event listeners, because otherwise the event might fire on an uninstall element which results in an error when trying to get the state of the element. 659 | state.onExpandScroll && removeEvent(getExpandElement(element), "scroll", state.onExpandScroll); 660 | state.onShrinkScroll && removeEvent(getShrinkElement(element), "scroll", state.onShrinkScroll); 661 | state.onAnimationStart && removeEvent(state.container, "animationstart", state.onAnimationStart); 662 | 663 | state.container && element.removeChild(state.container); 664 | } 665 | 666 | return { 667 | makeDetectable: makeDetectable, 668 | addListener: addListener, 669 | uninstall: uninstall, 670 | initDocument: initDocument 671 | }; 672 | }; 673 | -------------------------------------------------------------------------------- /src/element-resize-detector.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var forEach = require("./collection-utils").forEach; 4 | var elementUtilsMaker = require("./element-utils"); 5 | var listenerHandlerMaker = require("./listener-handler"); 6 | var idGeneratorMaker = require("./id-generator"); 7 | var idHandlerMaker = require("./id-handler"); 8 | var reporterMaker = require("./reporter"); 9 | var browserDetector = require("./browser-detector"); 10 | var batchProcessorMaker = require("batch-processor"); 11 | var stateHandler = require("./state-handler"); 12 | 13 | //Detection strategies. 14 | var objectStrategyMaker = require("./detection-strategy/object.js"); 15 | var scrollStrategyMaker = require("./detection-strategy/scroll.js"); 16 | 17 | function isCollection(obj) { 18 | return Array.isArray(obj) || obj.length !== undefined; 19 | } 20 | 21 | function toArray(collection) { 22 | if (!Array.isArray(collection)) { 23 | var array = []; 24 | forEach(collection, function (obj) { 25 | array.push(obj); 26 | }); 27 | return array; 28 | } else { 29 | return collection; 30 | } 31 | } 32 | 33 | function isElement(obj) { 34 | return obj && obj.nodeType === 1; 35 | } 36 | 37 | /** 38 | * @typedef idHandler 39 | * @type {object} 40 | * @property {function} get Gets the resize detector id of the element. 41 | * @property {function} set Generate and sets the resize detector id of the element. 42 | */ 43 | 44 | /** 45 | * @typedef Options 46 | * @type {object} 47 | * @property {boolean} callOnAdd Determines if listeners should be called when they are getting added. 48 | Default is true. If true, the listener is guaranteed to be called when it has been added. 49 | If false, the listener will not be guarenteed to be called when it has been added (does not prevent it from being called). 50 | * @property {idHandler} idHandler A custom id handler that is responsible for generating, setting and retrieving id's for elements. 51 | If not provided, a default id handler will be used. 52 | * @property {reporter} reporter A custom reporter that handles reporting logs, warnings and errors. 53 | If not provided, a default id handler will be used. 54 | If set to false, then nothing will be reported. 55 | * @property {boolean} debug If set to true, the the system will report debug messages as default for the listenTo method. 56 | */ 57 | 58 | /** 59 | * Creates an element resize detector instance. 60 | * @public 61 | * @param {Options?} options Optional global options object that will decide how this instance will work. 62 | */ 63 | module.exports = function(options) { 64 | options = options || {}; 65 | 66 | //idHandler is currently not an option to the listenTo function, so it should not be added to globalOptions. 67 | var idHandler; 68 | 69 | if (options.idHandler) { 70 | // To maintain compatability with idHandler.get(element, readonly), make sure to wrap the given idHandler 71 | // so that readonly flag always is true when it's used here. This may be removed next major version bump. 72 | idHandler = { 73 | get: function (element) { return options.idHandler.get(element, true); }, 74 | set: options.idHandler.set 75 | }; 76 | } else { 77 | var idGenerator = idGeneratorMaker(); 78 | var defaultIdHandler = idHandlerMaker({ 79 | idGenerator: idGenerator, 80 | stateHandler: stateHandler 81 | }); 82 | idHandler = defaultIdHandler; 83 | } 84 | 85 | //reporter is currently not an option to the listenTo function, so it should not be added to globalOptions. 86 | var reporter = options.reporter; 87 | 88 | if(!reporter) { 89 | //If options.reporter is false, then the reporter should be quiet. 90 | var quiet = reporter === false; 91 | reporter = reporterMaker(quiet); 92 | } 93 | 94 | //batchProcessor is currently not an option to the listenTo function, so it should not be added to globalOptions. 95 | var batchProcessor = getOption(options, "batchProcessor", batchProcessorMaker({ reporter: reporter })); 96 | 97 | //Options to be used as default for the listenTo function. 98 | var globalOptions = {}; 99 | globalOptions.callOnAdd = !!getOption(options, "callOnAdd", true); 100 | globalOptions.debug = !!getOption(options, "debug", false); 101 | 102 | var eventListenerHandler = listenerHandlerMaker(idHandler); 103 | var elementUtils = elementUtilsMaker({ 104 | stateHandler: stateHandler 105 | }); 106 | 107 | //The detection strategy to be used. 108 | var detectionStrategy; 109 | var desiredStrategy = getOption(options, "strategy", "object"); 110 | var importantCssRules = getOption(options, "important", false); 111 | var strategyOptions = { 112 | reporter: reporter, 113 | batchProcessor: batchProcessor, 114 | stateHandler: stateHandler, 115 | idHandler: idHandler, 116 | important: importantCssRules 117 | }; 118 | 119 | if(desiredStrategy === "scroll") { 120 | if (browserDetector.isLegacyOpera()) { 121 | reporter.warn("Scroll strategy is not supported on legacy Opera. Changing to object strategy."); 122 | desiredStrategy = "object"; 123 | } else if (browserDetector.isIE(9)) { 124 | reporter.warn("Scroll strategy is not supported on IE9. Changing to object strategy."); 125 | desiredStrategy = "object"; 126 | } 127 | } 128 | 129 | if(desiredStrategy === "scroll") { 130 | detectionStrategy = scrollStrategyMaker(strategyOptions); 131 | } else if(desiredStrategy === "object") { 132 | detectionStrategy = objectStrategyMaker(strategyOptions); 133 | } else { 134 | throw new Error("Invalid strategy name: " + desiredStrategy); 135 | } 136 | 137 | //Calls can be made to listenTo with elements that are still being installed. 138 | //Also, same elements can occur in the elements list in the listenTo function. 139 | //With this map, the ready callbacks can be synchronized between the calls 140 | //so that the ready callback can always be called when an element is ready - even if 141 | //it wasn't installed from the function itself. 142 | var onReadyCallbacks = {}; 143 | 144 | /** 145 | * Makes the given elements resize-detectable and starts listening to resize events on the elements. Calls the event callback for each event for each element. 146 | * @public 147 | * @param {Options?} options Optional options object. These options will override the global options. Some options may not be overriden, such as idHandler. 148 | * @param {element[]|element} elements The given array of elements to detect resize events of. Single element is also valid. 149 | * @param {function} listener The callback to be executed for each resize event for each element. 150 | */ 151 | function listenTo(options, elements, listener) { 152 | function onResizeCallback(element) { 153 | var listeners = eventListenerHandler.get(element); 154 | forEach(listeners, function callListenerProxy(listener) { 155 | listener(element); 156 | }); 157 | } 158 | 159 | function addListener(callOnAdd, element, listener) { 160 | eventListenerHandler.add(element, listener); 161 | 162 | if(callOnAdd) { 163 | listener(element); 164 | } 165 | } 166 | 167 | //Options object may be omitted. 168 | if(!listener) { 169 | listener = elements; 170 | elements = options; 171 | options = {}; 172 | } 173 | 174 | if(!elements) { 175 | throw new Error("At least one element required."); 176 | } 177 | 178 | if(!listener) { 179 | throw new Error("Listener required."); 180 | } 181 | 182 | if (isElement(elements)) { 183 | // A single element has been passed in. 184 | elements = [elements]; 185 | } else if (isCollection(elements)) { 186 | // Convert collection to array for plugins. 187 | // TODO: May want to check so that all the elements in the collection are valid elements. 188 | elements = toArray(elements); 189 | } else { 190 | return reporter.error("Invalid arguments. Must be a DOM element or a collection of DOM elements."); 191 | } 192 | 193 | var elementsReady = 0; 194 | 195 | var callOnAdd = getOption(options, "callOnAdd", globalOptions.callOnAdd); 196 | var onReadyCallback = getOption(options, "onReady", function noop() {}); 197 | var debug = getOption(options, "debug", globalOptions.debug); 198 | 199 | forEach(elements, function attachListenerToElement(element) { 200 | if (!stateHandler.getState(element)) { 201 | stateHandler.initState(element); 202 | idHandler.set(element); 203 | } 204 | 205 | var id = idHandler.get(element); 206 | 207 | debug && reporter.log("Attaching listener to element", id, element); 208 | 209 | if(!elementUtils.isDetectable(element)) { 210 | debug && reporter.log(id, "Not detectable."); 211 | if(elementUtils.isBusy(element)) { 212 | debug && reporter.log(id, "System busy making it detectable"); 213 | 214 | //The element is being prepared to be detectable. Do not make it detectable. 215 | //Just add the listener, because the element will soon be detectable. 216 | addListener(callOnAdd, element, listener); 217 | onReadyCallbacks[id] = onReadyCallbacks[id] || []; 218 | onReadyCallbacks[id].push(function onReady() { 219 | elementsReady++; 220 | 221 | if(elementsReady === elements.length) { 222 | onReadyCallback(); 223 | } 224 | }); 225 | return; 226 | } 227 | 228 | debug && reporter.log(id, "Making detectable..."); 229 | //The element is not prepared to be detectable, so do prepare it and add a listener to it. 230 | elementUtils.markBusy(element, true); 231 | return detectionStrategy.makeDetectable({ debug: debug, important: importantCssRules }, element, function onElementDetectable(element) { 232 | debug && reporter.log(id, "onElementDetectable"); 233 | 234 | if (stateHandler.getState(element)) { 235 | elementUtils.markAsDetectable(element); 236 | elementUtils.markBusy(element, false); 237 | detectionStrategy.addListener(element, onResizeCallback); 238 | addListener(callOnAdd, element, listener); 239 | 240 | // Since the element size might have changed since the call to "listenTo", we need to check for this change, 241 | // so that a resize event may be emitted. 242 | // Having the startSize object is optional (since it does not make sense in some cases such as unrendered elements), so check for its existance before. 243 | // Also, check the state existance before since the element may have been uninstalled in the installation process. 244 | var state = stateHandler.getState(element); 245 | if (state && state.startSize) { 246 | var width = element.offsetWidth; 247 | var height = element.offsetHeight; 248 | if (state.startSize.width !== width || state.startSize.height !== height) { 249 | onResizeCallback(element); 250 | } 251 | } 252 | 253 | if(onReadyCallbacks[id]) { 254 | forEach(onReadyCallbacks[id], function(callback) { 255 | callback(); 256 | }); 257 | } 258 | } else { 259 | // The element has been unisntalled before being detectable. 260 | debug && reporter.log(id, "Element uninstalled before being detectable."); 261 | } 262 | 263 | delete onReadyCallbacks[id]; 264 | 265 | elementsReady++; 266 | if(elementsReady === elements.length) { 267 | onReadyCallback(); 268 | } 269 | }); 270 | } 271 | 272 | debug && reporter.log(id, "Already detecable, adding listener."); 273 | 274 | //The element has been prepared to be detectable and is ready to be listened to. 275 | addListener(callOnAdd, element, listener); 276 | elementsReady++; 277 | }); 278 | 279 | if(elementsReady === elements.length) { 280 | onReadyCallback(); 281 | } 282 | } 283 | 284 | function uninstall(elements) { 285 | if(!elements) { 286 | return reporter.error("At least one element is required."); 287 | } 288 | 289 | if (isElement(elements)) { 290 | // A single element has been passed in. 291 | elements = [elements]; 292 | } else if (isCollection(elements)) { 293 | // Convert collection to array for plugins. 294 | // TODO: May want to check so that all the elements in the collection are valid elements. 295 | elements = toArray(elements); 296 | } else { 297 | return reporter.error("Invalid arguments. Must be a DOM element or a collection of DOM elements."); 298 | } 299 | 300 | forEach(elements, function (element) { 301 | eventListenerHandler.removeAllListeners(element); 302 | detectionStrategy.uninstall(element); 303 | stateHandler.cleanState(element); 304 | }); 305 | } 306 | 307 | function initDocument(targetDocument) { 308 | detectionStrategy.initDocument && detectionStrategy.initDocument(targetDocument); 309 | } 310 | 311 | return { 312 | listenTo: listenTo, 313 | removeListener: eventListenerHandler.removeListener, 314 | removeAllListeners: eventListenerHandler.removeAllListeners, 315 | uninstall: uninstall, 316 | initDocument: initDocument 317 | }; 318 | }; 319 | 320 | function getOption(options, name, defaultValue) { 321 | var value = options[name]; 322 | 323 | if((value === undefined || value === null) && defaultValue !== undefined) { 324 | return defaultValue; 325 | } 326 | 327 | return value; 328 | } 329 | -------------------------------------------------------------------------------- /src/element-utils.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | module.exports = function(options) { 4 | var getState = options.stateHandler.getState; 5 | 6 | /** 7 | * Tells if the element has been made detectable and ready to be listened for resize events. 8 | * @public 9 | * @param {element} The element to check. 10 | * @returns {boolean} True or false depending on if the element is detectable or not. 11 | */ 12 | function isDetectable(element) { 13 | var state = getState(element); 14 | return state && !!state.isDetectable; 15 | } 16 | 17 | /** 18 | * Marks the element that it has been made detectable and ready to be listened for resize events. 19 | * @public 20 | * @param {element} The element to mark. 21 | */ 22 | function markAsDetectable(element) { 23 | getState(element).isDetectable = true; 24 | } 25 | 26 | /** 27 | * Tells if the element is busy or not. 28 | * @public 29 | * @param {element} The element to check. 30 | * @returns {boolean} True or false depending on if the element is busy or not. 31 | */ 32 | function isBusy(element) { 33 | return !!getState(element).busy; 34 | } 35 | 36 | /** 37 | * Marks the object is busy and should not be made detectable. 38 | * @public 39 | * @param {element} element The element to mark. 40 | * @param {boolean} busy If the element is busy or not. 41 | */ 42 | function markBusy(element, busy) { 43 | getState(element).busy = !!busy; 44 | } 45 | 46 | return { 47 | isDetectable: isDetectable, 48 | markAsDetectable: markAsDetectable, 49 | isBusy: isBusy, 50 | markBusy: markBusy 51 | }; 52 | }; 53 | -------------------------------------------------------------------------------- /src/id-generator.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | module.exports = function() { 4 | var idCount = 1; 5 | 6 | /** 7 | * Generates a new unique id in the context. 8 | * @public 9 | * @returns {number} A unique id in the context. 10 | */ 11 | function generate() { 12 | return idCount++; 13 | } 14 | 15 | return { 16 | generate: generate 17 | }; 18 | }; 19 | -------------------------------------------------------------------------------- /src/id-handler.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | module.exports = function(options) { 4 | var idGenerator = options.idGenerator; 5 | var getState = options.stateHandler.getState; 6 | 7 | /** 8 | * Gets the resize detector id of the element. 9 | * @public 10 | * @param {element} element The target element to get the id of. 11 | * @returns {string|number|null} The id of the element. Null if it has no id. 12 | */ 13 | function getId(element) { 14 | var state = getState(element); 15 | 16 | if (state && state.id !== undefined) { 17 | return state.id; 18 | } 19 | 20 | return null; 21 | } 22 | 23 | /** 24 | * Sets the resize detector id of the element. Requires the element to have a resize detector state initialized. 25 | * @public 26 | * @param {element} element The target element to set the id of. 27 | * @returns {string|number|null} The id of the element. 28 | */ 29 | function setId(element) { 30 | var state = getState(element); 31 | 32 | if (!state) { 33 | throw new Error("setId required the element to have a resize detection state."); 34 | } 35 | 36 | var id = idGenerator.generate(); 37 | 38 | state.id = id; 39 | 40 | return id; 41 | } 42 | 43 | return { 44 | get: getId, 45 | set: setId 46 | }; 47 | }; 48 | -------------------------------------------------------------------------------- /src/listener-handler.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | module.exports = function(idHandler) { 4 | var eventListeners = {}; 5 | 6 | /** 7 | * Gets all listeners for the given element. 8 | * @public 9 | * @param {element} element The element to get all listeners for. 10 | * @returns All listeners for the given element. 11 | */ 12 | function getListeners(element) { 13 | var id = idHandler.get(element); 14 | 15 | if (id === undefined) { 16 | return []; 17 | } 18 | 19 | return eventListeners[id] || []; 20 | } 21 | 22 | /** 23 | * Stores the given listener for the given element. Will not actually add the listener to the element. 24 | * @public 25 | * @param {element} element The element that should have the listener added. 26 | * @param {function} listener The callback that the element has added. 27 | */ 28 | function addListener(element, listener) { 29 | var id = idHandler.get(element); 30 | 31 | if(!eventListeners[id]) { 32 | eventListeners[id] = []; 33 | } 34 | 35 | eventListeners[id].push(listener); 36 | } 37 | 38 | function removeListener(element, listener) { 39 | var listeners = getListeners(element); 40 | for (var i = 0, len = listeners.length; i < len; ++i) { 41 | if (listeners[i] === listener) { 42 | listeners.splice(i, 1); 43 | break; 44 | } 45 | } 46 | } 47 | 48 | function removeAllListeners(element) { 49 | var listeners = getListeners(element); 50 | if (!listeners) { return; } 51 | listeners.length = 0; 52 | } 53 | 54 | return { 55 | get: getListeners, 56 | add: addListener, 57 | removeListener: removeListener, 58 | removeAllListeners: removeAllListeners 59 | }; 60 | }; 61 | -------------------------------------------------------------------------------- /src/reporter.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /* global console: false */ 4 | 5 | /** 6 | * Reporter that handles the reporting of logs, warnings and errors. 7 | * @public 8 | * @param {boolean} quiet Tells if the reporter should be quiet or not. 9 | */ 10 | module.exports = function(quiet) { 11 | function noop() { 12 | //Does nothing. 13 | } 14 | 15 | var reporter = { 16 | log: noop, 17 | warn: noop, 18 | error: noop 19 | }; 20 | 21 | if(!quiet && window.console) { 22 | var attachFunction = function(reporter, name) { 23 | //The proxy is needed to be able to call the method with the console context, 24 | //since we cannot use bind. 25 | reporter[name] = function reporterProxy() { 26 | var f = console[name]; 27 | if (f.apply) { //IE9 does not support console.log.apply :) 28 | f.apply(console, arguments); 29 | } else { 30 | for (var i = 0; i < arguments.length; i++) { 31 | f(arguments[i]); 32 | } 33 | } 34 | }; 35 | }; 36 | 37 | attachFunction(reporter, "log"); 38 | attachFunction(reporter, "warn"); 39 | attachFunction(reporter, "error"); 40 | } 41 | 42 | return reporter; 43 | }; -------------------------------------------------------------------------------- /src/state-handler.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var prop = "_erd"; 4 | 5 | function initState(element) { 6 | element[prop] = {}; 7 | return getState(element); 8 | } 9 | 10 | function getState(element) { 11 | return element[prop]; 12 | } 13 | 14 | function cleanState(element) { 15 | delete element[prop]; 16 | } 17 | 18 | module.exports = { 19 | initState: initState, 20 | getState: getState, 21 | cleanState: cleanState 22 | }; 23 | -------------------------------------------------------------------------------- /test/element-resize-detector_test.js: -------------------------------------------------------------------------------- 1 | /* global describe:false, it:false, beforeEach:false, expect:false, elementResizeDetectorMaker:false, _:false, $:false, jasmine:false */ 2 | 3 | "use strict"; 4 | 5 | function ensureMapEqual(before, after, ignore) { 6 | var beforeKeys = _.keys(before); 7 | var afterKeys = _.keys(after); 8 | 9 | var unionKeys = _.union(beforeKeys, afterKeys); 10 | 11 | var diffValueKeys = _.filter(unionKeys, function (key) { 12 | var beforeValue = before[key]; 13 | var afterValue = after[key]; 14 | return !ignore(key, beforeValue, afterValue) && beforeValue !== afterValue; 15 | }); 16 | 17 | if (diffValueKeys.length) { 18 | var beforeDiffObject = {}; 19 | var afterDiffObject = {}; 20 | 21 | _.forEach(diffValueKeys, function (key) { 22 | beforeDiffObject[key] = before[key]; 23 | afterDiffObject[key] = after[key]; 24 | }); 25 | 26 | expect(afterDiffObject).toEqual(beforeDiffObject); 27 | } 28 | } 29 | 30 | function getStyle(element) { 31 | function clone(styleObject) { 32 | var clonedTarget = {}; 33 | _.forEach(styleObject.cssText.split(";").slice(0, -1), function (declaration) { 34 | var colonPos = declaration.indexOf(":"); 35 | var attr = declaration.slice(0, colonPos).trim(); 36 | if (attr.indexOf("-") === -1) { // Remove attributes like "background-image", leaving "backgroundImage" 37 | clonedTarget[attr] = declaration.slice(colonPos + 2); 38 | } 39 | }); 40 | return clonedTarget; 41 | } 42 | 43 | var style = getComputedStyle(element); 44 | return clone(style); 45 | } 46 | 47 | function getAttributes(element) { 48 | var attrs = {}; 49 | _.forEach(element.attributes, function (attr) { 50 | attrs[attr.nodeName] = attr.value; 51 | }); 52 | return attrs; 53 | } 54 | 55 | var ensureAttributes = ensureMapEqual; 56 | 57 | var reporter = { 58 | log: function () { 59 | throw new Error("Reporter.log should not be called"); 60 | }, 61 | warn: function () { 62 | throw new Error("Reporter.warn should not be called"); 63 | }, 64 | error: function () { 65 | throw new Error("Reporter.error should not be called"); 66 | } 67 | }; 68 | 69 | $("body").prepend("
"); 70 | 71 | function listenToTest(strategy) { 72 | describe("[" + strategy + "] listenTo", function () { 73 | it("should be able to attach a listener to an element", function (done) { 74 | var erd = elementResizeDetectorMaker({ 75 | callOnAdd: false, 76 | reporter: reporter, 77 | strategy: strategy 78 | }); 79 | 80 | var listener = jasmine.createSpy("listener"); 81 | 82 | erd.listenTo($("#test")[0], listener); 83 | 84 | setTimeout(function () { 85 | $("#test").width(300); 86 | }, 200); 87 | 88 | setTimeout(function () { 89 | expect(listener).toHaveBeenCalledWith($("#test")[0]); 90 | done(); 91 | }, 400); 92 | }); 93 | 94 | it("should throw on invalid parameters", function () { 95 | var erd = elementResizeDetectorMaker({ 96 | callOnAdd: false, 97 | reporter: reporter, 98 | strategy: strategy 99 | }); 100 | 101 | expect(erd.listenTo).toThrow(); 102 | 103 | expect(_.partial(erd.listenTo, $("#test")[0])).toThrow(); 104 | }); 105 | 106 | describe("option.onReady", function () { 107 | it("should be called when installing a listener to an element", function (done) { 108 | var erd = elementResizeDetectorMaker({ 109 | callOnAdd: false, 110 | reporter: reporter, 111 | strategy: strategy 112 | }); 113 | 114 | var listener = jasmine.createSpy("listener"); 115 | 116 | erd.listenTo({ 117 | onReady: function () { 118 | $("#test").width(200); 119 | setTimeout(function () { 120 | expect(listener).toHaveBeenCalledWith($("#test")[0]); 121 | done(); 122 | }, 200); 123 | } 124 | }, $("#test")[0], listener); 125 | }); 126 | 127 | it("should be called when all elements are ready", function (done) { 128 | var erd = elementResizeDetectorMaker({ 129 | callOnAdd: false, 130 | reporter: reporter, 131 | strategy: strategy 132 | }); 133 | 134 | var listener = jasmine.createSpy("listener"); 135 | 136 | erd.listenTo({ 137 | onReady: function () { 138 | $("#test").width(200); 139 | $("#test2").width(300); 140 | setTimeout(function () { 141 | expect(listener).toHaveBeenCalledWith($("#test")[0]); 142 | expect(listener).toHaveBeenCalledWith($("#test2")[0]); 143 | done(); 144 | }, 200); 145 | } 146 | }, $("#test, #test2"), listener); 147 | }); 148 | 149 | it("should be able to handle listeners for the same element but different calls", function (done) { 150 | var erd = elementResizeDetectorMaker({ 151 | callOnAdd: false, 152 | reporter: reporter, 153 | strategy: strategy 154 | }); 155 | 156 | var onReady1 = jasmine.createSpy("listener"); 157 | var onReady2 = jasmine.createSpy("listener"); 158 | 159 | erd.listenTo({ 160 | onReady: onReady1 161 | }, $("#test"), function noop() { 162 | }); 163 | erd.listenTo({ 164 | onReady: onReady2 165 | }, $("#test"), function noop() { 166 | }); 167 | 168 | setTimeout(function () { 169 | expect(onReady1.calls.count()).toBe(1); 170 | expect(onReady2.calls.count()).toBe(1); 171 | done(); 172 | }, 300); 173 | }); 174 | 175 | it("should be able to handle when elements occur multiple times in the same call (and other calls)", function (done) { 176 | var erd = elementResizeDetectorMaker({ 177 | callOnAdd: false, 178 | reporter: reporter, 179 | strategy: strategy 180 | }); 181 | 182 | var onReady1 = jasmine.createSpy("listener"); 183 | var onReady2 = jasmine.createSpy("listener"); 184 | 185 | erd.listenTo({ 186 | onReady: onReady1 187 | }, [$("#test")[0], $("#test")[0]], function noop() { 188 | }); 189 | erd.listenTo({ 190 | onReady: onReady2 191 | }, $("#test"), function noop() { 192 | }); 193 | 194 | setTimeout(function () { 195 | expect(onReady1.calls.count()).toBe(1); 196 | expect(onReady2.calls.count()).toBe(1); 197 | done(); 198 | }, 300); 199 | }); 200 | }); 201 | 202 | it("should be able to attach multiple listeners to an element", function (done) { 203 | var erd = elementResizeDetectorMaker({ 204 | callOnAdd: false, 205 | reporter: reporter, 206 | strategy: strategy 207 | }); 208 | 209 | var listener1 = jasmine.createSpy("listener1"); 210 | var listener2 = jasmine.createSpy("listener2"); 211 | 212 | erd.listenTo($("#test")[0], listener1); 213 | erd.listenTo($("#test")[0], listener2); 214 | 215 | setTimeout(function () { 216 | $("#test").width(300); 217 | }, 200); 218 | 219 | setTimeout(function () { 220 | expect(listener1).toHaveBeenCalledWith($("#test")[0]); 221 | expect(listener2).toHaveBeenCalledWith($("#test")[0]); 222 | done(); 223 | }, 400); 224 | }); 225 | 226 | it("should be able to attach a listener to an element multiple times within the same call", function (done) { 227 | var erd = elementResizeDetectorMaker({ 228 | callOnAdd: false, 229 | reporter: reporter, 230 | strategy: strategy 231 | }); 232 | 233 | var listener1 = jasmine.createSpy("listener1"); 234 | 235 | erd.listenTo([$("#test")[0], $("#test")[0]], listener1); 236 | 237 | setTimeout(function () { 238 | $("#test").width(300); 239 | }, 200); 240 | 241 | setTimeout(function () { 242 | expect(listener1).toHaveBeenCalledWith($("#test")[0]); 243 | expect(listener1.calls.count()).toBe(2); 244 | done(); 245 | }, 400); 246 | }); 247 | 248 | it("should be able to attach listeners to multiple elements", function (done) { 249 | var erd = elementResizeDetectorMaker({ 250 | callOnAdd: false, 251 | reporter: reporter, 252 | strategy: strategy 253 | }); 254 | 255 | var listener1 = jasmine.createSpy("listener1"); 256 | 257 | erd.listenTo($("#test, #test2"), listener1); 258 | 259 | setTimeout(function () { 260 | $("#test").width(200); 261 | }, 200); 262 | 263 | setTimeout(function () { 264 | expect(listener1).toHaveBeenCalledWith($("#test")[0]); 265 | }, 400); 266 | 267 | setTimeout(function () { 268 | $("#test2").width(500); 269 | }, 600); 270 | 271 | setTimeout(function () { 272 | expect(listener1).toHaveBeenCalledWith($("#test2")[0]); 273 | done(); 274 | }, 800); 275 | }); 276 | 277 | //Only run this test if the browser actually is able to get the computed style of an element. 278 | //Only IE8 is lacking the getComputedStyle method. 279 | if (window.getComputedStyle) { 280 | it("should keep the style of the element intact", function (done) { 281 | var erd = elementResizeDetectorMaker({ 282 | callOnAdd: false, 283 | reporter: reporter, 284 | strategy: strategy 285 | }); 286 | 287 | function ignoreStyleChange(key, before, after) { 288 | return (key === "position" && before === "static" && after === "relative") || 289 | (/^(top|right|bottom|left)$/.test(key) && before === "auto" && after === "0px"); 290 | } 291 | 292 | var beforeComputedStyle = getStyle($("#test")[0]); 293 | erd.listenTo($("#test")[0], _.noop); 294 | var afterComputedStyle = getStyle($("#test")[0]); 295 | ensureMapEqual(beforeComputedStyle, afterComputedStyle, ignoreStyleChange); 296 | 297 | //Test styles async since making an element listenable is async. 298 | setTimeout(function () { 299 | var afterComputedStyleAsync = getStyle($("#test")[0]); 300 | ensureMapEqual(beforeComputedStyle, afterComputedStyleAsync, ignoreStyleChange); 301 | expect(true).toEqual(true); // Needed so that jasmine does not warn about no expects in the test (the actual expects are in the ensureMapEqual). 302 | done(); 303 | }, 200); 304 | }); 305 | } 306 | 307 | describe("options.callOnAdd", function () { 308 | it("should be true default and call all functions when listenTo succeeds", function (done) { 309 | var erd = elementResizeDetectorMaker({ 310 | reporter: reporter, 311 | strategy: strategy 312 | }); 313 | 314 | var listener = jasmine.createSpy("listener"); 315 | var listener2 = jasmine.createSpy("listener2"); 316 | 317 | erd.listenTo($("#test")[0], listener); 318 | erd.listenTo($("#test")[0], listener2); 319 | 320 | setTimeout(function () { 321 | expect(listener).toHaveBeenCalledWith($("#test")[0]); 322 | expect(listener2).toHaveBeenCalledWith($("#test")[0]); 323 | listener.calls.reset(); 324 | listener2.calls.reset(); 325 | $("#test").width(300); 326 | }, 200); 327 | 328 | setTimeout(function () { 329 | expect(listener).toHaveBeenCalledWith($("#test")[0]); 330 | expect(listener2).toHaveBeenCalledWith($("#test")[0]); 331 | done(); 332 | }, 400); 333 | }); 334 | 335 | it("should call listener multiple times when listening to multiple elements", function (done) { 336 | var erd = elementResizeDetectorMaker({ 337 | reporter: reporter, 338 | strategy: strategy 339 | }); 340 | 341 | var listener1 = jasmine.createSpy("listener1"); 342 | erd.listenTo($("#test, #test2"), listener1); 343 | 344 | setTimeout(function () { 345 | expect(listener1).toHaveBeenCalledWith($("#test")[0]); 346 | expect(listener1).toHaveBeenCalledWith($("#test2")[0]); 347 | done(); 348 | }, 200); 349 | }); 350 | }); 351 | 352 | it("should call listener if the element is changed synchronously after listenTo", function (done) { 353 | var erd = elementResizeDetectorMaker({ 354 | callOnAdd: false, 355 | reporter: reporter, 356 | strategy: strategy 357 | }); 358 | 359 | var listener1 = jasmine.createSpy("listener1"); 360 | erd.listenTo($("#test"), listener1); 361 | $("#test").width(200); 362 | 363 | setTimeout(function () { 364 | expect(listener1).toHaveBeenCalledWith($("#test")[0]); 365 | done(); 366 | }, 200); 367 | }); 368 | 369 | it("should not emit resize when listenTo is called", function (done) { 370 | var erd = elementResizeDetectorMaker({ 371 | callOnAdd: false, 372 | reporter: reporter, 373 | strategy: strategy 374 | }); 375 | 376 | var listener1 = jasmine.createSpy("listener1"); 377 | erd.listenTo($("#test"), listener1); 378 | 379 | setTimeout(function () { 380 | expect(listener1).not.toHaveBeenCalledWith($("#test")[0]); 381 | done(); 382 | }, 200); 383 | }); 384 | 385 | it("should not emit resize event even though the element is back to its start size", function (done) { 386 | var erd = elementResizeDetectorMaker({ 387 | callOnAdd: false, 388 | reporter: reporter, 389 | strategy: strategy 390 | }); 391 | 392 | var listener = jasmine.createSpy("listener1"); 393 | $("#test").width(200); 394 | erd.listenTo($("#test"), listener); 395 | 396 | setTimeout(function () { 397 | expect(listener).not.toHaveBeenCalledWith($("#test")[0]); 398 | listener.calls.reset(); 399 | $("#test").width(100); 400 | }, 200); 401 | 402 | setTimeout(function () { 403 | expect(listener).toHaveBeenCalledWith($("#test")[0]); 404 | listener.calls.reset(); 405 | $("#test").width(200); 406 | }, 400); 407 | 408 | setTimeout(function () { 409 | expect(listener).toHaveBeenCalledWith($("#test")[0]); 410 | done(); 411 | }, 600); 412 | }); 413 | 414 | it("should use the option.idHandler if present", function (done) { 415 | var ID_ATTR = "some-fancy-id-attr"; 416 | 417 | var idHandler = { 418 | get: function (element, readonly) { 419 | if (element[ID_ATTR] === undefined) { 420 | if (readonly) { 421 | return null; 422 | } 423 | 424 | this.set(element); 425 | } 426 | 427 | return $(element).attr(ID_ATTR); 428 | }, 429 | set: function (element) { 430 | var id; 431 | 432 | if ($(element).attr("id") === "test") { 433 | id = "test+1"; 434 | } else if ($(element).attr("id") === "test2") { 435 | id = "test2+2"; 436 | } 437 | 438 | $(element).attr(ID_ATTR, id); 439 | 440 | return id; 441 | } 442 | }; 443 | 444 | var erd = elementResizeDetectorMaker({ 445 | idHandler: idHandler, 446 | callOnAdd: false, 447 | reporter: reporter, 448 | strategy: strategy 449 | }); 450 | 451 | var listener1 = jasmine.createSpy("listener1"); 452 | var listener2 = jasmine.createSpy("listener1"); 453 | 454 | var attrsBeforeTest = getAttributes($("#test")[0]); 455 | var attrsBeforeTest2 = getAttributes($("#test2")[0]); 456 | 457 | erd.listenTo($("#test"), listener1); 458 | erd.listenTo($("#test, #test2"), listener2); 459 | 460 | var attrsAfterTest = getAttributes($("#test")[0]); 461 | var attrsAfterTest2 = getAttributes($("#test2")[0]); 462 | 463 | var ignoreValidIdAttrAndStyle = function (key) { 464 | return key === ID_ATTR || key === "style"; 465 | }; 466 | 467 | ensureAttributes(attrsBeforeTest, attrsAfterTest, ignoreValidIdAttrAndStyle); 468 | ensureAttributes(attrsBeforeTest2, attrsAfterTest2, ignoreValidIdAttrAndStyle); 469 | 470 | expect($("#test").attr(ID_ATTR)).toEqual("test+1"); 471 | expect($("#test2").attr(ID_ATTR)).toEqual("test2+2"); 472 | 473 | setTimeout(function () { 474 | $("#test").width(300); 475 | $("#test2").width(500); 476 | }, 200); 477 | 478 | setTimeout(function () { 479 | expect(listener1).toHaveBeenCalledWith($("#test")[0]); 480 | expect(listener2).toHaveBeenCalledWith($("#test")[0]); 481 | expect(listener2).toHaveBeenCalledWith($("#test2")[0]); 482 | done(); 483 | }, 600); 484 | }); 485 | 486 | it("should be able to install into elements that are detached from the DOM", function (done) { 487 | var erd = elementResizeDetectorMaker({ 488 | callOnAdd: false, 489 | reporter: reporter, 490 | strategy: strategy 491 | }); 492 | 493 | var listener1 = jasmine.createSpy("listener1"); 494 | var div = document.createElement("div"); 495 | div.style.width = "100%"; 496 | div.style.height = "100%"; 497 | erd.listenTo(div, listener1); 498 | 499 | setTimeout(function () { 500 | $("#test")[0].appendChild(div); 501 | }, 200); 502 | 503 | setTimeout(function () { 504 | $("#test").width(200); 505 | }, 400); 506 | 507 | setTimeout(function () { 508 | expect(listener1).toHaveBeenCalledWith(div); 509 | done(); 510 | }, 600); 511 | }); 512 | 513 | it("should handle iframes, by using initDocument", function (done) { 514 | var erd = elementResizeDetectorMaker({ 515 | callOnAdd: false, 516 | strategy: strategy, 517 | reporter: reporter 518 | }); 519 | 520 | var listener1 = jasmine.createSpy("listener1"); 521 | var iframe = document.createElement("iframe"); 522 | $("#test")[0].appendChild(iframe); 523 | erd.initDocument(iframe.contentDocument); 524 | var div = iframe.contentDocument.createElement("div"); 525 | 526 | div.style.width = "100%"; 527 | div.style.height = "100%"; 528 | div.id = "target"; 529 | erd.listenTo(div, listener1); 530 | 531 | setTimeout(function () { 532 | // FireFox triggers the onload state of the iframe and wipes its content. 533 | iframe.contentDocument.body.appendChild(div); 534 | erd.initDocument(iframe.contentDocument); 535 | }, 10); 536 | 537 | setTimeout(function () { 538 | div.style.width = "100px"; 539 | }, 200); 540 | 541 | setTimeout(function () { 542 | expect(listener1).toHaveBeenCalledWith(div); 543 | done(); 544 | }, 400); 545 | }); 546 | 547 | it("should detect resizes caused by padding and font-size changes", function (done) { 548 | var erd = elementResizeDetectorMaker({ 549 | callOnAdd: false, 550 | reporter: reporter, 551 | strategy: strategy 552 | }); 553 | 554 | var listener = jasmine.createSpy("listener"); 555 | $("#test").html("test"); 556 | $("#test").css("padding", "0px"); 557 | $("#test").css("font-size", "16px"); 558 | 559 | erd.listenTo($("#test"), listener); 560 | 561 | $("#test").css("padding", "10px"); 562 | 563 | setTimeout(function () { 564 | expect(listener).toHaveBeenCalledWith($("#test")[0]); 565 | listener.calls.reset(); 566 | $("#test").css("font-size", "20px"); 567 | }, 200); 568 | 569 | setTimeout(function () { 570 | expect(listener).toHaveBeenCalledWith($("#test")[0]); 571 | done(); 572 | }, 400); 573 | }); 574 | 575 | describe("should handle unrendered elements correctly", function () { 576 | it("when installing", function (done) { 577 | var erd = elementResizeDetectorMaker({ 578 | callOnAdd: false, 579 | reporter: reporter, 580 | strategy: strategy 581 | }); 582 | 583 | $("#test").html("
"); 584 | $("#test").css("display", "none"); 585 | 586 | var listener = jasmine.createSpy("listener"); 587 | erd.listenTo($("#inner"), listener); 588 | 589 | setTimeout(function () { 590 | expect(listener).not.toHaveBeenCalled(); 591 | $("#test").css("display", ""); 592 | }, 200); 593 | 594 | setTimeout(function () { 595 | expect(listener).toHaveBeenCalledWith($("#inner")[0]); 596 | listener.calls.reset(); 597 | $("#inner").width("300px"); 598 | }, 400); 599 | 600 | setTimeout(function () { 601 | expect(listener).toHaveBeenCalledWith($("#inner")[0]); 602 | listener.calls.reset(); 603 | done(); 604 | }, 600); 605 | }); 606 | 607 | it("when element gets unrendered after installation", function (done) { 608 | var erd = elementResizeDetectorMaker({ 609 | callOnAdd: false, 610 | reporter: reporter, 611 | strategy: strategy 612 | }); 613 | 614 | // The div is rendered to begin with. 615 | $("#test").html("
"); 616 | 617 | var listener = jasmine.createSpy("listener"); 618 | erd.listenTo($("#inner"), listener); 619 | 620 | // The it gets unrendered, and it changes width. 621 | setTimeout(function () { 622 | expect(listener).not.toHaveBeenCalled(); 623 | $("#test").css("display", "none"); 624 | $("#inner").width("300px"); 625 | }, 100); 626 | 627 | // Render the element again. 628 | setTimeout(function () { 629 | expect(listener).not.toHaveBeenCalled(); 630 | $("#test").css("display", ""); 631 | }, 200); 632 | 633 | // ERD should detect that the element has changed size as soon as it gets rendered again. 634 | setTimeout(function () { 635 | expect(listener).toHaveBeenCalledWith($("#inner")[0]); 636 | done(); 637 | }, 300); 638 | }); 639 | }); 640 | 641 | describe("inline elements", function () { 642 | it("should be listenable", function (done) { 643 | var erd = elementResizeDetectorMaker({ 644 | callOnAdd: false, 645 | reporter: reporter, 646 | strategy: strategy 647 | }); 648 | 649 | $("#test").html("test"); 650 | 651 | var listener = jasmine.createSpy("listener"); 652 | erd.listenTo($("#inner"), listener); 653 | 654 | setTimeout(function () { 655 | expect(listener).not.toHaveBeenCalled(); 656 | $("#inner").append("testing testing"); 657 | }, 100); 658 | 659 | setTimeout(function () { 660 | expect(listener).toHaveBeenCalledWith($("#inner")[0]); 661 | done(); 662 | }, 200); 663 | }); 664 | 665 | it("should not get altered dimensions", function (done) { 666 | var erd = elementResizeDetectorMaker({ 667 | callOnAdd: false, 668 | reporter: reporter, 669 | strategy: strategy 670 | }); 671 | 672 | $("#test").html(""); 673 | 674 | var widthBefore = $("#inner").width(); 675 | var heightBefore = $("#inner").height(); 676 | 677 | var listener = jasmine.createSpy("listener"); 678 | erd.listenTo($("#inner"), listener); 679 | 680 | setTimeout(function () { 681 | expect($("#inner").width()).toEqual(widthBefore); 682 | expect($("#inner").height()).toEqual(heightBefore); 683 | done(); 684 | }, 100); 685 | }); 686 | }); 687 | 688 | it("should handle dir=rtl correctly", function (done) { 689 | var erd = elementResizeDetectorMaker({ 690 | callOnAdd: false, 691 | reporter: reporter, 692 | strategy: strategy 693 | }); 694 | 695 | var listener = jasmine.createSpy("listener"); 696 | 697 | $("#test")[0].dir = "rtl"; 698 | erd.listenTo($("#test")[0], listener); 699 | 700 | setTimeout(function () { 701 | $("#test").width(300); 702 | }, 200); 703 | 704 | setTimeout(function () { 705 | expect(listener).toHaveBeenCalledWith($("#test")[0]); 706 | done(); 707 | }, 400); 708 | }); 709 | 710 | it("should handle fast consecutive resizes", function (done) { 711 | var erd = elementResizeDetectorMaker({ 712 | callOnAdd: false, 713 | strategy: strategy, 714 | reporter: reporter 715 | }); 716 | 717 | var listener = jasmine.createSpy("listener"); 718 | 719 | $("#test").width(100); 720 | erd.listenTo($("#test")[0], listener); 721 | 722 | setTimeout(function () { 723 | $("#test").width(300); 724 | }, 50); 725 | 726 | setTimeout(function () { 727 | expect(listener.calls.count()).toEqual(1); 728 | $("#test").width(500); 729 | setTimeout(function () { 730 | $("#test").width(300); 731 | }, 0); 732 | }, 100); 733 | 734 | // Some browsers skip the 300 -> 500 -> 300 resize, and some actually processes it. 735 | // So the resize events may be 1 or 3 at this point. 736 | 737 | setTimeout(function () { 738 | var count = listener.calls.count(); 739 | expect(count === 1 || count === 3).toEqual(true); 740 | }, 150); 741 | 742 | 743 | setTimeout(function () { 744 | var count = listener.calls.count(); 745 | expect(count === 1 || count === 3).toEqual(true); 746 | $("#test").width(800); 747 | }, 200); 748 | 749 | setTimeout(function () { 750 | var count = listener.calls.count(); 751 | expect(count === 2 || count === 4).toEqual(true); 752 | done(); 753 | }, 250); 754 | }); 755 | 756 | }); 757 | } 758 | 759 | function removalTest(strategy) { 760 | describe("[" + strategy + "] resizeDetector.removeListener", function () { 761 | it("should remove listener from element", function (done) { 762 | var erd = elementResizeDetectorMaker({ 763 | callOnAdd: false, 764 | strategy: strategy 765 | }); 766 | 767 | var $testElem = $("#test"); 768 | 769 | var listenerCall = jasmine.createSpy("listener"); 770 | var listenerNotCall = jasmine.createSpy("listener"); 771 | 772 | erd.listenTo($testElem[0], listenerCall); 773 | erd.listenTo($testElem[0], listenerNotCall); 774 | 775 | setTimeout(function () { 776 | erd.removeListener($testElem[0], listenerNotCall); 777 | $testElem.width(300); 778 | }, 200); 779 | 780 | setTimeout(function () { 781 | expect(listenerCall).toHaveBeenCalled(); 782 | expect(listenerNotCall).not.toHaveBeenCalled(); 783 | done(); 784 | }, 400); 785 | }); 786 | }); 787 | 788 | describe("[" + strategy + "] resizeDetector.removeAllListeners", function () { 789 | it("should remove all listeners from element", function (done) { 790 | var erd = elementResizeDetectorMaker({ 791 | callOnAdd: false, 792 | strategy: strategy 793 | }); 794 | 795 | var $testElem = $("#test"); 796 | 797 | var listener1 = jasmine.createSpy("listener"); 798 | var listener2 = jasmine.createSpy("listener"); 799 | 800 | erd.listenTo($testElem[0], listener1); 801 | erd.listenTo($testElem[0], listener2); 802 | 803 | setTimeout(function () { 804 | erd.removeAllListeners($testElem[0]); 805 | $testElem.width(300); 806 | }, 200); 807 | 808 | setTimeout(function () { 809 | expect(listener1).not.toHaveBeenCalled(); 810 | expect(listener2).not.toHaveBeenCalled(); 811 | done(); 812 | }, 400); 813 | }); 814 | 815 | it("should work for elements that don't have the detector installed", function () { 816 | var erd = elementResizeDetectorMaker({ 817 | strategy: strategy 818 | }); 819 | var $testElem = $("#test"); 820 | expect(erd.removeAllListeners.bind(erd, $testElem[0])).not.toThrow(); 821 | }); 822 | }); 823 | 824 | describe("[scroll] Specific scenarios", function () { 825 | it("should be able to call uninstall in the middle of a resize", function (done) { 826 | var erd = elementResizeDetectorMaker({ 827 | strategy: "scroll" 828 | }); 829 | 830 | var $testElem = $("#test"); 831 | var testElem = $testElem[0]; 832 | var listener = jasmine.createSpy("listener"); 833 | 834 | erd.listenTo(testElem, listener); 835 | setTimeout(function () { 836 | // We want the uninstall to happen exactly when a scroll event occured before the delayed batched is going to be processed. 837 | // So we intercept the erd shrink/expand functions in the state so that we may call uninstall after the handling of the event. 838 | var uninstalled = false; 839 | 840 | function wrapOnScrollEvent(oldFn) { 841 | return function () { 842 | oldFn(); 843 | if (!uninstalled) { 844 | expect(erd.uninstall.bind(erd, testElem)).not.toThrow(); 845 | uninstalled = true; 846 | done(); 847 | } 848 | }; 849 | } 850 | 851 | var state = testElem._erd; 852 | state.onExpand = wrapOnScrollEvent(state.onExpand); 853 | state.onShrink = wrapOnScrollEvent(state.onShrink); 854 | $("#test").width(300); 855 | }, 50); 856 | }); 857 | 858 | it("should be able to call uninstall and then install in the middle of a resize (issue #61)", function (done) { 859 | var erd = elementResizeDetectorMaker({ 860 | strategy: "scroll", 861 | reporter: reporter 862 | }); 863 | 864 | var $testElem = $("#test"); 865 | var testElem = $testElem[0]; 866 | var listener = jasmine.createSpy("listener"); 867 | 868 | erd.listenTo(testElem, listener); 869 | setTimeout(function () { 870 | // We want the uninstall to happen exactly when a scroll event occured before the delayed batched is going to be processed. 871 | // So we intercept the erd shrink/expand functions in the state so that we may call uninstall after the handling of the event. 872 | var uninstalled = false; 873 | 874 | function wrapOnScrollEvent(oldFn) { 875 | return function () { 876 | oldFn(); 877 | if (!uninstalled) { 878 | expect(erd.uninstall.bind(erd, testElem)).not.toThrow(); 879 | uninstalled = true; 880 | var listener2 = jasmine.createSpy("listener"); 881 | expect(erd.listenTo.bind(erd, testElem, listener2)).not.toThrow(); 882 | setTimeout(function () { 883 | done(); 884 | }, 0); 885 | } 886 | }; 887 | } 888 | 889 | var state = testElem._erd; 890 | state.onExpand = wrapOnScrollEvent(state.onExpand); 891 | state.onShrink = wrapOnScrollEvent(state.onShrink); 892 | $("#test").width(300); 893 | }, 50); 894 | }); 895 | 896 | // Only run this shadow DOM test for browsers that support the feature 897 | if (!!HTMLElement.prototype.attachShadow) { 898 | it("should work for elements within an open shadow root (issue #127)", function(done) { 899 | var erd = elementResizeDetectorMaker({ 900 | callOnAdd: false, 901 | reporter: reporter, 902 | strategy: "scroll" 903 | }); 904 | 905 | var listener = jasmine.createSpy("listener"); 906 | 907 | // Setup shadow root with a child div 908 | var shadow = $("#shadowtest")[0].attachShadow({mode: "open"}); 909 | var shadowChild = document.createElement("div"); 910 | shadow.appendChild(shadowChild); 911 | 912 | erd.listenTo(shadowChild, listener); 913 | 914 | setTimeout(function () { 915 | $(shadowChild).width(300); 916 | }, 200); 917 | 918 | setTimeout(function () { 919 | expect(listener).toHaveBeenCalledWith(shadowChild); 920 | done(); 921 | }, 400); 922 | }); 923 | } 924 | }); 925 | 926 | describe("[" + strategy + "] resizeDetector.uninstall", function () { 927 | it("should completely remove detector from element", function (done) { 928 | var erd = elementResizeDetectorMaker({ 929 | callOnAdd: false, 930 | strategy: strategy 931 | }); 932 | 933 | var $testElem = $("#test"); 934 | 935 | var listener = jasmine.createSpy("listener"); 936 | 937 | erd.listenTo($testElem[0], listener); 938 | 939 | setTimeout(function () { 940 | erd.uninstall($testElem[0]); 941 | // detector element should be removed 942 | expect($testElem[0].childNodes.length).toBe(0); 943 | $testElem.width(300); 944 | }, 200); 945 | 946 | setTimeout(function () { 947 | expect(listener).not.toHaveBeenCalled(); 948 | done(); 949 | }, 400); 950 | }); 951 | 952 | it("should completely remove detector from multiple elements", function (done) { 953 | var erd = elementResizeDetectorMaker({ 954 | callOnAdd: false, 955 | strategy: strategy 956 | }); 957 | 958 | var listener = jasmine.createSpy("listener"); 959 | 960 | erd.listenTo($("#test, #test2"), listener); 961 | 962 | setTimeout(function () { 963 | erd.uninstall($("#test, #test2")); 964 | // detector element should be removed 965 | expect($("#test")[0].childNodes.length).toBe(0); 966 | expect($("#test2")[0].childNodes.length).toBe(0); 967 | $("#test, #test2").width(300); 968 | }, 200); 969 | 970 | setTimeout(function () { 971 | expect(listener).not.toHaveBeenCalled(); 972 | done(); 973 | }, 400); 974 | }); 975 | 976 | it("should be able to call uninstall directly after listenTo", function () { 977 | var erd = elementResizeDetectorMaker({ 978 | strategy: strategy 979 | }); 980 | 981 | var $testElem = $("#test"); 982 | var listener = jasmine.createSpy("listener"); 983 | 984 | erd.listenTo($testElem[0], listener); 985 | expect(erd.uninstall.bind(erd, $testElem[0])).not.toThrow(); 986 | }); 987 | 988 | it("should be able to call uninstall directly async after listenTo", function (done) { 989 | var erd = elementResizeDetectorMaker({ 990 | strategy: strategy 991 | }); 992 | 993 | var $testElem = $("#test"); 994 | var listener = jasmine.createSpy("listener"); 995 | 996 | erd.listenTo($testElem[0], listener); 997 | setTimeout(function () { 998 | expect(erd.uninstall.bind(erd, $testElem[0])).not.toThrow(); 999 | done(); 1000 | }, 0); 1001 | }); 1002 | 1003 | it("should be able to call uninstall in callOnAdd callback", function (done) { 1004 | var error = false; 1005 | 1006 | // Ugly hack to catch async errors. 1007 | window.onerror = function () { 1008 | error = true; 1009 | }; 1010 | 1011 | var erd = elementResizeDetectorMaker({ 1012 | strategy: strategy, 1013 | callOnAdd: true 1014 | }); 1015 | 1016 | erd.listenTo($("#test"), function () { 1017 | expect(erd.uninstall.bind(null, ($("#test")))).not.toThrow(); 1018 | }); 1019 | 1020 | setTimeout(function () { 1021 | expect(error).toBe(false); 1022 | done(); 1023 | window.error = null; 1024 | }, 50); 1025 | }); 1026 | 1027 | it("should be able to call uninstall in callOnAdd callback with multiple elements", function (done) { 1028 | var error = false; 1029 | 1030 | // Ugly hack to catch async errors. 1031 | window.onerror = function () { 1032 | error = true; 1033 | }; 1034 | 1035 | var erd = elementResizeDetectorMaker({ 1036 | strategy: strategy, 1037 | callOnAdd: true 1038 | }); 1039 | 1040 | var listener = jasmine.createSpy("listener"); 1041 | 1042 | erd.listenTo($("#test, #test2"), function () { 1043 | expect(erd.uninstall.bind(null, ($("#test, #test2")))).not.toThrow(); 1044 | listener(); 1045 | }); 1046 | 1047 | setTimeout(function () { 1048 | expect(listener.calls.count()).toBe(1); 1049 | expect(error).toBe(false); 1050 | done(); 1051 | window.error = null; 1052 | }, 50); 1053 | }); 1054 | 1055 | it("should be able to call uninstall on non-erd elements", function () { 1056 | var erd = elementResizeDetectorMaker({ 1057 | strategy: strategy 1058 | }); 1059 | 1060 | var $testElem = $("#test"); 1061 | 1062 | expect(erd.uninstall.bind(erd, $testElem[0])).not.toThrow(); 1063 | 1064 | var listener = jasmine.createSpy("listener"); 1065 | erd.listenTo($testElem[0], listener); 1066 | expect(erd.uninstall.bind(erd, $testElem[0])).not.toThrow(); 1067 | expect(erd.uninstall.bind(erd, $testElem[0])).not.toThrow(); 1068 | }); 1069 | }); 1070 | } 1071 | 1072 | function importantRuleTest(strategy) { 1073 | describe("[" + strategy + "] resizeDetector.important", function () { 1074 | it("should add all rules with important", function (done) { 1075 | var erd = elementResizeDetectorMaker({ 1076 | callOnAdd: true, 1077 | strategy: strategy, 1078 | important: true 1079 | }); 1080 | 1081 | var testElem = $("#test"); 1082 | var listenerCall = jasmine.createSpy("listener"); 1083 | 1084 | erd.listenTo(testElem[0], listenerCall); 1085 | 1086 | setTimeout(function () { 1087 | if (strategy === "scroll") { 1088 | expect(testElem[0].style.cssText).toMatch(/!important;$/); 1089 | } 1090 | 1091 | testElem.find("*").toArray().forEach(function (element) { 1092 | var rules = element.style.cssText.split(";").filter(function (rule) { 1093 | return !!rule; 1094 | }); 1095 | 1096 | rules.forEach(function (rule) { 1097 | expect(rule).toMatch(/!important$/); 1098 | }); 1099 | }); 1100 | 1101 | done(); 1102 | }, 50); 1103 | }); 1104 | 1105 | it("Overrides important CSS", function (done) { 1106 | var erd = elementResizeDetectorMaker({ 1107 | callOnAdd: false, 1108 | strategy: strategy, 1109 | important: true 1110 | }); 1111 | 1112 | var listener = jasmine.createSpy("listener"); 1113 | var testElem = $("#test"); 1114 | var style = document.createElement("style"); 1115 | style.appendChild(document.createTextNode("#test { position: static !important; }")); 1116 | document.head.appendChild(style); 1117 | 1118 | erd.listenTo(testElem[0], listener); 1119 | 1120 | setTimeout(function () { 1121 | $("#test").width(300); 1122 | }, 100); 1123 | 1124 | setTimeout(function () { 1125 | expect(listener).toHaveBeenCalledWith($("#test")[0]); 1126 | done(); 1127 | }, 200); 1128 | }); 1129 | }); 1130 | } 1131 | 1132 | describe("element-resize-detector", function () { 1133 | beforeEach(function () { 1134 | //This messed with tests in IE8. 1135 | //TODO: Investigate why, because it would be nice to have instead of the current solution. 1136 | //loadFixtures("element-resize-detector_fixture.html"); 1137 | $("#fixtures").html("
"); 1138 | }); 1139 | 1140 | describe("elementResizeDetectorMaker", function () { 1141 | it("should be globally defined", function () { 1142 | expect(elementResizeDetectorMaker).toBeDefined(); 1143 | }); 1144 | 1145 | it("should create an element-resize-detector instance", function () { 1146 | var erd = elementResizeDetectorMaker(); 1147 | 1148 | expect(erd).toBeDefined(); 1149 | expect(erd.listenTo).toBeDefined(); 1150 | }); 1151 | }); 1152 | 1153 | // listenToTest("object"); 1154 | // removalTest("object"); 1155 | // importantRuleTest("object"); 1156 | listenToTest("scroll"); 1157 | removalTest("scroll"); 1158 | importantRuleTest("scroll"); 1159 | }); 1160 | --------------------------------------------------------------------------------