Skip to content

Instantly share code, notes, and snippets.

@EliCDavis
Last active March 7, 2016 22:16
Show Gist options
  • Save EliCDavis/cbc5f8c3d1b483b9ff8e to your computer and use it in GitHub Desktop.
Save EliCDavis/cbc5f8c3d1b483b9ff8e to your computer and use it in GitHub Desktop.
Easily pull a wallpaper from your favorite subreddits
/*
The MIT License (MIT)
Copyright (c) 2016 Eli C. Davis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
"use strict";
var subredditsToHit = ["AbandonedPorn", "EarthPorn", "wallpapers", "ArchitecturePorn", "RuralPorn"];
var subsHit = 0;
function getAllWallpapers(){
for(var i = 0; i < subredditsToHit.length; i ++){
makeHttpRequest("https://www.reddit.com/r/"+subredditsToHit[i]+".json",
function(){
subsHit ++;
if(subsHit === subredditsToHit.length){
setRndWallpaper();
}
},
function(data){
subsHit ++;
addValidWallpapers(data);
if(subsHit === subredditsToHit.length){
setRndWallpaper();
}
}
);
}
}
var collectedValidWallpapers = [];
var addValidWallpapers = function(data){
for(var i = 0; i < data.data.children.length; i ++){
if(data.data.children[i].data.domain === "i.imgur.com"){
if(data.data.children[i].data.ups > 20){
collectedValidWallpapers.push(data.data.children[i].data.url);
}
}
}
};
function setRndWallpaper(){
var chosenWallpaper = Math.floor((Math.random() * collectedValidWallpapers.length));
document.body.style.background = "url("+collectedValidWallpapers[chosenWallpaper]+") fixed 50% / cover";
}
function makeHttpRequest(url, errcb, succb){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var postData = JSON.parse(xmlhttp.responseText);
succb(postData);
} else {
if(xmlhttp.readyState === 4 && xmlhttp.status !== 200){
if(errcb !== null){
errcb();
}
}
}
};
xmlhttp.open("GET",
url, true);
xmlhttp.send();
}
getAllWallpapers();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment