HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
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.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<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>
$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%);
}
}
}
/**
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();
Also see: Tab Triggers