Guest User

Untitled

a guest
Nov 14th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. 'use strict';
  2. export default class createImageObject{
  3.  
  4. /**
  5. *
  6. * @param {Element to be animated} el
  7. * @param {ClassName to be added once loaded} className
  8. */
  9. constructor(el, className) {
  10. this.item = el;
  11. this.type = el.tagName;
  12. this.className = className;
  13. this.mobile = false;
  14. this.source = this.setSource();
  15.  
  16. /**
  17. * Throw error if image cannot be loaded due a undefined image url;
  18. */
  19. if (this.type === 'IMG' && this.source === undefined || this.type === 'FIGURE' && this.source === undefined) {
  20. throw Error ("Couldn't load image source. Please check again");
  21. }
  22.  
  23. /**
  24. * If type not equals an image tag or figure tag, we just add the class
  25. * to trigger the animation / load.
  26. */
  27. if (this.type !== 'IMG' && this.type !== 'FIGURE') {
  28. this.item.classList.add(this.className);
  29. return ;
  30. }
  31.  
  32. /**
  33. * If everthing passed, create new image Instance;
  34. */
  35. this.createImage();
  36. };
  37.  
  38. createImage() {
  39. this.image = new Image();
  40.  
  41. this.image.src = this.source;
  42.  
  43. this.image.onload = () => {
  44.  
  45. if (this.type === 'IMG') {
  46. this.item.src = this.source;
  47. } else {
  48. this.item.style.backgroundImage = `url(${this.source})`;
  49. }
  50.  
  51. this.item.classList.add(this.className);
  52. };
  53.  
  54. this.image.onerror = (error) => {
  55. throw Error(error);
  56. }
  57. }
  58.  
  59. setSource() {
  60. if (window.innerWidth < 768) { this.mobile = true; };
  61.  
  62. if (this.mobile && this.item.dataset.mobileSrc !== undefined) {
  63. this.source = this.item.dataset.mobileSrc
  64.  
  65. return this.item.dataset.mobileSrc;
  66. };
  67.  
  68. return this.item.dataset.src;
  69. }
  70.  
  71. }
Add Comment
Please, Sign In to add comment