Pen Settings

HTML

CSS

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

JavaScript

Babel includes JSX processing.

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

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <main>
  <header class="header">
    <h1 class="header__title">Movie Comparison</h1>
  </header>
  
  <div class="columns">
    <!--   Left side movie   -->
    <section class="column">
      <div id="left-autocomplete"></div>
      <div id="left-details"></div>
    </section>
    
    <!--   Right side movie   -->
    <section class="column">
      <div id="right-autocomplete"></div>
      <div id="right-details"></div>
    </section>
  </div>

</main>
              
            
!

CSS

              
                $primary-color: #1D253D;
$primary-color-light: #6478B4;
$text-color: #fff;
$success-color: #19CF7F;
$negative-color: #F30C81;

// Default styling
* {
  box-sizing: border-box;
}

p {
  margin: 0;
}

body {
  margin: 0;
  padding: 0;
  
  color: $text-color;
  background-color: $primary-color;
  
  font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif;
}

.columns {
  display: flex;
  max-width: 900px;
  margin: 0 auto;
  
  .column {
    flex: 0 0 50%;
    padding: 0 1rem;
  }
}

// Header of the app
.header {
  padding: 2rem 1rem;

  text-align: center;

  &__title {
    margin: 0;
  
    color: $primary-color-light;
    font-size: 20px;
    letter-spacing: 2px;
  }
}

// Autocomplete
.autocomplete {
  &__label {
    display: block;
  }
  
  &__input {
    display: block;
    width: 100%;
    margin-top: 0.5rem;
    padding: 1rem 1.25rem;
    
    border: 0;
    border-radius: 4px;
    
    color: $text-color;
    background-color: lighten($primary-color, 10%);
    outline: 0;
    
    font-size: 18px;
    transition: all .15s ease-out;
    
    &:focus {
      box-shadow: 0 0 0 3px rgba($primary-color-light, 0.75);
    }
    
    &:hover {
      background-color: lighten($primary-color, 15%);
    }
  }
  
  .dropdown__menu__item {
    img {
      width: 30px;
      margin-right: 1rem;
    }
  }
}

// Generic dropdown
.dropdown {
  position: relative;
  vertical-align: top;

  display: inline-flex; 
  width: 100%;

  &--active {
    .dropdown__menu {
      display: block;
    }
  }
      
  &__menu {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 20;
    overflow-y: scroll;

    display: none;
    width: 100%;
    min-width: 12rem;
    max-height: 300px;
    padding: 0.5rem 0;
    
    border-radius: 4px;
    background-color: white;
    
    &__link {
      display: flex;
      align-items: center;
      padding: 0.5rem 1rem;
      
      color: $primary-color;
      cursor: pointer;
      
      transition: all 0.15s ease-out;
      
      &:hover,
      &:focus {
        background-color: #eee;
      }
    }
  }
}

// Movie summary
.media {
  display: block;
  margin-bottom: 2rem;
  
  &__title {
    text-align: center;
  }
  
  &__info {
    height: 175px;
    overflow-y: auto;
  }
  
  &__figure {
    width: 100%;
    margin: 0;
    padding: 1rem;
    border-radius: 10px;
    
    background-color: lighten($primary-color, 5%);
    
    img {
      display: block;
      margin: 0 auto;
      height: 200px;
      
      border-radius: 10px;
    }
  }
}

.compare {
  padding: 1.5rem 1rem;
  margin-bottom: 1rem;

  border-radius: 10px;
  color: $primary-color;
  
  &--winner {
    background-color: $success-color;
  }
  
  &--loser {
    background-color: $negative-color;
  }
  
  &__title {
    margin-bottom: 0.5rem;
    
    font-weight: 700;
    font-size: 24px;
  }
  
  &__subtitle {
    .compare--winner & {
      color: darken($success-color, 20%);
    }
    
    .compare--loser & {
      color: darken($negative-color, 20%);
    }
  }
}
              
            
!

