Add ajax demo

pull/174/head
Glen Cheney 7 years ago
parent 68be2fe35f
commit 5ca1ca6ba0

@ -44,6 +44,11 @@
"slug": "shuffle-with-react",
"label": "Shuffle with React"
},
{
"url": "demos/2017-08-28-ajax",
"slug": "ajax",
"label": "Loading ajax content"
},
{
"external": true,
"url": "http://codepen.io/pen?template=qrjOpX",

@ -1,7 +1,7 @@
---
layout: default
title: Shuffle with React
description: TODO
description: An example using the React framework with Shuffle.
image: /demos/flexbox-grid.jpg
extraJS: [ "demos/react.js" ]
externalJS: ["https://unpkg.com/react@latest/dist/react.js", "https://unpkg.com/react-dom@latest/dist/react-dom.js", "https://unpkg.com/babel-standalone@6.15.0/babel.min.js"]
@ -54,7 +54,7 @@ prism: true
<div class="col-12@sm">
<h2>Shuffle with React</h2>
<p>And other view-based libraries like Vue and Preact.</p>
<p>The simplest way is to use <code>shuffleInstance.resetItems();</code> inside the <code>componentDidUpdate()</code> lifecycle method.</p>
<p>The simplest way is to use <code>shuffleInstance.resetItems();</code> inside the <code>componentDidUpdate()</code> lifecycle method.</p>
</div>
</div>
</div>

@ -0,0 +1,74 @@
---
layout: default
title: Loading ajax content
description: Fetch data from an api, then add it to Shuffle.
image: /demos/ajax.jpg
extraJS: ["demos/ajax.js"]
externalJS: ["https://unpkg.com/whatwg-fetch"]
prism: true
photoCredit: false
---
<style>
.person-item {
margin-top: 16px;
}
.person-item__inner {
display: flex;
text-align: center;
height: 100px;
}
.person-item__inner > span {
margin: auto;
color: white;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.55);
}
.load-more-wrapper {
margin: 20px 0;
}
</style>
<div class="container">
<div class="row">
<div class="col-12@sm">
<h2>Shuffle with <abbr title="asynchronous JavaScript and XML">Ajax</abbr> Content</h2>
<p>This demo builds off the <a href="{{ site.baseurl }}{% post_url 2013-06-19-adding-removing %}">adding and removing demo</a> to append new items after fetching them from an API and follows the same pattern:</p>
<ol>
<li>Insert the elements into the shuffle container element (in this case, <code>#grid</code>) however you like. You could use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML"><code>insertAdjacentHTML</code></a>, <code>jQuery.append</code>, or any other method of inserting new content.</li>
<li>Make an array of the newly added items.</li>
<li>Call <code>add(newItemsArray)</code> on your shuffle instance.</li>
</ol>
<p>The data comes from <a href="https://reqres.in" target="_blank" rel="noopener">https://reqres.in</a>.</p>
</div>
</div>
</div>
<div class="container">
<div id="grid" class="my-shuffle-container row">
<div class="col-3@xs col-3@sm my-sizer-element"></div>
</div>
<div class="row">
<div class="col-6@xs col-12@sm">
<div class="load-more-wrapper text-center">
<button class="btn" id="load-more-button">Load More</button>
</div>
</div>
</div>
</div>
<div class="container has-code-block">
<div class="row">
<div class="col-12@sm">
<h2>Source code for this demo</h2>
<p>Link to <a href="{{ site.baseurl }}/js/demos/ajax.js">demo source</a></p>
<div class="code-block">
<pre class="language-jsx" data-src="{{ site.baseurl }}/js/demos/ajax.js"></pre>
</div>
</div>
</div>
</div>

@ -61,6 +61,13 @@
&:focus.active {
box-shadow: inset 0 1px 2px rgba(0,0,0,.3), 0 0 0 2px rgba($gray20, 0.4);
}
&:disabled {
cursor: not-allowed;
opacity: 0.7;
color: $gray20;
background-color: rgba($gray20, 0);
}
}
$btn-variants: (
@ -94,6 +101,11 @@ $btn-variants: (
&:focus.active {
box-shadow: inset 0 1px 2px rgba(0,0,0,.3), 0 0 0 2px rgba($color, 0.4);
}
&:disabled {
color: $color;
background-color: rgba($color, 0);
}
}
}

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

@ -0,0 +1,106 @@
var Shuffle = window.Shuffle;
var currentPage = 1;
var totalPages;
var gridContainerElement = document.getElementById('grid');
var loadMoreButton = document.getElementById('load-more-button');
var shuffleInstance;
// Fetch first page of results from the API.
// You should probably polyfill `fetch` if you're going to copy this demo.
// https://github.com/github/fetch
fetch('https://reqres.in/api/users?page=' + currentPage)
.then(function (response) {
return response.json();
})
.then(function (response) {
// Store the total number of pages so we know when to disable the "load more" button.
totalPages = response.total_pages;
// Create and insert the markup.
var markup = getItemMarkup(response.data);
appendMarkupToGrid(markup);
// Add click listener to button to load the next page.
loadMoreButton.addEventListener('click', fetchNextPage);
// Initialize Shuffle now that there are items.
shuffleInstance = new Shuffle(gridContainerElement, {
itemSelector: '.js-item',
sizer: '.my-sizer-element',
});
});
function fetchNextPage() {
currentPage += 1;
fetch('https://reqres.in/api/users?page=' + currentPage)
.then(function (response) {
return response.json();
})
.then(function (response) {
// Create and insert the markup.
var markup = getItemMarkup(response.data);
appendMarkupToGrid(markup);
// Check if there are any more pages to load.
if (currentPage === totalPages) {
replaceLoadMoreButton();
}
// Save the total number of new items returned from the API.
var itemsFromResponse = response.data.length;
// Get an array of elements that were just added to the grid above.
var allItemsInGrid = Array.from(gridContainerElement.children);
// Use negative beginning index to extract items from the end of the array.
var newItems = allItemsInGrid.slice(-itemsFromResponse);
// Notify the shuffle instance that new items were added.
shuffleInstance.add(newItems);
});
}
/**
* Convert an object to HTML markup for an item.
* @param {object} dataForSingleItem Data object.
* @return {string}
*/
function getMarkupFromData(dataForSingleItem) {
var name = dataForSingleItem.first_name + ' ' + dataForSingleItem.last_name;
// https://www.paulirish.com/2009/random-hex-color-code-snippets/
var randomColor = ('000000' + Math.random().toString(16).slice(2, 8)).slice(-6);
return [
'<div class="js-item col-3@xs col-3@sm person-item" data-id="' + dataForSingleItem.id + '">',
'<div class="person-item__inner" style="background-color:#' + randomColor + '">',
'<span>' + name + '</span>',
'</div>',
'</div>',
].join('');
}
/**
* Convert an array of item objects to HTML markup.
* @param {object[]} items Items array.
* @return {string}
*/
function getItemMarkup(items) {
return items.reduce(function (str, item) {
return str + getMarkupFromData(item);
}, '');
}
/**
* Append HTML markup to the main Shuffle element.
* @param {string} markup A string of HTML.
*/
function appendMarkupToGrid(markup) {
gridContainerElement.insertAdjacentHTML('beforeend', markup);
}
/**
* Remove the load more button so that the user cannot click it again.
*/
function replaceLoadMoreButton() {
var text = document.createTextNode('All users loaded');
var replacement = document.createElement('p');
replacement.appendChild(text);
loadMoreButton.parentNode.replaceChild(replacement, loadMoreButton);
}
Loading…
Cancel
Save