Create Website Background Image That Changes On A Click
I am wondering how to create a background image that will change when clicked. It's supposed to go through a sequence of images like this. Any clues how to make this?
Solution 1:
The jQuery Way
Here's a basic jQuery solution:
var images = [
'http://placekitten.com/500/500',
'http://placekitten.com/400/400',
'http://placekitten.com/750/750'
];
$(".changeBG").on("click", function(){
$("body").css("backgroundImage", function( o, v ) {
var backg = v.match( /\((.+)\)/ );
var index = $.inArray( ( backg ? backg[1] : "" ), images );
return"url('" + ( images[++index] || images[0] ) + "')";
});
});
Demo: http://jsbin.com/isubag/2/edit
The Pure JavaScript (almost) Way
That solution is pretty heavy on the jQuery, which will slow it down just a bit. You could go with a far more holistic approach. Unfortunately there is still the use of $.inArray
(though polyfills do exist), as native support for indexOf
on arrays isn't all that great.
var bg = {
images: [
'http://placekitten.com/500/500',
'http://placekitten.com/400/400',
'http://placekitten.com/750/750'
],
get: function () {
var match = document.body.style.backgroundImage.match( /\((.+)\)/ );
return match ? match[1] : "" ;
},
set: function ( url ) {
document.body.style.backgroundImage = "url('" + url + "')" ;
}
};
functionbgCycler () {
var index = $.inArray( bg.get(), bg.images );
bg.set( bg.images[++index] || bg.images[0] );
}
Post a Comment for "Create Website Background Image That Changes On A Click"