views:

27

answers:

3

I have a background image on a div and I would like to change its position from center bottom to center top when I mouse over the link which is in the div.

I don't speak jQuery very well, I am kind of like the American in France, knowing little more than parlez vous, but here goes.

Here is the html:

<div class="video-link">
 <a href="#">Watch the Pack It Videos Now.</a>
</div>

Here is the CSS:

.video-link { 
        width: 610px;
        height: 68px;
        background: url(../_images/btn_horz-video.png) no-repeat center bottom;
        margin: 10px 0 10px 50px; 
        }

.video-link a { 
        color: #000; 
        text-decoration: none; 
        border: none;
        font-size: 18px;
        display: block;
        padding: 25px 0 0 90px; font-weight: bold; }                                                    

And last but not least, here is the jQuery:

$(".video-link a").hover(function() {
  $(this).closest(".div").css({ 'background-position': 'top center' });
  }, function() {
  $(this).closest(".div").css({ 'background-position': 'bottom center' });
});

Here is the page - It is the Watch the Pack It Videos Now image about midway down the page.

Thanks.

A: 

See jQuery Mouseover.

mcandre
Why do you recommend `mouseover` instead of `hover`? Care to elaborate?
patrick dw
Hmm, it looks like hover may be better as mouseover won't work if display:none is set.
mcandre
+4  A: 

I would just change it to this:

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

I tested it on your site and it worked.

EDIT: What I did was remove the a and just applied the hover to the div. Then I took out the closest method call and just applied the css change to this since it now applies to the div. Obviously this wouldn't work if other places are using this css but I didn't see any.

spinon
While this works, I would make 2 comments here...the first is that this isn't genuine anymore, you're giving a hover state for an area that if clicked, might no do anything (outside the link, still on the div)...the second, I would do this purely in CSS if doing the hover on the div, no reason for JS/jQuery in that case :)
Nick Craver
@Nick Both valid points. Thanks!
spinon
+3  A: 

In your .closest(selector), instead of ".div" you just need "div", like this:

$(".video-link a").hover(function() {
  $(this).closest("div").css({ 'background-position': 'top center' });
}, function() {
  $(this).closest("div").css({ 'background-position': 'bottom center' });
});

.div is a class selector looking for a class="div" element, whereas div is an element selector, looking for <div>.

Nick Craver
Hi Nick, you helped me on something very similar about three months ago. Well done! thanks.
fmz
@Nick Good catch! I didn't even notice that.
spinon