JS

              
                /**

  If the calls fail, it might be because the api limit has been reached.
  It's able to do 1.000 calls/day, search for 89c28a6e and replace it with your own (you can get one for free at http://omdbapi.com/)

*/

// Some default classes and variables used in the app
const DEFAULTS = {
  DROPDOWN_CLASS_ITEM: "dropdown__menu__item",
  DROPDOWN_CLASS_LINK: "dropdown__menu__link",
  DROPDOWN_CLASS_ACTIVE: "dropdown--active",
  COMPARE_CLASS_WINNER: "compare--winner",
  COMPARE_CLASS_LOSER: "compare--loser",
  API_BASE_URL: "https://www.omdbapi.com",
  API_KEY: "89c28a6e"
};

// Reusable Autocomplete Class
class Autocomplete {
  constructor(config) {
    ({
      root: this.root,
      optionTemplate: this.optionTemplate,
      onOptionSelect: this.onOptionSelect,
      inputValue: this.inputValue,
      fetchData: this.fetchData
    } = config);

    this.createRootTemplate(this.root);

    this.input = this.root.querySelector(".autocomplete__input");
    this.dropdown = this.root.querySelector(".autocomplete__dropdown");
    this.resultsWrapper = this.root.querySelector(".results");

    this.initListeners();
  }

  initListeners() {
    this.input.addEventListener("input", this.debounce(ev => this.onInput(ev), 500));

    document.addEventListener("click", ev => {
      if (!this.root.contains(ev.target)) {
        this.dropdown.classList.remove(DEFAULTS.DROPDOWN_CLASS_ACTIVE);
      }
    });
  }

  async onInput(ev) {
    const items = await this.fetchData(ev[0].target.value);

    if (!items.length) {
      this.dropdown.classList.remove(DEFAULTS.DROPDOWN_CLASS_ACTIVE);
      return;
    }

    this.resultsWrapper.innerHTML = "";
    this.dropdown.classList.add(DEFAULTS.DROPDOWN_CLASS_ACTIVE);

    for (const item of items) {
      const option = document.createElement("li");
      option.classList.add(DEFAULTS.DROPDOWN_CLASS_ITEM);

      const link = document.createElement("a");
      link.classList.add(DEFAULTS.DROPDOWN_CLASS_LINK);
      link.innerHTML = this.optionTemplate(item);

      option.appendChild(link);
      option.addEventListener("click", () => {
        this.dropdown.classList.remove(DEFAULTS.DROPDOWN_CLASS_ACTIVE);
        this.input.value = this.inputValue(item);
        this.onOptionSelect(item);
      });

      this.resultsWrapper.appendChild(option);
    }
  }

  debounce(callback, delay = 1000) {
    return (...args) => {
      if (this.timeoutId) clearTimeout(this.timeoutId);
  
      this.timeoutId = setTimeout(() => {
        callback.call(null, args);
      }, delay);
    };
  }

  createRootTemplate(el) {
    el.innerHTML = `
      <div class="autocomplete">
        <label class="autocomplete__label">
          Search
          <input class="autocomplete__input" />
        </label>

        <div class="autocomplete__dropdown dropdown">
          <ul class="dropdown__menu results">
          </ul>
        </div>
      </div>
    `;
  }
}

// Class to compare movies
class MovieComparison {
  constructor() {
    this.init();
  }

  movieAutocompleteConfig() {
    return {
      optionTemplate(movie) {
        const imgSrc = movie.Poster === "N/A" ? "" : movie.Poster;
        return `
        <img src="${imgSrc}" />
        ${movie.Title} (${movie.Year})
      `;
      },
      inputValue(movie) {
        return movie.Title;
      },
      async fetchData(searchTerm) {
        const response = await axios.get(DEFAULTS.API_BASE_URL, {
          params: {
            apikey: DEFAULTS.API_KEY, // This api can only be used 1000 times a day
            s: searchTerm
          }
        });

        return response.data.Error ? [] : response.data.Search;
      }
    };
  }

