forrest
forrest

Reputation: 10982

How do I change the div background when I mouse over a picture?

I have a thumbnail image inside a div. I use another image as the background for the div so that it frames the thumbnail. I need to be able to change the position of the background image from bottom center to top center when I mouse over the thumbnail.

Here is the html:

<div class="image">
   <a class="zoom1" title="Sample title" href="images/xyz-large.jpg"><img src="images/portfolio-xyz.jpg" alt="XYZ Inc" /></a>
</div>

Here is the css:

div.image     { width: 314px; height: 231px; background: url(images/bg_portfolio-img.png) no-repeat bottom center; }
div.image img { position: relative; top: 8px; left: 8px; }

I would like to do this with just the css and it would be something like this:

div image a.zoom1:hover  { background-position: top center;}

However, that obviously doesn't work. I am open to a jQuery solution but I would require some assistance there as well.

Thanks in advance for the help!

Upvotes: 3

Views: 882

Answers (3)

Giles Van Gruisen
Giles Van Gruisen

Reputation: 961

Javascript is the easy way.

If you'd like to do it just with CSS, you could completely take out the extra div, and add the background image to the img and just give it padding. That way, you can just change the background-position on img:hover.

Upvotes: 1

Adam Kiss
Adam Kiss

Reputation: 11859

css solution

if your link (a) completely fills parent div, you can do

div.image:hover { background-position: center top; }
  • fills completely, because then there will be no difference in interactivity (unresponsive link, but changing bg if div is bigger than a)
  • unfortunately, that is no-no for IE6

jQuery solution

$(".image a").hover(function(){
  $(this).parent('.image').addClass('hover');
},function(){
  $(this).parent('.image').removeClass('hover');
});

and then in css

div.image { background-position: center bottom; }  //normal
div.hover { background-position: center top; } //override

jQuery note

1

if .hover is too vague, go with

div#some-holding-div div.hover {...}

I'm sure there is some holding div in your markup

2

Also, you could set css properties straight from jQuery (instead adding class and removing class, you could just set nackgroundPosition and set it back)

note

It's just from top of my head, could be probably tailored to better suit your needs - and it wasn't tested.

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630469

Try something like this using .hover():

$(".image img").hover(function() {
  $(this).closest(".image").css({ 'background-position': 'top center' });
}, function() {
  $(this).closest(".image").css({ 'background-position': 'bottom center' });
});

When hovering over a <img> inside a class="image" it looks up to the div and swaps the background, same when you hover out in reverse. You can add more properties in the .css() call if you want to spice it up more, read here for details.

Upvotes: 1

Related Questions