views:

48

answers:

4
.myDiv {
   background: url(/images/myimage.jpg);
   margin: 0 auto;
}

<div class="myDiv">
  Click Me!
</div>

I just want the Background image to fade, and not the the text Click me. Is that possible in jQuery?

Here's my attempt :

  $(".myDiv").hover(function() {
 $(this).css("background", fadeTo("slow", 0.5))
  },function(){
  $(this).fadeTo("slow", 1.0);
});

Which obviously doesn't work. It's just psuedo-code. :(

+4  A: 

This is impossible; you cannot have a semi-transparent background image, even in HTML5. (AFAIK)

Instead, you should make a separate <div> element for the background and fade it in normally.

SLaks
You have the largest rating I have ever seen on SO. I am honored to have an answer annhilated by you. :D
Trip
A: 

You will have to create your text div and position it in front of another "background div" and then fade out the background div. You should consider if it is necessary to do this in the first place?

Rick Chen
A: 

jQuery doesn't support anything like that natively. However check this article to see how it can be done with cleverly designed background images.

The effect is done by using the animate function and moving the backgroundPosition CSS style.

Philip T.
+1  A: 

You could simulate what you're trying to do with 2 absolute divs on top of eachother. Consider the following scenario.

<div class="my-div">
    <div class="my-background"></div>
    <span class="my-text">Some text here</span>
</div>

CSS

.my-div {
    position: relative;
    width: 100px;
    height: 20px;
}
.my-background {
    position: absolute;
    background: url(bg.jpg);
    width: 100px;
    height: 20px;
    z-index: 2;
}
.my-text {
    position: absolute;
    z-index: 3;
}

Basically I've created a div, placed an div with a background inside, and a text element on top.

You can now easily fade the background using

$(".my-background").fadeTo("slow", 0.5);
Marko