0

I will have a list of images (tiled background type) I would like to be able to click on an image and make it the background image for the entire body for display purposes. so far I have this:

$(document).ready(function(){       

    //var image = ???; what should be here?

    $('.img1').click(function(){
        $('#body').css('background-image', 'url(images/tiles/tile77.jpg'); //the image url cannot be one single url
        });   

    });   

my current row of images(just being used to get the script working. The images will be coming from a database later.

<div class="threecol"><img class="img1" src="images/tiles/tile39.jpg"></div>
<div class="threecol"><img class="img1" src="images/tiles/tile77.jpg"></div>
<div class="threecol"><img class="img1" src="images/tiles/tile47.jpg"></div>
<div class="threecol last"><img class="img1" src="images/tiles/tile33.jpg"></div>

The script works the way I have it, but I need the background image to be the image that I clicked on, not the static one I have here. I need it to work each time I click on an image.

I admit it, I am clueless as to how to get it to work time after time and also how to configure the script at .css(background-image, ?????) to be dynamic

Thanks for any advice

1 Answer 1

4

Grab the src attribute of the .img1 element you just fired the click event on and set that as the URL in your CSS modification to the body element:

$('.img1').click(function(){
    $('body').css('background-image', 'url(' + this.src + ')');
});

Also there should only ever be a single body element in your document, so no need to select it via an ID, just use $('body') instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, I see what you are saying. My body element is body id="body". That worked perfectly thank you very much. It didnt seem like it would be this easy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.