  init() {
    new Autocomplete({
      ...this.movieAutocompleteConfig(),
      root: document.querySelector("#left-autocomplete"),
      onOptionSelect: movie => {
        this.onMovieSelect(
          movie,
          document.querySelector("#left-details"),
          "left"
        );
      }
    });

    new Autocomplete({
      ...this.movieAutocompleteConfig(),
      root: document.querySelector("#right-autocomplete"),
      onOptionSelect: movie => {
        this.onMovieSelect(
          movie,
          document.querySelector("#right-details"),
          "right"
        );
      }
    });
  }

  async onMovieSelect(movie, summaryElement, side) {
    const response = await axios.get(DEFAULTS.API_BASE_URL, {
      params: {
        apikey: DEFAULTS.API_KEY,
        i: movie.imdbID
      }
    });

    summaryElement.innerHTML = this.movieTemplate(response.data);

    if (side === "left") {
      this.leftMovie = response.data;
    } else {
      this.rightMovie = response.data;
    }

    if (this.leftMovie && this.rightMovie) {
      this.runComparison();
    }
  }

  runComparison() {
    const leftSideStats = document.querySelectorAll("#left-details .compare");
    const rightSideStats = document.querySelectorAll("#right-details .compare");

    console.log(rightSideStats);

    for (const [i, leftStat] of leftSideStats.entries()) {
      const rightStat = rightSideStats[i];

      const leftSideValue = parseInt(leftStat.dataset.value);
      const rightStatValue = parseInt(rightStat.dataset.value);

      if (rightStatValue > leftSideValue) {
        leftStat.classList.remove(DEFAULTS.COMPARE_CLASS_WINNER);
        leftStat.classList.add(DEFAULTS.COMPARE_CLASS_LOSER);
      } else {
        rightStat.classList.remove(DEFAULTS.COMPARE_CLASS_WINNER);
        rightStat.classList.add(DEFAULTS.COMPARE_CLASS_LOSER);
      }
    }
  }

  movieTemplate(detail) {
    const boxOffice = parseInt(
      detail.BoxOffice.replace(/\$/g, "").replace(/,/g, "")
    );
    const metascore = parseInt(detail.Metascore);
    const imdbScore = parseFloat(detail.imdbRating);
    const imdbVotes = parseInt(detail.imdbVotes.replace(/,/g, ""));
    const awardsCount = detail.Awards.split(" ")
      .filter(Number)
      .reduce((acc, cur) => acc + parseInt(cur), 0);

    return `
      <article class="media">
        <h1 class="media__title">${detail.Title}</h1>
        <figure class="media__figure">
            <img src="${detail.Poster}" />
        </figure>
  
        <div class="media__info">
          <h4>${detail.Genre}</h4>
          <p>${detail.Plot}</p>
        </div>
      </article>
  
      <article class="compare ${DEFAULTS.COMPARE_CLASS_WINNER}" data-value="${awardsCount}">
        <p class="compare__title">${detail.Awards}</p>
        <p class="compare__subtitle">Awards</p>
      </article>
  
      <article class="compare ${DEFAULTS.COMPARE_CLASS_WINNER}" data-value="${boxOffice}">
        <p class="compare__title">${detail.BoxOffice}</p>
        <p class="compare__subtitle">Box Office</p>
      </article>
  
      <article class="compare ${DEFAULTS.COMPARE_CLASS_WINNER}" data-value="${metascore}">
        <p class="compare__title">${detail.Metascore}</p>
        <p class="compare__subtitle">Metascore</p>
      </article>
  
      <article class="compare ${DEFAULTS.COMPARE_CLASS_WINNER}"" data-value="${imdbScore}">
        <p class="compare__title">${detail.imdbRating}</p>
        <p class="compare__subtitle">IMDB Rating</p>
      </article>
  
      <article class="compare ${DEFAULTS.COMPARE_CLASS_WINNER}"" data-value="${imdbVotes}">
        <p class="compare__title">${detail.imdbVotes}</p>
        <p class="compare__subtitle">IMDB Votes</p>
      </article>
    `;
  }
}

const comparison = new MovieComparison();

              
            
!
999px

Console