chameleon-backgrounds 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +194 -0
- package/dist/chameleon-backgrounds.js +356 -0
- package/dist/chameleon-backgrounds.min.js +2 -0
- package/dist/chameleon-backgrounds.min.js.LICENSE.txt +24 -0
- package/package.json +54 -0
- package/src/chameleon-backgrounds.js +398 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2017-present Lennart van Ballegoij (https://weblenn.com/)
|
|
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.
|
package/README.md
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
# ChameleonBackgrounds
|
|
2
|
+
|
|
3
|
+
A **zero-dependency** JavaScript library to dynamically load background images with elegant fade-in transitions and slideshow support.
|
|
4
|
+
|
|
5
|
+
> **v2.0** โ Fully rewritten from scratch. No jQuery required.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Why?
|
|
10
|
+
|
|
11
|
+
Large background images slow down initial page loads. ChameleonBackgrounds **defers loading** these images and reveals them with a smooth CSS transition once they're fully downloaded โ no layout shifts, no flicker.
|
|
12
|
+
|
|
13
|
+
## Features
|
|
14
|
+
|
|
15
|
+
- ๐ฏ **Zero dependencies** โ no jQuery, no frameworks
|
|
16
|
+
- ๐ผ๏ธ **Single image** mode with preload + fade-in
|
|
17
|
+
- ๐ **Slider** mode with configurable duration and looping
|
|
18
|
+
- ๐จ **Overlay** support with color, pattern images, and minimum opacity
|
|
19
|
+
- ๐งน **`destroy()`** method for clean teardown
|
|
20
|
+
- ๐ฆ **ES Module** + **UMD** dual distribution
|
|
21
|
+
- ๐ **Backward compatible** with v1 snake_case option names
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
### npm
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
npm install chameleon-backgrounds
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### CDN / Script Tag
|
|
34
|
+
|
|
35
|
+
```html
|
|
36
|
+
<script src="dist/chameleon-backgrounds.js"></script>
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### ES Module
|
|
40
|
+
|
|
41
|
+
```js
|
|
42
|
+
import ChameleonBackgrounds from 'chameleon-backgrounds';
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## Quick Start
|
|
48
|
+
|
|
49
|
+
### Single Background
|
|
50
|
+
|
|
51
|
+
```html
|
|
52
|
+
<script src="dist/chameleon-backgrounds.js"></script>
|
|
53
|
+
<script>
|
|
54
|
+
const bg = new ChameleonBackgrounds({
|
|
55
|
+
element: 'body',
|
|
56
|
+
type: 'single',
|
|
57
|
+
src: './img/chameleon.jpg',
|
|
58
|
+
overlayColor: '#0f1e25',
|
|
59
|
+
overlayImage: './img/transparent-tile.png', // optional
|
|
60
|
+
minOverlay: 0.5, // optional, default: 0
|
|
61
|
+
transitionDuration: 2000
|
|
62
|
+
});
|
|
63
|
+
</script>
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Slider / Slideshow
|
|
67
|
+
|
|
68
|
+
```html
|
|
69
|
+
<div id="hero"></div>
|
|
70
|
+
|
|
71
|
+
<script src="dist/chameleon-backgrounds.js"></script>
|
|
72
|
+
<script>
|
|
73
|
+
const bg = new ChameleonBackgrounds({
|
|
74
|
+
element: '#hero',
|
|
75
|
+
type: 'slider',
|
|
76
|
+
src: [
|
|
77
|
+
'./img/image1.jpg',
|
|
78
|
+
'./img/image2.jpg',
|
|
79
|
+
'./img/image3.jpg'
|
|
80
|
+
],
|
|
81
|
+
overlayColor: '#656946',
|
|
82
|
+
overlayImage: './img/transparent-tile.png', // optional
|
|
83
|
+
minOverlay: 0.6, // optional
|
|
84
|
+
transitionDuration: 3000,
|
|
85
|
+
sliderDuration: 4000,
|
|
86
|
+
sliderLoop: true
|
|
87
|
+
});
|
|
88
|
+
</script>
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### ES Module Usage
|
|
92
|
+
|
|
93
|
+
```js
|
|
94
|
+
import ChameleonBackgrounds from 'chameleon-backgrounds';
|
|
95
|
+
|
|
96
|
+
const bg = new ChameleonBackgrounds({
|
|
97
|
+
element: '#hero',
|
|
98
|
+
type: 'single',
|
|
99
|
+
src: '/images/hero.jpg',
|
|
100
|
+
overlayColor: '#1a1a2e',
|
|
101
|
+
transitionDuration: 1500
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
// Clean up when done
|
|
105
|
+
bg.destroy();
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
## Options
|
|
111
|
+
|
|
112
|
+
| Option | Type | Default | Required | Description |
|
|
113
|
+
|---|---|---|---|---|
|
|
114
|
+
| `element` | `string \| HTMLElement` | `'body'` | yes | CSS selector or DOM element to attach to |
|
|
115
|
+
| `type` | `'single' \| 'slider'` | `'single'` | yes | Background mode |
|
|
116
|
+
| `src` | `string \| string[]` | `''` | yes | Image URL (single) or array of URLs (slider) |
|
|
117
|
+
| `overlayColor` | `string` | `'#0f1e25'` | yes | Overlay color (hex, rgb, rgba, hsl) |
|
|
118
|
+
| `overlayImage` | `string \| null` | `null` | no | Overlay pattern image URL |
|
|
119
|
+
| `minOverlay` | `number` | `0` | no | Minimum overlay opacity after fade (0โ1) |
|
|
120
|
+
| `transitionDuration` | `number` | `2000` | yes | Fade duration in milliseconds |
|
|
121
|
+
| `sliderDuration` | `number` | `8000` | slider only | Time each slide is shown (ms) |
|
|
122
|
+
| `sliderLoop` | `boolean` | `false` | slider only | Restart slider after last slide |
|
|
123
|
+
|
|
124
|
+
### Legacy Option Names
|
|
125
|
+
|
|
126
|
+
For backward compatibility, v1 snake_case option names are still supported:
|
|
127
|
+
|
|
128
|
+
| v1 (snake_case) | v2 (camelCase) |
|
|
129
|
+
|---|---|
|
|
130
|
+
| `transition_duration` | `transitionDuration` |
|
|
131
|
+
| `slider_duration` | `sliderDuration` |
|
|
132
|
+
| `slider_loop` | `sliderLoop` |
|
|
133
|
+
| `min_overlay` | `minOverlay` |
|
|
134
|
+
| `overlay_color` | `overlayColor` |
|
|
135
|
+
| `overlay_image` | `overlayImage` |
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## API
|
|
140
|
+
|
|
141
|
+
### `new ChameleonBackgrounds(options)`
|
|
142
|
+
|
|
143
|
+
Creates a new instance and immediately begins loading.
|
|
144
|
+
|
|
145
|
+
### `.destroy()`
|
|
146
|
+
|
|
147
|
+
Stops any running slider, removes all injected DOM and styles, and restores the target element to its original state.
|
|
148
|
+
|
|
149
|
+
### `.getOptions()` / `.options` (ESM)
|
|
150
|
+
|
|
151
|
+
Returns a read-only copy of the resolved options.
|
|
152
|
+
|
|
153
|
+
---
|
|
154
|
+
|
|
155
|
+
## Migration from v1
|
|
156
|
+
|
|
157
|
+
1. **Remove jQuery** โ ChameleonBackgrounds v2 uses native DOM APIs.
|
|
158
|
+
2. **Rename options** (optional) โ snake_case names still work, but camelCase is now preferred.
|
|
159
|
+
3. **Use `new`** โ `new ChameleonBackgrounds(options)` works identically to v1.
|
|
160
|
+
4. **Clean up** โ Call `.destroy()` when removing the background (new in v2).
|
|
161
|
+
|
|
162
|
+
```diff
|
|
163
|
+
- <script src="jquery.min.js"></script>
|
|
164
|
+
- <script src="chameleonbackgrounds.js"></script>
|
|
165
|
+
+ <script src="dist/chameleon-backgrounds.js"></script>
|
|
166
|
+
|
|
167
|
+
<script>
|
|
168
|
+
- var options = {
|
|
169
|
+
+ const options = {
|
|
170
|
+
element: 'body',
|
|
171
|
+
type: 'single',
|
|
172
|
+
src: './img/chameleon.jpg',
|
|
173
|
+
overlayColor: '#0f1e25',
|
|
174
|
+
- transition_duration: 2000
|
|
175
|
+
+ transitionDuration: 2000
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
- background = new ChameleonBackgrounds(options);
|
|
179
|
+
+ const background = new ChameleonBackgrounds(options);
|
|
180
|
+
</script>
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
---
|
|
184
|
+
|
|
185
|
+
## Tips
|
|
186
|
+
|
|
187
|
+
- **Transparent patterns** work great as `overlayImage` โ combine with `overlayColor` and `minOverlay` for cohesive designs across different background images.
|
|
188
|
+
- Find awesome transparent patterns at [transparenttextures.com](https://www.transparenttextures.com/).
|
|
189
|
+
|
|
190
|
+
---
|
|
191
|
+
|
|
192
|
+
## License
|
|
193
|
+
|
|
194
|
+
[MIT](./LICENSE) ยฉ [Lennart van Ballegoij](https://weblenn.com/)
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* _____ _ _
|
|
3
|
+
* / ____| | | |
|
|
4
|
+
* | | | |__ __ _ _ __ ___ ___| | ___ ___ _ __
|
|
5
|
+
* | | | '_ \ / _` | '_ ` _ \ / _ \ |/ _ \/ _ \| '_ \
|
|
6
|
+
* | |____| | | | (_| | | | | | | __/ | __/ (_) | | | |
|
|
7
|
+
* \_____|_| |_|\__,_|_| |_| |_|\___|_|\___|\___|_| |_|_
|
|
8
|
+
* | _ \ | | | |
|
|
9
|
+
* | |_) | __ _ ___| | ____ _ _ __ ___ _ _ _ __ __| |___
|
|
10
|
+
* | _ < / _` |/ __| |/ / _` | '__/ _ \| | | | '_ \ / _` / __|
|
|
11
|
+
* | |_) | (_| | (__| < (_| | | | (_) | |_| | | | | (_| \__ \
|
|
12
|
+
* |____/ \__,_|\___|_|\_\__, |_| \___/ \__,_|_| |_|\__,_|___/
|
|
13
|
+
* __/ |
|
|
14
|
+
* |___/
|
|
15
|
+
*
|
|
16
|
+
* ChameleonBackgrounds v2.0.0 โ UMD Bundle
|
|
17
|
+
* A zero-dependency JavaScript library to dynamically load background
|
|
18
|
+
* images with elegant fade-in transitions and slideshow support.
|
|
19
|
+
*
|
|
20
|
+
* @author Lennart van Ballegoij (https://weblenn.com/)
|
|
21
|
+
* @license MIT
|
|
22
|
+
* @see https://github.com/WebLenn/ChameleonBackgrounds
|
|
23
|
+
*/
|
|
24
|
+
(function (root, factory) {
|
|
25
|
+
if (typeof define === 'function' && define.amd) {
|
|
26
|
+
// AMD
|
|
27
|
+
define([], factory);
|
|
28
|
+
} else if (typeof module === 'object' && module.exports) {
|
|
29
|
+
// CommonJS
|
|
30
|
+
module.exports = factory();
|
|
31
|
+
} else {
|
|
32
|
+
// Browser global
|
|
33
|
+
root.ChameleonBackgrounds = factory();
|
|
34
|
+
}
|
|
35
|
+
}(typeof self !== 'undefined' ? self : this, function () {
|
|
36
|
+
'use strict';
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* @typedef {Object} ChameleonOptions
|
|
40
|
+
* @property {string|HTMLElement} element - CSS selector or DOM element to attach to.
|
|
41
|
+
* @property {'single'|'slider'} type - Background mode.
|
|
42
|
+
* @property {string|string[]} src - Image URL(s). String for 'single', array for 'slider'.
|
|
43
|
+
* @property {string} overlayColor - Overlay color (hex, rgb, rgba, hsl).
|
|
44
|
+
* @property {string} [overlayImage] - Optional overlay pattern image URL.
|
|
45
|
+
* @property {number} [minOverlay=0] - Minimum overlay opacity after fade (0โ1).
|
|
46
|
+
* @property {number} [transitionDuration=2000] - Fade duration in milliseconds.
|
|
47
|
+
* @property {number} [sliderDuration=8000] - Time each slide is shown in milliseconds.
|
|
48
|
+
* @property {boolean} [sliderLoop=false] - Whether the slider restarts after the last slide.
|
|
49
|
+
*/
|
|
50
|
+
|
|
51
|
+
const DEFAULTS = Object.freeze({
|
|
52
|
+
element: 'body',
|
|
53
|
+
type: 'single',
|
|
54
|
+
src: '',
|
|
55
|
+
overlayColor: '#0f1e25',
|
|
56
|
+
overlayImage: null,
|
|
57
|
+
minOverlay: 0,
|
|
58
|
+
transitionDuration: 2000,
|
|
59
|
+
sliderDuration: 8000,
|
|
60
|
+
sliderLoop: false,
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
const ALIASES = Object.freeze({
|
|
64
|
+
transition_duration: 'transitionDuration',
|
|
65
|
+
slider_duration: 'sliderDuration',
|
|
66
|
+
slider_loop: 'sliderLoop',
|
|
67
|
+
min_overlay: 'minOverlay',
|
|
68
|
+
overlay_color: 'overlayColor',
|
|
69
|
+
overlay_image: 'overlayImage',
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Convert legacy snake_case option keys to camelCase.
|
|
74
|
+
*/
|
|
75
|
+
function normalizeOptions(opts) {
|
|
76
|
+
const result = {};
|
|
77
|
+
for (const key of Object.keys(opts)) {
|
|
78
|
+
const alias = ALIASES[key];
|
|
79
|
+
result[alias !== undefined ? alias : key] = opts[key];
|
|
80
|
+
}
|
|
81
|
+
return result;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Resolve a CSS selector string or HTMLElement to an HTMLElement.
|
|
86
|
+
*/
|
|
87
|
+
function resolveElement(el) {
|
|
88
|
+
if (el instanceof HTMLElement) return el;
|
|
89
|
+
if (typeof el === 'string') {
|
|
90
|
+
if (el === 'body') return document.body;
|
|
91
|
+
var found = document.querySelector(el);
|
|
92
|
+
if (!found) throw new Error('[ChameleonBackgrounds] Element not found: ' + el);
|
|
93
|
+
return found;
|
|
94
|
+
}
|
|
95
|
+
throw new TypeError('[ChameleonBackgrounds] Invalid element: ' + el);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Generate a short unique ID for scoping styles.
|
|
100
|
+
*/
|
|
101
|
+
function generateUID() {
|
|
102
|
+
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
|
103
|
+
return crypto.randomUUID().slice(0, 8);
|
|
104
|
+
}
|
|
105
|
+
return Array.from({ length: 8 }, function () {
|
|
106
|
+
return 'abcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(Math.random() * 36));
|
|
107
|
+
}).join('');
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// -------------------------------------------------------------------------
|
|
111
|
+
// Constructor
|
|
112
|
+
// -------------------------------------------------------------------------
|
|
113
|
+
|
|
114
|
+
function ChameleonBackgrounds(options) {
|
|
115
|
+
if (!(this instanceof ChameleonBackgrounds)) {
|
|
116
|
+
return new ChameleonBackgrounds(options);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
var normalized = normalizeOptions(options || {});
|
|
120
|
+
this._options = {};
|
|
121
|
+
for (var k in DEFAULTS) {
|
|
122
|
+
if (DEFAULTS.hasOwnProperty(k)) {
|
|
123
|
+
this._options[k] = normalized[k] !== undefined ? normalized[k] : DEFAULTS[k];
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
this._uid = generateUID();
|
|
128
|
+
this._element = resolveElement(this._options.element);
|
|
129
|
+
this._originalHTML = this._element.innerHTML;
|
|
130
|
+
this._styleElement = null;
|
|
131
|
+
this._sliderIntervalId = null;
|
|
132
|
+
this._destroyed = false;
|
|
133
|
+
|
|
134
|
+
this._init();
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// -------------------------------------------------------------------------
|
|
138
|
+
// Public API
|
|
139
|
+
// -------------------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Clean up all injected DOM, styles, and intervals.
|
|
143
|
+
* Restores the target element to its original state.
|
|
144
|
+
*/
|
|
145
|
+
ChameleonBackgrounds.prototype.destroy = function () {
|
|
146
|
+
if (this._destroyed) return;
|
|
147
|
+
this._destroyed = true;
|
|
148
|
+
|
|
149
|
+
if (this._sliderIntervalId !== null) {
|
|
150
|
+
clearInterval(this._sliderIntervalId);
|
|
151
|
+
this._sliderIntervalId = null;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (this._styleElement && this._styleElement.parentNode) {
|
|
155
|
+
this._styleElement.parentNode.removeChild(this._styleElement);
|
|
156
|
+
this._styleElement = null;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
this._element.innerHTML = this._originalHTML;
|
|
160
|
+
this._element.style.backgroundImage = '';
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Readonly copy of the resolved options.
|
|
165
|
+
*/
|
|
166
|
+
ChameleonBackgrounds.prototype.getOptions = function () {
|
|
167
|
+
var copy = {};
|
|
168
|
+
for (var k in this._options) {
|
|
169
|
+
if (this._options.hasOwnProperty(k)) {
|
|
170
|
+
copy[k] = this._options[k];
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return copy;
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// -------------------------------------------------------------------------
|
|
177
|
+
// Initialization (private by convention)
|
|
178
|
+
// -------------------------------------------------------------------------
|
|
179
|
+
|
|
180
|
+
ChameleonBackgrounds.prototype._init = function () {
|
|
181
|
+
this._injectStyles();
|
|
182
|
+
this._buildDOM();
|
|
183
|
+
|
|
184
|
+
var self = this;
|
|
185
|
+
|
|
186
|
+
if (this._element === document.body || this._element.matches('body')) {
|
|
187
|
+
// Use a microtask so the DOM changes settle first
|
|
188
|
+
Promise.resolve().then(function () { self._retrieveBackground(); });
|
|
189
|
+
} else {
|
|
190
|
+
if (document.readyState === 'complete') {
|
|
191
|
+
this._retrieveBackground();
|
|
192
|
+
} else {
|
|
193
|
+
window.addEventListener('load', function onLoad() {
|
|
194
|
+
window.removeEventListener('load', onLoad);
|
|
195
|
+
self._retrieveBackground();
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
ChameleonBackgrounds.prototype._injectStyles = function () {
|
|
202
|
+
var uid = this._uid;
|
|
203
|
+
var selector = this._options.element === 'body' || this._element.matches('body')
|
|
204
|
+
? 'body'
|
|
205
|
+
: this._options.element;
|
|
206
|
+
var duration = this._options.transitionDuration / 1000;
|
|
207
|
+
var position = this._element.matches('body') ? 'fixed' : 'absolute';
|
|
208
|
+
var overlayBg = this._options.overlayImage
|
|
209
|
+
? 'url(' + this._options.overlayImage + ')'
|
|
210
|
+
: 'none';
|
|
211
|
+
|
|
212
|
+
var selectorStr = typeof selector === 'string' ? selector : '.cbg-host-' + uid;
|
|
213
|
+
|
|
214
|
+
var css =
|
|
215
|
+
selectorStr + ' { position: relative; } ' +
|
|
216
|
+
'#cbg-inner-' + uid + ' { z-index: 2; position: relative; } ' +
|
|
217
|
+
'.cbg-loader-' + uid + ' { ' +
|
|
218
|
+
'height: 100%; width: 100%; ' +
|
|
219
|
+
'position: ' + position + '; ' +
|
|
220
|
+
'background-image: ' + overlayBg + '; ' +
|
|
221
|
+
'background-color: ' + this._options.overlayColor + '; ' +
|
|
222
|
+
'opacity: 1; z-index: 1; ' +
|
|
223
|
+
'transition: opacity ' + duration + 's ease; ' +
|
|
224
|
+
'top: 0; left: 0; ' +
|
|
225
|
+
'}';
|
|
226
|
+
|
|
227
|
+
var style = document.createElement('style');
|
|
228
|
+
style.setAttribute('data-chameleon-uid', uid);
|
|
229
|
+
style.textContent = css;
|
|
230
|
+
document.head.appendChild(style);
|
|
231
|
+
this._styleElement = style;
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
ChameleonBackgrounds.prototype._buildDOM = function () {
|
|
235
|
+
var uid = this._uid;
|
|
236
|
+
var content = this._element.innerHTML;
|
|
237
|
+
|
|
238
|
+
var wrapper = document.createElement('div');
|
|
239
|
+
wrapper.id = 'cbg-inner-' + uid;
|
|
240
|
+
wrapper.innerHTML = content;
|
|
241
|
+
|
|
242
|
+
var loader = document.createElement('div');
|
|
243
|
+
loader.className = 'cbg-loader-' + uid;
|
|
244
|
+
|
|
245
|
+
this._element.innerHTML = '';
|
|
246
|
+
this._element.appendChild(wrapper);
|
|
247
|
+
this._element.appendChild(loader);
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
// -------------------------------------------------------------------------
|
|
251
|
+
// Background Loading
|
|
252
|
+
// -------------------------------------------------------------------------
|
|
253
|
+
|
|
254
|
+
ChameleonBackgrounds.prototype._retrieveBackground = function () {
|
|
255
|
+
if (this._destroyed) return;
|
|
256
|
+
|
|
257
|
+
if (this._options.type === 'single') {
|
|
258
|
+
var src = typeof this._options.src === 'string'
|
|
259
|
+
? this._options.src
|
|
260
|
+
: this._options.src[0];
|
|
261
|
+
this._loadBackground(src);
|
|
262
|
+
} else if (this._options.type === 'slider') {
|
|
263
|
+
this._startSlider();
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
ChameleonBackgrounds.prototype._loadBackground = function (src, callback) {
|
|
268
|
+
if (this._destroyed) { if (callback) callback(); return; }
|
|
269
|
+
|
|
270
|
+
var self = this;
|
|
271
|
+
var img = new Image();
|
|
272
|
+
|
|
273
|
+
img.onload = function () {
|
|
274
|
+
if (self._destroyed) { if (callback) callback(); return; }
|
|
275
|
+
|
|
276
|
+
self._element.style.backgroundImage = 'url(' + src + ')';
|
|
277
|
+
self._element.style.backgroundSize = 'cover';
|
|
278
|
+
|
|
279
|
+
var loader = self._element.querySelector('.cbg-loader-' + self._uid);
|
|
280
|
+
if (loader) {
|
|
281
|
+
loader.style.opacity = String(self._options.minOverlay);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
if (callback) callback();
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
img.onerror = function () {
|
|
288
|
+
console.warn('[ChameleonBackgrounds] Failed to load image: ' + src);
|
|
289
|
+
if (callback) callback();
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
img.src = src;
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
ChameleonBackgrounds.prototype.reloadBackground = function (src, callback) {
|
|
296
|
+
if (this._destroyed) { if (callback) callback(); return; }
|
|
297
|
+
|
|
298
|
+
var loader = this._element.querySelector('.cbg-loader-' + this._uid);
|
|
299
|
+
if (loader) {
|
|
300
|
+
loader.style.opacity = '1';
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
var self = this;
|
|
304
|
+
setTimeout(function () {
|
|
305
|
+
if (self._destroyed) { if (callback) callback(); return; }
|
|
306
|
+
self._loadBackground(src, callback);
|
|
307
|
+
}, this._options.transitionDuration);
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
// -------------------------------------------------------------------------
|
|
311
|
+
// Slider
|
|
312
|
+
// -------------------------------------------------------------------------
|
|
313
|
+
|
|
314
|
+
ChameleonBackgrounds.prototype._startSlider = function () {
|
|
315
|
+
if (this._destroyed) return;
|
|
316
|
+
|
|
317
|
+
var sources = this._options.src;
|
|
318
|
+
if (!Array.isArray(sources) || sources.length === 0) {
|
|
319
|
+
console.warn('[ChameleonBackgrounds] Slider mode requires an array of image URLs in `src`.');
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
var self = this;
|
|
324
|
+
var index = 0;
|
|
325
|
+
|
|
326
|
+
this._loadBackground(sources[index], function () {
|
|
327
|
+
if (self._destroyed) return;
|
|
328
|
+
|
|
329
|
+
index = 1;
|
|
330
|
+
if (sources.length === 1) return;
|
|
331
|
+
|
|
332
|
+
var interval = self._options.sliderDuration + self._options.transitionDuration * 2;
|
|
333
|
+
|
|
334
|
+
self._sliderIntervalId = setInterval(function () {
|
|
335
|
+
if (self._destroyed) {
|
|
336
|
+
clearInterval(self._sliderIntervalId);
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
self.reloadBackground(sources[index]);
|
|
341
|
+
index++;
|
|
342
|
+
|
|
343
|
+
if (index >= sources.length) {
|
|
344
|
+
if (self._options.sliderLoop) {
|
|
345
|
+
index = 0;
|
|
346
|
+
} else {
|
|
347
|
+
clearInterval(self._sliderIntervalId);
|
|
348
|
+
self._sliderIntervalId = null;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}, interval);
|
|
352
|
+
});
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
return ChameleonBackgrounds;
|
|
356
|
+
}));
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! For license information please see chameleon-backgrounds.min.js.LICENSE.txt */
|
|
2
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ChameleonBackgrounds=t():e.ChameleonBackgrounds=t()}(this,()=>(()=>{"use strict";const e={d:(t,n)=>{if(Array.isArray(n))for(var o=0;o<n.length;){var r=n[o++],i=n[o++];e.o(t,r)?0===i&&o++:0===i?Object.defineProperty(t,r,{enumerable:!0,value:n[o++]}):Object.defineProperty(t,r,{enumerable:!0,get:i})}else for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};let t={};class n{static#e=Object.freeze({element:"body",type:"single",src:"",overlayColor:"#0f1e25",overlayImage:null,minOverlay:0,transitionDuration:2e3,sliderDuration:8e3,sliderLoop:!1});static#t=Object.freeze({transition_duration:"transitionDuration",slider_duration:"sliderDuration",slider_loop:"sliderLoop",min_overlay:"minOverlay",overlay_color:"overlayColor",overlay_image:"overlayImage"});#n;#o;#r;#i;#s=null;#l=null;#a=!1;constructor(e={}){const t=n.#d(e);this.#n={...n.#e,...t},this.#r=n.#c(),this.#o=n.#h(this.#n.element),this.#i=this.#o.innerHTML,this.#u()}destroy(){this.#a||(this.#a=!0,null!==this.#l&&(clearInterval(this.#l),this.#l=null),this.#s?.parentNode&&(this.#s.parentNode.removeChild(this.#s),this.#s=null),this.#o.innerHTML=this.#i,this.#o.style.backgroundImage="")}get options(){return{...this.#n}}#u(){this.#m(),this.#y(),this.#o.matches("body")?queueMicrotask(()=>this.#p()):"complete"===document.readyState?this.#p():window.addEventListener("load",()=>this.#p(),{once:!0})}#m(){const e=this.#r,t="body"===this.#n.element||this.#o.matches("body")?"body":this.#n.element,n=this.#n.transitionDuration/1e3,o=`\n ${"string"==typeof t?t:`.cbg-host-${e}`} {\n position: relative;\n }\n\n #cbg-inner-${e} {\n z-index: 2;\n position: relative;\n }\n\n .cbg-loader-${e} {\n height: 100%;\n width: 100%;\n position: ${this.#o.matches("body")?"fixed":"absolute"};\n background-image: ${this.#n.overlayImage?`url(${this.#n.overlayImage})`:"none"};\n background-color: ${this.#n.overlayColor};\n opacity: 1;\n z-index: 1;\n transition: opacity ${n}s ease;\n top: 0;\n left: 0;\n }\n `,r=document.createElement("style");r.dataset.chameleonUid=e,r.textContent=o,document.head.appendChild(r),this.#s=r}#y(){const e=this.#r,t=this.#o.innerHTML,n=document.createElement("div");n.id=`cbg-inner-${e}`,n.innerHTML=t;const o=document.createElement("div");o.classList.add(`cbg-loader-${e}`),this.#o.innerHTML="",this.#o.appendChild(n),this.#o.appendChild(o)}#p(){this.#a||("single"===this.#n.type?this.#g("string"==typeof this.#n.src?this.#n.src:this.#n.src[0]):"slider"===this.#n.type&&this.#f())}#g(e,t=!0){return this.#a?Promise.resolve():new Promise(t=>{const n=new Image;n.onload=()=>{if(this.#a)return t();this.#o.style.backgroundImage=`url(${e})`,this.#o.style.backgroundSize="cover";const n=this.#o.querySelector(`.cbg-loader-${this.#r}`);n&&(n.style.opacity=String(this.#n.minOverlay)),t()},n.onerror=()=>{console.warn(`[ChameleonBackgrounds] Failed to load image: ${e}`),t()},n.src=e})}reloadBackground(e){if(this.#a)return Promise.resolve();const t=this.#o.querySelector(`.cbg-loader-${this.#r}`);return t&&(t.style.opacity="1"),new Promise(t=>{setTimeout(()=>{if(this.#a)return t();this.#g(e,!1).then(t)},this.#n.transitionDuration)})}#f(){if(this.#a)return;const e=this.#n.src;if(!Array.isArray(e)||0===e.length)return void console.warn("[ChameleonBackgrounds] Slider mode requires an array of image URLs in `src`.");let t=0;this.#g(e[t]).then(()=>{if(this.#a)return;if(t=1,1===e.length)return;const n=this.#n.sliderDuration+2*this.#n.transitionDuration;this.#l=setInterval(()=>{this.#a?clearInterval(this.#l):(this.reloadBackground(e[t]),t++,t>=e.length&&(this.#n.sliderLoop?t=0:(clearInterval(this.#l),this.#l=null)))},n)})}static#d(e){const t={};for(const[o,r]of Object.entries(e))t[n.#t[o]??o]=r;return t}static#h(e){if(e instanceof HTMLElement)return e;if("string"==typeof e){if("body"===e)return document.body;const t=document.querySelector(e);if(!t)throw new Error(`[ChameleonBackgrounds] Element not found: ${e}`);return t}throw new TypeError(`[ChameleonBackgrounds] Invalid element: ${e}`)}static#c(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID().slice(0,8):Array.from({length:8},()=>"abcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(36*Math.random()))).join("")}}const o=n;return e.d(t,["default",0,o]),t=t.default,t})());
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* _____ _ _
|
|
3
|
+
* / ____| | | |
|
|
4
|
+
* | | | |__ __ _ _ __ ___ ___| | ___ ___ _ __
|
|
5
|
+
* | | | '_ \ / _` | '_ ` _ \ / _ \ |/ _ \/ _ \| '_ \
|
|
6
|
+
* | |____| | | | (_| | | | | | | __/ | __/ (_) | | | |
|
|
7
|
+
* \_____|_| |_|\__,_|_| |_| |_|\___|_|\___|\___|_| |_|_
|
|
8
|
+
* | _ \ | | | |
|
|
9
|
+
* | |_) | __ _ ___| | ____ _ _ __ ___ _ _ _ __ __| |___
|
|
10
|
+
* | _ < / _` |/ __| |/ / _` | '__/ _ \| | | | '_ \ / _` / __|
|
|
11
|
+
* | |_) | (_| | (__| < (_| | | | (_) | |_| | | | | (_| \__ \
|
|
12
|
+
* |____/ \__,_|\___|_|\_\__, |_| \___/ \__,_|_| |_|\__,_|___/
|
|
13
|
+
* __/ |
|
|
14
|
+
* |___/
|
|
15
|
+
*
|
|
16
|
+
* @module ChameleonBackgrounds
|
|
17
|
+
* @version 2.0.0
|
|
18
|
+
* @author Lennart van Ballegoij (https://weblenn.com/)
|
|
19
|
+
* @license MIT
|
|
20
|
+
* @see https://github.com/WebLenn/ChameleonBackgrounds
|
|
21
|
+
*
|
|
22
|
+
* A zero-dependency JavaScript library to dynamically load background
|
|
23
|
+
* images with elegant fade-in transitions and slideshow support.
|
|
24
|
+
*/
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "chameleon-backgrounds",
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "A zero-dependency JavaScript library to dynamically load background images with elegant fade-in transitions and slideshow support.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/chameleon-backgrounds.js",
|
|
7
|
+
"module": "src/chameleon-backgrounds.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./src/chameleon-backgrounds.js",
|
|
11
|
+
"require": "./dist/chameleon-backgrounds.js",
|
|
12
|
+
"default": "./dist/chameleon-backgrounds.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"src/",
|
|
17
|
+
"dist/",
|
|
18
|
+
"README.md",
|
|
19
|
+
"LICENSE"
|
|
20
|
+
],
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "webpack",
|
|
23
|
+
"test": "echo \"Open test/index.html in a browser to test.\""
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"background",
|
|
27
|
+
"image",
|
|
28
|
+
"loader",
|
|
29
|
+
"slider",
|
|
30
|
+
"slideshow",
|
|
31
|
+
"fade",
|
|
32
|
+
"transition",
|
|
33
|
+
"vanilla",
|
|
34
|
+
"javascript",
|
|
35
|
+
"no-jquery"
|
|
36
|
+
],
|
|
37
|
+
"author": "Lennart van Ballegoij (https://weblenn.com/)",
|
|
38
|
+
"license": "MIT",
|
|
39
|
+
"repository": {
|
|
40
|
+
"type": "git",
|
|
41
|
+
"url": "git+https://github.com/WebLenn/ChameleonBackgrounds.git"
|
|
42
|
+
},
|
|
43
|
+
"homepage": "https://github.com/WebLenn/ChameleonBackgrounds#readme",
|
|
44
|
+
"bugs": {
|
|
45
|
+
"url": "https://github.com/WebLenn/ChameleonBackgrounds/issues"
|
|
46
|
+
},
|
|
47
|
+
"directories": {
|
|
48
|
+
"test": "test"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"webpack": "^5.109.0",
|
|
52
|
+
"webpack-cli": "^7.2.1"
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* _____ _ _
|
|
3
|
+
* / ____| | | |
|
|
4
|
+
* | | | |__ __ _ _ __ ___ ___| | ___ ___ _ __
|
|
5
|
+
* | | | '_ \ / _` | '_ ` _ \ / _ \ |/ _ \/ _ \| '_ \
|
|
6
|
+
* | |____| | | | (_| | | | | | | __/ | __/ (_) | | | |
|
|
7
|
+
* \_____|_| |_|\__,_|_| |_| |_|\___|_|\___|\___|_| |_|_
|
|
8
|
+
* | _ \ | | | |
|
|
9
|
+
* | |_) | __ _ ___| | ____ _ _ __ ___ _ _ _ __ __| |___
|
|
10
|
+
* | _ < / _` |/ __| |/ / _` | '__/ _ \| | | | '_ \ / _` / __|
|
|
11
|
+
* | |_) | (_| | (__| < (_| | | | (_) | |_| | | | | (_| \__ \
|
|
12
|
+
* |____/ \__,_|\___|_|\_\__, |_| \___/ \__,_|_| |_|\__,_|___/
|
|
13
|
+
* __/ |
|
|
14
|
+
* |___/
|
|
15
|
+
*
|
|
16
|
+
* @module ChameleonBackgrounds
|
|
17
|
+
* @version 2.0.0
|
|
18
|
+
* @author Lennart van Ballegoij (https://weblenn.com/)
|
|
19
|
+
* @license MIT
|
|
20
|
+
* @see https://github.com/WebLenn/ChameleonBackgrounds
|
|
21
|
+
*
|
|
22
|
+
* A zero-dependency JavaScript library to dynamically load background
|
|
23
|
+
* images with elegant fade-in transitions and slideshow support.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @typedef {Object} ChameleonOptions
|
|
28
|
+
* @property {string|HTMLElement} element - CSS selector or DOM element to attach to.
|
|
29
|
+
* @property {'single'|'slider'} type - Background mode.
|
|
30
|
+
* @property {string|string[]} src - Image URL(s). String for 'single', array for 'slider'.
|
|
31
|
+
* @property {string} overlayColor - Overlay color (hex, rgb, rgba, hsl).
|
|
32
|
+
* @property {string} [overlayImage] - Optional overlay pattern image URL.
|
|
33
|
+
* @property {number} [minOverlay=0] - Minimum overlay opacity after fade (0โ1).
|
|
34
|
+
* @property {number} [transitionDuration=2000] - Fade duration in milliseconds.
|
|
35
|
+
* @property {number} [sliderDuration=8000] - Time each slide is shown in milliseconds.
|
|
36
|
+
* @property {boolean} [sliderLoop=false] - Whether the slider restarts after the last slide.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
class ChameleonBackgrounds {
|
|
40
|
+
/** @type {ChameleonOptions} */
|
|
41
|
+
static #DEFAULTS = Object.freeze({
|
|
42
|
+
element: 'body',
|
|
43
|
+
type: 'single',
|
|
44
|
+
src: '',
|
|
45
|
+
overlayColor: '#0f1e25',
|
|
46
|
+
overlayImage: null,
|
|
47
|
+
minOverlay: 0,
|
|
48
|
+
transitionDuration: 2000,
|
|
49
|
+
sliderDuration: 8000,
|
|
50
|
+
sliderLoop: false,
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// Legacy snake_case โ camelCase alias map
|
|
54
|
+
static #ALIASES = Object.freeze({
|
|
55
|
+
transition_duration: 'transitionDuration',
|
|
56
|
+
slider_duration: 'sliderDuration',
|
|
57
|
+
slider_loop: 'sliderLoop',
|
|
58
|
+
min_overlay: 'minOverlay',
|
|
59
|
+
overlay_color: 'overlayColor',
|
|
60
|
+
overlay_image: 'overlayImage',
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
/** @type {ChameleonOptions} */
|
|
64
|
+
#options;
|
|
65
|
+
|
|
66
|
+
/** @type {HTMLElement} */
|
|
67
|
+
#element;
|
|
68
|
+
|
|
69
|
+
/** @type {string} */
|
|
70
|
+
#uid;
|
|
71
|
+
|
|
72
|
+
/** @type {string} */
|
|
73
|
+
#originalHTML;
|
|
74
|
+
|
|
75
|
+
/** @type {HTMLStyleElement|null} */
|
|
76
|
+
#styleElement = null;
|
|
77
|
+
|
|
78
|
+
/** @type {number|null} */
|
|
79
|
+
#sliderIntervalId = null;
|
|
80
|
+
|
|
81
|
+
/** @type {boolean} */
|
|
82
|
+
#destroyed = false;
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Create a new ChameleonBackgrounds instance.
|
|
86
|
+
* @param {Partial<ChameleonOptions>} [options]
|
|
87
|
+
*/
|
|
88
|
+
constructor(options = {}) {
|
|
89
|
+
const normalized = ChameleonBackgrounds.#normalizeOptions(options);
|
|
90
|
+
this.#options = { ...ChameleonBackgrounds.#DEFAULTS, ...normalized };
|
|
91
|
+
this.#uid = ChameleonBackgrounds.#generateUID();
|
|
92
|
+
this.#element = ChameleonBackgrounds.#resolveElement(this.#options.element);
|
|
93
|
+
this.#originalHTML = this.#element.innerHTML;
|
|
94
|
+
|
|
95
|
+
this.#init();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ---------------------------------------------------------------------------
|
|
99
|
+
// Public API
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Clean up all injected DOM, styles, and intervals.
|
|
104
|
+
* Restores the target element to its original state.
|
|
105
|
+
*/
|
|
106
|
+
destroy() {
|
|
107
|
+
if (this.#destroyed) return;
|
|
108
|
+
this.#destroyed = true;
|
|
109
|
+
|
|
110
|
+
// Stop any running slider
|
|
111
|
+
if (this.#sliderIntervalId !== null) {
|
|
112
|
+
clearInterval(this.#sliderIntervalId);
|
|
113
|
+
this.#sliderIntervalId = null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Remove injected style element
|
|
117
|
+
if (this.#styleElement?.parentNode) {
|
|
118
|
+
this.#styleElement.parentNode.removeChild(this.#styleElement);
|
|
119
|
+
this.#styleElement = null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Restore original HTML and remove inline background-image
|
|
123
|
+
this.#element.innerHTML = this.#originalHTML;
|
|
124
|
+
this.#element.style.backgroundImage = '';
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The resolved options (read-only copy).
|
|
129
|
+
* @returns {ChameleonOptions}
|
|
130
|
+
*/
|
|
131
|
+
get options() {
|
|
132
|
+
return { ...this.#options };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// ---------------------------------------------------------------------------
|
|
136
|
+
// Initialization
|
|
137
|
+
// ---------------------------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
#init() {
|
|
140
|
+
this.#injectStyles();
|
|
141
|
+
this.#buildDOM();
|
|
142
|
+
|
|
143
|
+
// If the element is NOT <body>, wait for window load to start loading images.
|
|
144
|
+
// For <body>, the loader is already visible, so we start immediately to avoid
|
|
145
|
+
// the re-execution issue the legacy lib had with body scripts.
|
|
146
|
+
if (this.#element.matches('body')) {
|
|
147
|
+
// Use a microtask so the DOM changes above settle first.
|
|
148
|
+
queueMicrotask(() => this.#retrieveBackground());
|
|
149
|
+
} else {
|
|
150
|
+
if (document.readyState === 'complete') {
|
|
151
|
+
this.#retrieveBackground();
|
|
152
|
+
} else {
|
|
153
|
+
window.addEventListener('load', () => this.#retrieveBackground(), { once: true });
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// ---------------------------------------------------------------------------
|
|
159
|
+
// DOM Construction
|
|
160
|
+
// ---------------------------------------------------------------------------
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Inject a scoped <style> element into the <head>.
|
|
164
|
+
*/
|
|
165
|
+
#injectStyles() {
|
|
166
|
+
const uid = this.#uid;
|
|
167
|
+
const selector = this.#options.element === 'body' || this.#element.matches('body')
|
|
168
|
+
? 'body'
|
|
169
|
+
: this.#options.element;
|
|
170
|
+
const duration = this.#options.transitionDuration / 1000; // ms โ s
|
|
171
|
+
const position = this.#element.matches('body') ? 'fixed' : 'absolute';
|
|
172
|
+
const overlayBg = this.#options.overlayImage
|
|
173
|
+
? `url(${this.#options.overlayImage})`
|
|
174
|
+
: 'none';
|
|
175
|
+
|
|
176
|
+
const css = `
|
|
177
|
+
${typeof selector === 'string' ? selector : `.cbg-host-${uid}`} {
|
|
178
|
+
position: relative;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
#cbg-inner-${uid} {
|
|
182
|
+
z-index: 2;
|
|
183
|
+
position: relative;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
.cbg-loader-${uid} {
|
|
187
|
+
height: 100%;
|
|
188
|
+
width: 100%;
|
|
189
|
+
position: ${position};
|
|
190
|
+
background-image: ${overlayBg};
|
|
191
|
+
background-color: ${this.#options.overlayColor};
|
|
192
|
+
opacity: 1;
|
|
193
|
+
z-index: 1;
|
|
194
|
+
transition: opacity ${duration}s ease;
|
|
195
|
+
top: 0;
|
|
196
|
+
left: 0;
|
|
197
|
+
}
|
|
198
|
+
`;
|
|
199
|
+
|
|
200
|
+
const style = document.createElement('style');
|
|
201
|
+
style.dataset.chameleonUid = uid;
|
|
202
|
+
style.textContent = css;
|
|
203
|
+
document.head.appendChild(style);
|
|
204
|
+
this.#styleElement = style;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Wrap existing content and insert the overlay loader.
|
|
209
|
+
*/
|
|
210
|
+
#buildDOM() {
|
|
211
|
+
const uid = this.#uid;
|
|
212
|
+
const content = this.#element.innerHTML;
|
|
213
|
+
|
|
214
|
+
const wrapper = document.createElement('div');
|
|
215
|
+
wrapper.id = `cbg-inner-${uid}`;
|
|
216
|
+
wrapper.innerHTML = content;
|
|
217
|
+
|
|
218
|
+
const loader = document.createElement('div');
|
|
219
|
+
loader.classList.add(`cbg-loader-${uid}`);
|
|
220
|
+
|
|
221
|
+
// Replace element contents
|
|
222
|
+
this.#element.innerHTML = '';
|
|
223
|
+
this.#element.appendChild(wrapper);
|
|
224
|
+
this.#element.appendChild(loader);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// ---------------------------------------------------------------------------
|
|
228
|
+
// Background Loading
|
|
229
|
+
// ---------------------------------------------------------------------------
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Route to the correct loader based on type.
|
|
233
|
+
*/
|
|
234
|
+
#retrieveBackground() {
|
|
235
|
+
if (this.#destroyed) return;
|
|
236
|
+
|
|
237
|
+
if (this.#options.type === 'single') {
|
|
238
|
+
this.#loadBackground(typeof this.#options.src === 'string' ? this.#options.src : this.#options.src[0]);
|
|
239
|
+
} else if (this.#options.type === 'slider') {
|
|
240
|
+
this.#startSlider();
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Preload an image and apply it as the element's background.
|
|
246
|
+
* @param {string} src - Image URL to load.
|
|
247
|
+
* @param {boolean} [isFirst=true] - Whether this is the first image (skips overlay reset).
|
|
248
|
+
* @returns {Promise<void>}
|
|
249
|
+
*/
|
|
250
|
+
#loadBackground(src, isFirst = true) {
|
|
251
|
+
if (this.#destroyed) return Promise.resolve();
|
|
252
|
+
|
|
253
|
+
return new Promise((resolve) => {
|
|
254
|
+
const img = new Image();
|
|
255
|
+
|
|
256
|
+
img.onload = () => {
|
|
257
|
+
if (this.#destroyed) return resolve();
|
|
258
|
+
|
|
259
|
+
this.#element.style.backgroundImage = `url(${src})`;
|
|
260
|
+
this.#element.style.backgroundSize = 'cover';
|
|
261
|
+
|
|
262
|
+
const loader = this.#element.querySelector(`.cbg-loader-${this.#uid}`);
|
|
263
|
+
if (loader) {
|
|
264
|
+
loader.style.opacity = String(this.#options.minOverlay);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
resolve();
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
img.onerror = () => {
|
|
271
|
+
console.warn(`[ChameleonBackgrounds] Failed to load image: ${src}`);
|
|
272
|
+
resolve();
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
img.src = src;
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Reload background with a fade-out โ swap โ fade-in cycle.
|
|
281
|
+
* @param {string} src - New image URL.
|
|
282
|
+
* @returns {Promise<void>}
|
|
283
|
+
*/
|
|
284
|
+
reloadBackground(src) {
|
|
285
|
+
if (this.#destroyed) return Promise.resolve();
|
|
286
|
+
|
|
287
|
+
const loader = this.#element.querySelector(`.cbg-loader-${this.#uid}`);
|
|
288
|
+
if (loader) {
|
|
289
|
+
loader.style.opacity = '1';
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
return new Promise((resolve) => {
|
|
293
|
+
setTimeout(() => {
|
|
294
|
+
if (this.#destroyed) return resolve();
|
|
295
|
+
this.#loadBackground(src, false).then(resolve);
|
|
296
|
+
}, this.#options.transitionDuration);
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// ---------------------------------------------------------------------------
|
|
301
|
+
// Slider
|
|
302
|
+
// ---------------------------------------------------------------------------
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Start the background slideshow.
|
|
306
|
+
*/
|
|
307
|
+
#startSlider() {
|
|
308
|
+
if (this.#destroyed) return;
|
|
309
|
+
|
|
310
|
+
const sources = this.#options.src;
|
|
311
|
+
if (!Array.isArray(sources) || sources.length === 0) {
|
|
312
|
+
console.warn('[ChameleonBackgrounds] Slider mode requires an array of image URLs in `src`.');
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// Load the first slide immediately
|
|
317
|
+
let index = 0;
|
|
318
|
+
this.#loadBackground(sources[index]).then(() => {
|
|
319
|
+
if (this.#destroyed) return;
|
|
320
|
+
|
|
321
|
+
index = 1;
|
|
322
|
+
if (sources.length === 1) return; // only one slide, nothing to rotate
|
|
323
|
+
|
|
324
|
+
const interval = this.#options.sliderDuration + this.#options.transitionDuration * 2;
|
|
325
|
+
|
|
326
|
+
this.#sliderIntervalId = setInterval(() => {
|
|
327
|
+
if (this.#destroyed) {
|
|
328
|
+
clearInterval(this.#sliderIntervalId);
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
this.reloadBackground(sources[index]);
|
|
333
|
+
index++;
|
|
334
|
+
|
|
335
|
+
if (index >= sources.length) {
|
|
336
|
+
if (this.#options.sliderLoop) {
|
|
337
|
+
index = 0;
|
|
338
|
+
} else {
|
|
339
|
+
clearInterval(this.#sliderIntervalId);
|
|
340
|
+
this.#sliderIntervalId = null;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}, interval);
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// ---------------------------------------------------------------------------
|
|
348
|
+
// Static Helpers
|
|
349
|
+
// ---------------------------------------------------------------------------
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Convert legacy snake_case option keys to camelCase.
|
|
353
|
+
* @param {Object} opts
|
|
354
|
+
* @returns {Object}
|
|
355
|
+
*/
|
|
356
|
+
static #normalizeOptions(opts) {
|
|
357
|
+
const result = {};
|
|
358
|
+
for (const [key, value] of Object.entries(opts)) {
|
|
359
|
+
const alias = ChameleonBackgrounds.#ALIASES[key];
|
|
360
|
+
result[alias ?? key] = value;
|
|
361
|
+
}
|
|
362
|
+
return result;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Resolve a CSS selector string or HTMLElement to an HTMLElement.
|
|
367
|
+
* @param {string|HTMLElement} el
|
|
368
|
+
* @returns {HTMLElement}
|
|
369
|
+
*/
|
|
370
|
+
static #resolveElement(el) {
|
|
371
|
+
if (el instanceof HTMLElement) return el;
|
|
372
|
+
if (typeof el === 'string') {
|
|
373
|
+
if (el === 'body') return document.body;
|
|
374
|
+
const found = document.querySelector(el);
|
|
375
|
+
if (!found) throw new Error(`[ChameleonBackgrounds] Element not found: ${el}`);
|
|
376
|
+
return /** @type {HTMLElement} */ (found);
|
|
377
|
+
}
|
|
378
|
+
throw new TypeError(`[ChameleonBackgrounds] Invalid element: ${el}`);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Generate a short unique ID for scoping styles.
|
|
383
|
+
* @returns {string}
|
|
384
|
+
*/
|
|
385
|
+
static #generateUID() {
|
|
386
|
+
// Prefer crypto.randomUUID where available, otherwise fall back
|
|
387
|
+
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
|
388
|
+
return crypto.randomUUID().slice(0, 8);
|
|
389
|
+
}
|
|
390
|
+
// Fallback: random alphanumeric string
|
|
391
|
+
return Array.from({ length: 8 }, () =>
|
|
392
|
+
'abcdefghijklmnopqrstuvwxyz0123456789'.charAt(Math.floor(Math.random() * 36))
|
|
393
|
+
).join('');
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
export default ChameleonBackgrounds;
|
|
398
|
+
export { ChameleonBackgrounds };
|