Skip to content

Instantly share code, notes, and snippets.

@kanian
Created April 7, 2016 11:12
Show Gist options
  • Save kanian/b85f798a3a0a807c7e0f9b69bb337a3e to your computer and use it in GitHub Desktop.
Save kanian/b85f798a3a0a807c7e0f9b69bb337a3e to your computer and use it in GitHub Desktop.
Full Background Slider
.background-slider {
position: absolute;
top:0;
left:0;
z-index: -1;
height:100%;
width:100%;
background-size: cover;
background-position: center;
}
$(document).ready(function () {
(function changeBg() {
var img_array = ["http://upload.wikimedia.org/wikipedia/commons/thumb/c/c2/Still_nature_-_Museu_Calouste_Gulbenkian.JPG/1280px-Still_nature_-_Museu_Calouste_Gulbenkian.JPG",
"http://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Snow_covered_hillside_with_small_evergreens.jpg/1280px-Snow_covered_hillside_with_small_evergreens.jpg",
"http://upload.wikimedia.org/wikipedia/commons/thumb/4/48/Uvas.jpg/1280px-Uvas.jpg"
],
_nxtIndex = 0,
_curIndex = 0,
interval = 15000;
function nextIndex(){ _nxtIndex = ( _nxtIndex + 1) % img_array.length; return _nxtIndex;};
function shiftIndexes(){
_curIndex = _nxtIndex;
nextIndex();
}
function assignBackgrounds(){
for (var i=0; i<img_array.length;i++){
$('#background-slide'+i).css('backgroundImage', function () {
return 'url(' + img_array[i] + ')';
});
if(i==0){
$('#background-slide'+i).css('opacity', 1);
}
else{
$('#background-slide'+i).css('opacity', 0);
}
}
}
function startBackgroundOpacityToggle() {
//console.log("in startBackgroundOpacityToggle. _curIndex = "+_curIndex);
elem = $('#background-slide'+_curIndex);
elem.animate({
opacity: (elem.css('opacity')==0) ? 1 : 0
}, {
duration: 5000,
start: finishBackgroundOpacityToggle
}); };
function finishBackgroundOpacityToggle (){
//console.log("in finishBackgroundOpacity. _nxtIndex = "+_nxtIndex);
elem = $('#background-slide'+_nxtIndex);
elem.animate({
opacity: (elem.css('opacity')==0) ? 1 : 0
}, {
duration: 5000,
complete: runSlider
});
};
function runSlider(){
shiftIndexes();
setTimeout(startBackgroundOpacityToggle,interval);
}
assignBackgrounds();
runSlider();
})();
});
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="BackgroundSlider.css"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script language="javascript" type="text/javascript" src="BackgroundSlider.js"></script>
</head>
<body>
<div id="background-slide1" class="background-slider"></div>
<div id="background-slide2" class="background-slider"></div>
<div id="background-slide0" class="background-slider"></div>
</body>
</html>
@kanian
Copy link
Author

kanian commented Apr 7, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment