I am currently using jQuery to dynamically change the background image of a web page. Right now, I have implemented two separate buttons that toggle between Image A and Image B. By default, Image A is displayed on the page.
My goal is to enhance this functionality by implementing a single button that switches the image and changes its label accordingly when clicked.
For Image A, the button should display "Zoom In". When clicked, Image B should replace Image A in the background, and the button text should change to "Zoom Out".
I hope that explanation makes sense!
jQuery(document).ready(function() {
var images = ['image-A.gif'];
var url = images[Math.floor(Math.random() * images.length)];
var img = new Image();
img.onload = function(){
jQuery('#test').css({'background-image': 'url('+url+')','background-size' : 'cover', 'background-position' : '50px 0'});
jQuery('#test').fadeIn(1000);
}
img.src = url;
});
jQuery(function(){
jQuery("#aChange").click(function(){
jQuery("#test").css("background-image", "url(image-B.gif)");
jQuery("#test").css("background-position", "50px -100px");
jQuery("#test").css("background-repeat", "no-repeat");
jQuery("#test").css("background-size", "cover");
return false;
});
jQuery("#bChange").click(function(){
jQuery("#test").css("background-image", "url(image-A.gif)");
jQuery("#test").css("background-position", "50px 0");
jQuery("#test").css("background-repeat", "no-repeat");
jQuery("#test").css("background-size", "cover");
return false;
});
});