JQuery Error: Missed TypeError: cannot use the "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 the header, the jQuery code above (which runs in the DOM ready) returns this error

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

Why is this? What am I doing wrong?


I’m trying to make a button that, when hovering, changes color and, when the mouse leaves, returns to its original color. I cannot set values ​​rigidly: I need this to be flexible and in itself to remember the old background color. The following code works fine, but if I move the mouse too fast, 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 in DOMReady, but not every time the mouse hits. In other words, I need to use the first code, but that throws an error. What can I do?

+4
source share
1 answer

You can use the "every" jQuery function:

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

"Everyone" should run this for each node match; your original would probably not have the correct meaning for 'this'.

+5
source

Source: https://habr.com/ru/post/1489693/


All Articles