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 id="joke-container">
  <h1>Dad Jokes</h1>

  <form id="joke-form" class="form-inline">
    <div class="form-group">
      <input type="text"
             id="joke-number"
             class="form-control mr-3"
             placeholder="joke id"
             required>
    </div>
    <button type="submit"
            class="btn btn-primary mr-3 mt-1"
            >get joke by ID</button>
  </form>

  <div id="joke-display">
    <div id="joke-controls">
      <button id="joke-control-prev"
              class="btn btn-primary" disabled="disabled"
              >
        &laquo; Prev
      </button>
      <button id="joke-control-random"
              class="btn btn-primary"
              >
        Random
      </button>
      <button id="joke-control-next"
              class="btn btn-primary" disabled="disabled"
              >
        Next &raquo;
      </button>
    </div><!-- /joke-controls -->

    <div id="joke-text" class="hidden">
    </div>
    <div id="joke-loading">
      <i class="fa fa-spin fa-spinner"></i>
      &nbsp; Loading
    </div>
    <div class="alert alert-danger my-3 hidden" id="error-text" role="alert">
    </div>
  </div><!-- /joke-display -->
</div><!-- /joke-container -->
            
          
!
            
              body {
  padding: 1.5rem;
  text-align: center;
}

#joke-container {
  max-width: 500px;
  margin: 0 auto;
}

#joke-display {
  margin-top: 2rem;
  text-align: center;
}

#joke-date {
  font-size: 1.25rem;
  color: #555;
  margin: 1rem 0;
}

#joke-text,
#joke-loading {
  margin-top: 2rem;
  font-size: 1.75rem;
}

.hidden {
  display: none;
}
            
          
!
            
              class InvalidArgumentException {
  constructor (argument, value, message) {
    this.name = 'InvalidArgumentException'
    this.argument = argument
    this.value = value
    
    if (typeof message !== 'undefined') {
      this.message = message
    } else {
      this.message = `Invalid argument ${argument} with value: ${value}.`;
    }
  }
  
  getArgument () {
    return this.argument
  }
  
  getValue () {
    return this.value
  }
    
  getMessage () {
    return this.message
  }
}

class DadJokeApi {
  constructor () {
    this.apiUrl = 'https://icanhazdadjoke.com'
    this.id = null
    this.count = null
    this.cache = {}
  }
  
  /**
   * Retrieves the count of jokes from the API and calls the given
   * callback with the count as first parameter. If the API call
   * wasn't successfull the count is NULL.
   */
  getCount (callback) {
    if (!(callback instanceof Function)) {
      throw new InvalidArgumentException('callback', callback, 'The parameter "callback" has to be a function!')
    }
    
    if (this.count !== null) {
      callback(this.count)
      return
    }
    
    $.getJSON(
      `${this.apiUrl}/search`,
      {
        'limit': 1
      }
    )
      // HTTP Status == 200
      .done((data) => {
        if (data.status === 200 && data.hasOwnProperty('total_jokes')) {
          this.count = data.total_jokes
          callback(this.count)
        } else {
          callback(null)
        }
      })
      // HTTP Status != 200
      .fail((data) => {
        callback(null)
      })
  }

  /**
   * Retrieves a joke by it's ID.
   */
  getJokeById (id, callback) {
    if (!(callback instanceof Function)) {
      throw new InvalidArgumentException('callback', callback, 'The parameter "callback" has to be a function!')
    }
    
    if (this.cache.hasOwnProperty(id)) {
      callback(this.cache[id])
      return
    }
    
    $.getJSON(
      `${this.apiUrl}/j/${id}`
    )
      // HTTP Status == 200
      .done((data) => {
        if (data.status === 200 && data.hasOwnProperty('joke')) {
          this.cache[id] = data
          callback(this.cache[id])
        } else {
          callback(null)
        }
      })
      // HTTP Status != 200
      .fail((data) => {
        callback(null)
      })
  }
  
