css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div class="container">

  <h1>XKCD Comics</h1>
  
  <form id="comic-form" class="form-inline">
    <div class="form-group">
      <input type="number"
             id="comic-number"
             class="form-control mr-3"
             placeholder="comic number"
             disabled required>
    </div>
    <button type="submit"
            class="btn btn-secondary mr-3"
            disabled>get comic by number</button>
  </form>
  
  <div id="comic-display">
    <h2 id="comic-title">Loading ...</h2>
    <div id="comic-controls">
      <button id="comic-control-prev"
              class="btn btn-secondary"
              disabled>
        &laquo; Prev
      </button>
      <button id="comic-control-random"
              class="btn btn-secondary"
              disabled>
        Random
      </button>
      <button id="comic-control-next"
              class="btn btn-secondary"
              disabled>
        Next &raquo;
      </button>
    </div><!-- /comic-controls -->
    
    <img id="comic-image">
    
    <div id="comic-date">
    </div><!-- /comic-date -->
  </div><!-- /comic-display -->
  
</div><!-- /container -->
            
          
!
            
              body {
  padding-top: 1.5rem;
}

#comic-display {
  display: none;
  margin-top: 2rem;
  width: 500px;
  text-align: center;
}

#comic-image {
  margin-top: 2rem;
  max-width: 100%;
}

#comic-date {
  font-size: 1.25rem;
  color: #555;
  margin: 1rem 0;
}
            
          
!
            
              class InvalidArgumentException {
  constructor(argument, value, message) {
    this.name = 'InvalidArgumentException';
    this.argument = argument;
    this.value = value;
    this.message = `Invalid argument ${ argument }`;
    
    if (typeof message !== 'undefined') {
      this.message = message;
    }
  }
}

class XkcdComics {
  constructor() {
    this.currentComicNumber = 0;
    this.currentComic = {};
    this.latestComicNumber = 0;
    this.latestComic = {};
    
    this.apiBaseUrl = 'https://xkcd.com';
    this.apiDataFormat = 'info.0.json';
    
    this.addCorsHeader();
  }
  
  addCorsHeader() {
    jQuery.ajaxPrefilter(function(options) {
      if (options.crossDomain && jQuery.support.cors) {
          options.url = 'https://cors-anywhere.herokuapp.com/' + options.url;
      }
    });
  }
  
  getLatestComic(callback) {
    if (!(callback instanceof Function)) {
      throw new InvalidArgumentException(
        'callback',
        callback,
        'The "callback" parameter has to be a function.'
      );
    }
    
    if (Object.keys(this.latestComic).length > 0) {
      callback(this.latestComic);
      return;
    }
    
    const apiUrl = `${ this.apiBaseUrl }/${ this.apiDataFormat }`;
    
    $.getJSON(apiUrl)
      .done((data) => {
        if (typeof data !== 'undefined'
            && typeof data !== 'null'
            && data.hasOwnProperty('num')
            && data.hasOwnProperty('img')) {
          this.latestComicNumber = data.num;
          this.latestComic = data;
          callback(data);
          return;
        } else {
          callback({
            "error": 500,
            "message": "Retrieved invalid data from the API."
          });
          return ;
        }
      })
      .fail((response) => {
        callback({
          "error": response.status,
          "message": response.statusText
        });
      });
  }
  
  getComicByRandom(callback) {
    if (!(callback instanceof Function)) {
      throw new InvalidArgumentException(
        'callback',
        callback,
        'The "callback" parameter has to be a function.'
      );
    }
    
    this.getLatestComic((data) => {
      this.latestComicNumber = data.num;
      const comicNumber = this.getRandomInt(1, this.latestComicNumber);
      
      this.getComicByNumber(comicNumber, (data) => {
        callback(data);
        return;
      });
    });
  }
  
  getComicByNumber(number, callback) {
    if (typeof number != 'number') {
      throw new InvalidArgumentException(
        'number',
        number,
        'Empty or missing parameter "number".'
      );
    }
    
    if (!(callback instanceof Function)) {
      throw new InvalidArgumentException(
        'callback',
        callback,
        'The "callback" parameter has to be a function.'
      );
    }
    
    const apiUrl = `${ this.apiBaseUrl }/${ number }/${ this.apiDataFormat }`;
    
    $.getJSON(apiUrl)
      .done((data) => {
        if (typeof data !== 'undefined'
            && typeof data !== 'null'
            && data.hasOwnProperty('num')
            && data.hasOwnProperty('img')) {
          callback(data);
          return;
        } else {
          callback({
            "error": 500,
            "message": "Retrieved invalid data from the API."
          });
          return ;
        }
      })
      .fail((response) => {
        callback({
          "error": response.status,
          "message": response.statusText
        });
      });
  }
  
