From c93b9af4b133423710f5d3cc258cb3ae30b19f68 Mon Sep 17 00:00:00 2001 From: Dan Head Date: Sun, 29 Apr 2018 18:06:36 +0100 Subject: [PATCH] Ensure images don't get stuck on opacity 0 --- js/image.js | 12 ++++++++---- js/image.spec.js | 30 ++++++++++++++++++++++++++---- js/windy.js | 2 +- 3 files changed, 35 insertions(+), 9 deletions(-) diff --git a/js/image.js b/js/image.js index 56bac49..56c3871 100644 --- a/js/image.js +++ b/js/image.js @@ -3,16 +3,20 @@ export default class Image { this.image = image; } - showImage() { + fadeIn() { this.image.style.opacity = 1; } - fadeIn() { + start() { this.image.style.opacity = 0; - this.attachLoadedEvent(); + if (this.image.complete) { + this.fadeIn(); + } else { + this.attachLoadedEvent(); + } } attachLoadedEvent() { - this.image.addEventListener('load', () => this.showImage()); + this.image.addEventListener('load', () => this.fadeIn()); } } diff --git a/js/image.spec.js b/js/image.spec.js index 41705b5..b91cd62 100644 --- a/js/image.spec.js +++ b/js/image.spec.js @@ -20,16 +20,38 @@ describe('Image', () => { expect(img.image).toBe(image); }); - test('fadeIn should set the element opacity to 0', () => { + test('fadeIn should set the element opacity to 1', () => { const img = new Image(image); img.fadeIn(); + expect(img.image.style.opacity).toBe('1'); + }); + + test('start should set the element opacity to 0', () => { + const img = new Image(image); + img.start(); expect(img.image.style.opacity).toBe('0'); }); - test('showImage should set the element opacity to 1', () => { + test('start should call fadeIn when image has already loaded', () => { const img = new Image(image); - img.showImage(); - expect(img.image.style.opacity).toBe('1'); + img.fadeIn = jest.fn(); + Object.defineProperty(img.image, 'complete', { + value: true, + writable: false, + }); + img.start(); + expect(img.fadeIn).toHaveBeenCalledTimes(1); + }); + + test('start should call attachLoadedEvent if image has not yet loaded', () => { + const img = new Image(image); + img.attachLoadedEvent = jest.fn(); + Object.defineProperty(img.image, 'complete', { + value: false, + writable: false, + }); + img.start(); + expect(img.attachLoadedEvent).toHaveBeenCalledTimes(1); }); }); diff --git a/js/windy.js b/js/windy.js index f39b896..cfb75f2 100644 --- a/js/windy.js +++ b/js/windy.js @@ -9,7 +9,7 @@ const windy = { export default function init() { document.querySelectorAll('img').forEach((image) => { const img = new Image(image); - img.fadeIn(); + img.start(); windy.images.push(img); }); windy.menu = new Menu({