0

I have this code:

$('#services_list > div').hover(function() {

    var serviceHoveredOn = '#' + $(this).attr('id');
    $(serviceHoveredOn + ' .service_expand').stop().animate({'width': '169px'}, 150);

},

function() {

    $(serviceHoveredOn + ' .service_expand').stop().animate({'width': '159px'}, 150);

});

But, serviceHoveredOn is not defined when I hover outside of my div. I searched and found this: jquery: passing variables in hover() function? But I am not sure how I can use toggle() to solve my problem. Thank you.

1 Answer 1

1

You cannot access variables declared in another function.


In your case, you don't even need it. Just use this, and pass it as a context:

$('#services_list > div').hover(function() {
    $('.service_expand', this).stop().animate({'width': '169px'}, 150);
},
function() {
    $('.service_expand', this).stop().animate({'width': '159px'}, 150);
});
Sign up to request clarification or add additional context in comments.

7 Comments

Amazing, thank you. I didn't know that I could use this like that. Would you mind explaining what that's called so I can look it up?
$('.service_expand', this) is equivalent to $(this).find('.service_expand'). It's called "the context". See the jQuery docs.
Ah, I knew about .find but I didn't even think about using it. This way is even simpler though. Much appreciated.
better to do $(this).find(".service_expand")...
@epascarello - Why? I think the context method might even be more performant. And don't tell me that find is clearer. Once you get used to using the context, it's just as clear.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.