Thomas
Thomas

Reputation: 231

Replace url of background-image with the url of a clicked image with jQuery

When any image in an unordered list is clicked, I would like the url associated with the thumbnail to replace the background-image css value of a particular div. Say,

<ul>
  <li><a href="dog.jpg"><img src="dog_thumb.jpg" /></a></li>
  <li><a href="cat.jpg"><img src="cat_thumb.jpg" /></a></li>
</ul>
<div id="background" style="background-image: url('default.jpg')"></div>

When dog_thumb.jpg is clicked, the href attached to it gets put into the css of the div:

<div id="background" style="background-image: url('dog.jpg')"></div>

If cat_thumb.jpg was then clicked, its href would switch with the div's background-image value.

Obviously, I won't use inline styles for the final page. I know how to switch the src of a thumbnail with that of another image on the page or switch between whole classes but, I can't seem to be able to find a way to manipulate just one attribute of a single class. I would like to do it this way because switching the background-image is much easier than having a bunch of divs on top of each other with z-indexes.

Upvotes: 2

Views: 605

Answers (2)

keif
keif

Reputation: 573

You click the anchor, and you want that href to replace the #background? Based on your example:

// all links will work this way, based on your example
$('a').click(function(e){
    // replace the css background image with the one in the href
    // please note, this assumes the href is the absolute or relative URL to the image
    $('#background').css('backgroundImage', $(this).attr('href'));
    // stop the link from acting like a link
    e.preventDefault();
});

You could also take the img src ad strip the thumb from it and put it in to the #background, you could also put a series of classes in your CSS and add/remove the class name as necessary to change the background. (I would recommend "default" as a class to add the default image, versus leaving it inline).

JavaScript manipulation inline CSS should overwrite the default styling you have (so if default.jpg is tied to the ID, it should overwrite it).

Upvotes: 1

S L
S L

Reputation: 14318

   $('img').click(
        function (){
            $(this).parent('ul').next('div').css('background', $(this).attr('src'));
        }
   )

Also as @RichardNeilIlagan suggested,

   $('img').click(
        function (){
            $('div#background').css('background', $(this).attr('src'));
        }
   )

Upvotes: 1

Related Questions