views:

33

answers:

3

I need to be able change the position of a background image in a containing div when I mouse over a link within that div.

Here is the page: It is the two blue play buttons mid right.

I had it working before but it is broken and I can't get it to work properly.

Here is the html:

<div class="h-video">
<p><a class="play-video" href="#flashArea3">Secondary headline goes here to say something you want. This needs to grab their attention.</a></p>
</div>

Here is the jQuery:

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

I would appreciate any assistance.

Thanks.

+4  A: 

Why use javascript? You can do this in CSS alone, although IE6 won't support it on a <div> element.

Example: http://jsfiddle.net/yr4yH/1/

CSS from example above:

.h-video {
    width: 461px;
    height: 67px;
    background-image: url("http://www.theideapeople.com/projectpath/ideapeople-new/_images/btn_video-home.png");
    background-position: bottom center;
    background-repeat: no-repeat
}

.h-video:hover {
    background-position: top center;
}​

If you need to support IE6, I'm sure you could rework your layout so .h-video is an <a> element instead of a <div>.

patrick dw
this turned out to be the most effective solution for this situation. Thanks.
fmz
@fmz - You're welcome. :o)
patrick dw
A: 

I'll leave a separate answer for this solution, but I'd still say to use CSS instead of javascript.

Your code that assigns then handlers with .hover() is running before the elements are loaded. Otherwise your code is correct.

The code example below wraps your code with $(function() { ... }); which is a shortcut for jQuery's .ready() method, which ensures that the document is loaded before your code runs.

   // Wrap your code like this so it doesn't run until the DOM is ready
$(function() {
    $(".h-video").hover(function() {
     $(this).closest("div").css({ 'background-position': 'top center' });
        }, function() {
     $(this).closest("div").css({ 'background-position': 'bottom center' });
    });
});

Also, jQuery's .closest() method isn't necessary here, but it doesn't hurt either. Might as well remove it.

patrick dw
A: 

Couple of notes:

  1. You have the positions reversed: "center top" not "top center" and "center bottom" not "bottom center" ref: http://www.w3schools.com/css/pr_background-position.asp

  2. Use addClass and RemoveClass. Don't set styles in-line. Use it just like the example on docs.jquery.com.

  3. If you don't need the IE support use CSS declaration w/o javascript.

nopuck4you