  getRandomInt(min, max) {
    if (typeof min !== 'number') {
      throw new InvalidArgumentException(
        'min',
        min,
        'The "min" parameter has to be a number.'
      );
    }
    
    if (typeof max !== 'number') {
      throw new InvalidArgumentException(
        'max',
        max,
        'The "max" parameter has to be a number.'
      );
    }
    
    min = Math.ceil(min);
    max = Math.floor(max);
    
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
}

class DevComics {
  constructor() {
    this.Xkcd = new XkcdComics();
    this.currentComicNumber = 0;
    this.latestComicNumber = 0;
    this.currentComic = null;
    
    this.elements = {
      "form": $('#comic-form'),
      "display": $('#comic-display'),
      "title": $('#comic-title'),
      "number": $('#comic-number'),
      "controls": {
        "prev": $('#comic-control-prev'),
        "random": $('#comic-control-random'),
        "next": $('#comic-control-next')
      },
      "image": $('#comic-image'),
      "date": $('#comic-date')
    };
    
    this.init();
  }
  
  init() {
    this.Xkcd.getLatestComic((data) => {
      if (data !== null
          && data.hasOwnProperty('error') === false) {
        this.latestComicNumber = data.num;
        this.currentComicNumber = data.num;
        this.currentComic = data;
        
        this.registerEventHandler();
        this.showComic();
      } else {
        this.showError('Failed during initilization! Please try again later.');
      }
    });
  }
  
  registerEventHandler() {
    // register search by comic number
    this.elements.form.on('submit', (e) => {
      e.preventDefault();
      
      const number = this.elements.number.val().trim();
      
      if (number.match(/[^\d]/) !== null) {
        this.showError('Please insert a valid number!');
        return;
      }
      
      this.getComicByNumber(
        this.elements.number.val().trim()
      );
    })
    
    // enable form elements
    this.elements.form.find('[disabled]').removeAttr('disabled');
    this.elements.controls.prev.removeAttr('disabled');
    this.elements.controls.random.removeAttr('disabled');
    
    // register comic controls
    this.elements.controls.prev.on('click', (e) => {
      e.preventDefault();
      
      if (typeof $(e.target).attr('disabled') === 'undefined') {
        this.getComicByNumber(this.currentComicNumber - 1);
      }
    })
    
    this.elements.controls.random.on('click', (e) => {
      e.preventDefault();
      this.getRandomComic();
    })
    
    this.elements.controls.next.on('click', (e) => {
      e.preventDefault();

      if (typeof $(e.target).attr('disabled') === 'undefined') {
        this.getComicByNumber(this.currentComicNumber + 1);
      }
    })
  }
  
  getComicByNumber(number) {
    number = parseInt(number, 10);
    
    this.Xkcd.getComicByNumber(number, (data) => {
      if (data.hasOwnProperty('error')) {
        let message = '';
        
        if (data.error === 404) {
          message = 'The comic number is invalid. Please try again.';
        } else {
          message = 'We had problems loading the comic data. Please try again later.'
        }
        
        this.showError(message);
      } else {
        this.currentComic = data;
        this.currentComicNumber = data.num;
        this.showComic();
      }
    });
  }
  
  getRandomComic() {
    this.Xkcd.getComicByRandom((data) => {
      if (data.hasOwnProperty('error')) {
        this.showError('We had problems loading the comic data. Please try again later.');
      } else {
        this.currentComic = data;
        this.currentComicNumber = data.num;
        this.showComic();
      }
    });
  }
  
  showComic() {
    $('.alert-danger').remove();
    this.elements.title.text(this.currentComic.title);
    this.elements.image.attr('src', this.currentComic.img);
    this.elements.date.text(`
      ${ this.currentComic.year } - ${ this.currentComic.month } - ${ this.currentComic.day }
    `);
    
    // Enable / disable previous button
    this.updateDisabledState(
      this.elements.controls.prev,
      (this.currentComicNumber <= 1)
    );
    
    // Enable / disable next button
    this.updateDisabledState(
      this.elements.controls.next,
      (this.currentComicNumber >= this.latestComicNumber)
    );
    
    this.elements.display.fadeIn('fast');
  }
  
  updateDisabledState(element, disabled) {
    if (disabled) {
      element.attr('disabled', 'disabled');
    } else {
      element.removeAttr('disabled');
    }
  }
  
  showError(message) {
    const errorElement = this.elements.form.find('.error-message');
    
    if (errorElement.length === 0) {
      this.elements.form.before(`
        <div class="alert alert-danger error-message">${ message }</div>
      `);  
    } else {
      errorElement.text(message);
    }
  }
}

const comics = new DevComics();
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console