  getOneByOne(page, callback) {
    $.getJSON(
      `${this.apiUrl}/search`,
      {
        'limit': 1,
        'page': page
      }
    )
      // HTTP Status == 200
      .done((data) => {
        if (data.status === 200 && data.hasOwnProperty('results')) {
          let previous = null
          let next = null;
            
          if (data.previous_page !== page) {
            previous = data.previous_page;
          }
          
          if (data.next_page !== page) {
            next = data.next_page;
          }
          
          callback({
            'joke': data.results[0].joke,            
            'id': data.results[0].id,
            'current': page,
            'previous': previous,
            'next': next,
            'total': data.total_pages
          })
        } else {
          callback(null)
        }
      })
      // HTTP Status != 200
      .fail((data) => {
        callback(null)
      })
  }
}

class DadJokeForm {
  constructor() {
    this.elements = {
      'form': $('#joke-form'),
      'jokeNumber': $('#joke-number'),
      'controls': {
        'prev': $('#joke-control-prev'),
        'random': $('#joke-control-random'),
        'next': $('#joke-control-next')
      },
      'text': $('#joke-text'),
      'errorText': $('#error-text'),
      'loading': $('#joke-loading')
    }
    
    this.DadJokes = new DadJokeApi()
    this.page = 1;
    this.totalPages = null
    this.prev = null
    this.next = null
  }
  
  init() {
    this.registerEvents();

    this.DadJokes.getOneByOne(this.page, (data) => {
        console.log(data)

        if (data === null) {
          this.showError('We could not load a Joke from the API. Please try again later.')
        } else {
          this.next = data.next
          this.prev = data.previous
          this.totalPages = data.total
          this.showJoke(data)
        }   
    })
  }
  
  registerEvents() {
    this.elements.form.submit((e) => {
      e.preventDefault()
      const jokeId = this.elements.jokeNumber.val().trim();
      
      this.DadJokes.getJokeById(jokeId, (data) => {        
        if (data === null) {
          this.showError('Unknown Joke ID')
        } else {
          this.showJoke(data)
        }
      })
    })
    
    this.elements.controls.prev.click((e) => {
      e.preventDefault()
        
      if (this.prev !== null && this.next !== null) {
          this.loadPage(this.prev)
      }
    })

    this.elements.controls.next.click((e) => {
      e.preventDefault()

      if (this.next !== null) {
        this.elements.controls.prev.removeAttr( 'disabled' )
        this.loadPage(this.next);
      }
    })
    
    this.elements.controls.random.click((e) => {
      e.preventDefault()
      this.elements.controls.next.removeAttr( 'disabled' )
      this.elements.controls.prev.removeAttr( 'disabled' )
      this.loadRandom()
    })
  }
  
  loadPage(page, callback) {
    this.DadJokes.getOneByOne(page, (data) => {
      if (data === null) {
        this.showError('We could not load a Joke from the API. Please try again later.')
      } else {
        this.next = data.next
        this.prev = data.previous
        this.showJoke(data)
        
        this.changeDisabledState(
          this.elements.controls.prev,
          (this.prev === null)
        )
        
        this.changeDisabledState(
          this.elements.controls.next,
          (this.next === null)
        )
      }   
    })  
  }
  
  loadRandom() {
    const page = this.getRandomIntInclusive(1, this.totalPages)
    this.loadPage(page)
  }
  
  showJoke(data) {
    this.elements.text.html(data.joke + '<br/>' + 'joke ID : ' + data.id)
    this.elements.loading.addClass('hidden')
    this.elements.text.removeClass('hidden')
    this.elements.errorText.addClass('hidden')
  }
  
  showError(message) {
    this.elements.text.addClass('hidden')
    this.elements.loading.addClass('hidden')
    
    this.elements.errorText.html(message)
    this.elements.errorText.removeClass('hidden')
  }
  
  getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
}

const jokeForm = new DadJokeForm();
jokeForm.init();
            
          
!
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