views:

2095

answers:

4

Hi!

I'd like to change the background position of a CSS-class while hovering a li-element.

HTML:

<div id="carousel">
    <ul id="submenu">
        <li>Apple</li>
        <li>Orange</li>
    </ul>
</div>

CSS:

#carousel { 
    float: left;
    width: 960px;
    height: 360px;
    background: url(../images/carousel.png);
}

Any suggestions on how to do this?

+2  A: 
$('#submenu li').hover(function(){
    $('#carousel').css('backgroundPosition', newValue);
});
Ben Shelock
Actually incomplete. Doesn't reset backgroundPostion when hovering stops. As it doesn't do that, also doesn't consider that there already might be meaningful value set for backgroundPosition which needs to be restored
jitter
Well thats all he asked for Jitter.
Ben Shelock
No. Reread question: "while hovering a li-element." Which to me implies "I want it reset when hovering stops"
jitter
No it doesn't jitter. If it said "while hovering a li-element. Then I want it reset when hovering stops" Then it would imply what you meant.Sorry to be so petty, however that comment you left months ago really pissed me off.
Ben Shelock
+1  A: 

Sets new value for backgroundPosition on the carousel div when a li in the submenu div is hovered. Removes the backgroundPosition when hovering ends and resets backgroundPosition to old value.

$('#submenu li').hover(function() {
    if ($('#carousel').data('oldbackgroundPosition')==undefined) {
        $('#carousel').data('oldbackgroundPosition', $('#carousel').css('backgroundPosition'));
    }
    $('#carousel').css('backgroundPosition', [enternewvaluehere]);
},
function() {
    var reset = '';
    if ($('#carousel').data('oldbackgroundPosition') != undefined) {
        reset = $('#carousel').data('oldbackgroundPosition');
        $('#carousel').removeData('oldbackgroundPosition');
    }
    $('#carousel').css('backgroundPosition', reset);
});
jitter
+3  A: 

Here you go:

$(document).ready(function(){
    $('#submenu li').hover(function(){
        $('#carousel').css('backgroundPosition', newValue);
    }, function(){
        $('$carousel').css('backgroundPosition', '');
    });
});
rebellion
What is a valid value of `newValue`? Is it a string? What format is it in?
Drew Noakes
He is changing the 'css property backgroundPosition', more details here: http://www.w3schools.com/css/pr_background-position.asp
Jakub
A: 

You guys are complicating things. You can simple do this from CSS.

#carousel li { background-position:0px 0px; }
#carousel li:hover { background-position:100px 0px; }
Marius Iordache
does not work in IE6.
meo
@meo I am so tempted to say "Who cares?" but Argh. IE6.
Christopher Altman