It shows up one image every 5 seconds (one per post). You can go forward and backward using cursor arrows (click inside first to be in context).
Live demo no longer available. JavaScript HTML CSSconst index = (() => {
const api = 'https://api.tumblr.com/v2/blog/'
const api_key = 'api_key=fuiKNFp9vQFvjLNvx4sUwti4Yb5yGutBN4Xh10LXZhhRKjWlV4'
/**
Checks if an url is valid or not
@param str 'string' URL
@return boolean
*/
function valid_url(str) {
const pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
if(!pattern.test(str)) {
alert('Please enter a valid URL.')
return false
} else return true
}
/**
Start showing posts' images
@param posts [array]
*/
function start(posts) {
const timeout = 5000 // 5s
let $container_ = document.querySelector('#container')
let next_timer_ = setTimeout(go, 0)
let i = -1
/**
Go back and forth
@param direction 'string' previous to go backward, anything else to go forward
*/
function go(direction) {
clearTimeout(next_timer_)
if (direction && direction == 'previous') {
// If we are at the begginng, it doesn't do anything
if (i < 1) return;
i--
} else i++
console.log(i)
// Finished when there are no more posts
if (i >= posts.length) return;
console.log(posts[i].photos[0].original_size.url)
// If there are no images, next post
if (!posts[i].photos.length) go()
// Load image
$container_.innerHTML =
'<img src="' + posts[i].photos[0].original_size.url + '">'
// Next image X seconds after the last image has loaded
const $img = document.querySelector('img')
if ($img.complete) {
next_timer_ = setTimeout(go, 5000)
} else {
$img.addEventListener('load', () => {
next_timer_ = setTimeout(go, timeout)
})
$img.addEventListener('error', () => alert('error'))
}
}
// Key bindings
document.addEventListener('keyup', e => {
console.log(e)
if (e.key == 'ArrowRight') go('next')
else if (e.key == 'ArrowLeft') go('previous')
})
}
function load(url) {
const api_url = api + url.split('//')[1] + '/posts/photo?' + api_key
if (!valid_url(url)) return;
// We have to use deprecated insecure jsonp ¬¬
$.ajax({
url: api_url,
dataType: "jsonp",
jsonp: "jsonp",
success: function(data) {
if (data.response.posts.length)
start(data.response.posts)
}
})
}
return {
load: load
}
})()
index.load('http://derekg.org') // without slash at the end
<div id="container"></div>
body {
background: black;
}
img {
width: 100%;
height: auto;
}
You could extend this example adding up and down cursor arrows to switch between different tumblrs.