Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery error: Uncaught TypeError: Cannot use 'in' operator to search for 'backgroundColor' in undefined

$('.metro_menu_button').data('oldColor', $(this).css('background-color'));

$('.metro_menu_button').hover(function () {
    $(this).stop().animate({
        backgroundColor: '#303030'
    }, 300);

}, function () {

    $(this).stop().animate({
        backgroundColor: $(this).data('oldColor')
    }, 300);

});

As for title, the jQuery code above (which is performed on DOM ready) is returning this error

Uncaught TypeError: Cannot use 'in' operator to search for 'backgroundColor' in undefined

Why is this? What am I doing wrong?


I'm trying to do a button which, on hover, changes color and, when the mouse leaves, get back to its original color. I can't hardcode the values: I need this to be flexible and remember by itself the old background color. The following code works fine but, if I move the mouse in and out too quickly, it will "forget" the original color.

$('.metro_menu_button').hover(function () {

    $(this).data('oldColor', $(this).css('background-color'));

    $(this).stop().animate({
        backgroundColor: '#303030'
    }, 300);

}, function () {

    $(this).stop().animate({
        backgroundColor: $(this).data('oldColor')
    }, 300);

});

I need to save oldColor on DOMReady, not everytime the mouse gets in. In other words, I need to use the first code but this is throwing the error. What can I do?

like image 234
Saturnix Avatar asked Jul 04 '13 11:07

Saturnix


1 Answers

You may be able to use the 'each' function of jQuery:

$('.metro_menu_button').each(function() {
    $(this).data('oldColor', $(this).css('background-color'));
});

The 'each' should run this for each matching node; your original would probably not have had the correct value for 'this'.

like image 195
Adrian Wragg Avatar answered Nov 01 '22 07:11

Adrian Wragg