Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- export default class createImageObject{
- /**
- *
- * @param {Element to be animated} el
- * @param {ClassName to be added once loaded} className
- */
- constructor(el, className) {
- this.item = el;
- this.type = el.tagName;
- this.className = className;
- this.mobile = false;
- this.source = this.setSource();
- /**
- * Throw error if image cannot be loaded due a undefined image url;
- */
- if (this.type === 'IMG' && this.source === undefined || this.type === 'FIGURE' && this.source === undefined) {
- throw Error ("Couldn't load image source. Please check again");
- }
- /**
- * If type not equals an image tag or figure tag, we just add the class
- * to trigger the animation / load.
- */
- if (this.type !== 'IMG' && this.type !== 'FIGURE') {
- this.item.classList.add(this.className);
- return ;
- }
- /**
- * If everthing passed, create new image Instance;
- */
- this.createImage();
- };
- createImage() {
- this.image = new Image();
- this.image.src = this.source;
- this.image.onload = () => {
- if (this.type === 'IMG') {
- this.item.src = this.source;
- } else {
- this.item.style.backgroundImage = `url(${this.source})`;
- }
- this.item.classList.add(this.className);
- };
- this.image.onerror = (error) => {
- throw Error(error);
- }
- }
- setSource() {
- if (window.innerWidth < 768) { this.mobile = true; };
- if (this.mobile && this.item.dataset.mobileSrc !== undefined) {
- this.source = this.item.dataset.mobileSrc
- return this.item.dataset.mobileSrc;
- };
- return this.item.dataset.src;
- }
- }
Add Comment
Please, Sign In to add comment