views:

122

answers:

1

Hi, I have a site where I randomize the background image using a php rotator script file. But I was thinking, is it possible to create a small preview gallery of each background image and make it so that when the user hovers over an image, the css background image of the site is changed on the fly? And when the user clicks on the image he wants, the image is permanently changed? The image URL would probably need to be saved in a database record btw.

How would I do this? First I'd need to create the gallery right. Perhaps I could do a "for each image in folder, display as stack panel" ? Making it so that based on the images in a said folder, the images are automatically published in the gallery?

Any ideas or thoughts on how I should do this? Base it on an existing gallery plugin perhaps?

+1  A: 

Assuming your images are in a div with a class of 'gallery'

​$(document).ready(function(){
    var originalBG = $('body').css('background');

    $('div.gallery img').hover(function(){
        // You could change this to include any other background options you need.
        $('body').css('background',"url('" + $(this).attr('src') + "')");
    },function(){
        $('body').css('background',originalBG);
    });

    $('div.gallery img').click(function(){
        originalBG = $('body').css('background');
        $.ajax({
            url: '/saveBG.php', // The url to your function to handle saving to the db
            data: originalBG,
            dataType:'Text',
            type: 'POST',  // Could also use GET if you prefer
            success: function(data) {
                // Just for testing purposes.
                alert('Background changed to: ' + data);
            }
        });
    });

});​
AdmSteck
I'm just gonna play around with this a bit :)Seems to be working almost :) There's something wrong with the url the code picks up. Using FireBug, I can see that the new background is "undefined".
Kenny Bones
Yeah, it's great. I did a few tweaks but it does the job! :) I was thinking if it is possible to actually fade in the background image as well, but it looks like that's a completely different task.
Kenny Bones
I believe the only way to get that to fade in or out would be to create some form of dummy div for the background. If you try to apply the jquery fadeTo effect to the body, everything fades, not just the background.
AdmSteck
I just did that and it works great! :) Figured it out myself as well, wow! :pAnyway, I don't fully understand that php url thingy there. Basically, in this click handler you do a callback function that does an ajax call to a php file? Do have an example of how that php file could look like?
Kenny Bones
AdmSteck