1

I'm trying to fadein a background-image to my list item. I've tried everything but couldn't find it...

HTML:

<li id="een">
    <h1>Title</h1>
    <p id="text1">Text</p>
</li>

jQuery:

$('#een').mouseenter(function(){
    $('#een').css("background-image", "url(images/een.png)");
});
Devin Burke
  • 13,642
  • 12
  • 55
  • 82
  • Try to wrap URL of image in `'` and make sure that your image's relative path is valid. You can also look here: http://stackoverflow.com/questions/512054/setting-background-image-using-jquery-css-property – ezze Nov 01 '12 at 20:45

2 Answers2

2

You'll need to make a background img element that is positioned absolute inside a relative parent.

jsFiddle

Here is an example of what I mean.

HTML Notice I add a div with the class li-background as first item in each li. This will be edited by CSS to not show on load and be absolutely positioned within its li parent which is relatively positioned. I also set its z-index to -1 so it doesnt show in from of text or any other item in li, so its a background!

<ul>
    <li id="een">
        <div class="li-background"><img src="http://www.freenew.net/upload/pscreen/47/gradient-screensaver-32.jpg" /></div>
        <h1>Title</h1>
        <p id="text1">Text</p>
    </li>
    <li id="een">
        <div class="li-background"><img src="http://www.freenew.net/upload/pscreen/47/gradient-screensaver-32.jpg" /></div>
        <h1>Title2</h1>
        <p id="text1">Text2</p>
    </li>
    <li id="een">
        <div class="li-background"><img src="http://www.freenew.net/upload/pscreen/47/gradient-screensaver-32.jpg" /></div>
        <h1>Title3</h1>
        <p id="text1">Text3</p>
    </li>
    <li id="een">
        <div class="li-background"><img src="http://www.freenew.net/upload/pscreen/47/gradient-screensaver-32.jpg" /></div>
        <h1>Title4</h1>
        <p id="text1">Text4</p>
    </li>
</ul>

CSS

ul li { position: relative; }
ul li:hover { color: white; }
.li-background {
    display: none;
    height: 100%;
    left: 0;
    position: absolute;
    top: 0;
    width: 100%;
    z-index: -1;
}
.li-background img {
    height: 100%;
    width: 100%;
}

jQ Script

$("li").hover(function(eIn) {
        $(this).children(".li-background").stop().fadeIn();
    },
    function(eOut) {
        $(this).children(".li-background").stop().fadeOut();
    });
SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
0

You could also use switchClass if you really want to go with background. like this:

if ($('#testDiv').hasClass('class1'))
    $('#testDiv').switchClass("class1", "class2", 500);
else 
    $('#testDiv').switchClass("class2", "class1", 500);
Felix
  • 830
  • 10
  • 17