The task is such that when you hover over an element to change its backgroundColor, after you move the mouse away, the old backgroundColor value should return.

$('td').hover( function(){ var a = $(this).prop('style'); $(this).css('backgroundColor', 'navy'); }, function(){ $(this).css('backgroundColor', a.backgroundColor); }); 

I do not return the same color. The variable is immediately written to the color that was changed.

  • Who sets you such tasks? - Drakonoved
  • @Drakonoved who puts something)) - YURII
  • What is not satisfied with the decision on CSS? Simpler and shorter + JS is not always enabled in the browser. - Drakonoved
  • @Drakonoved that suits me)), but this is exactly the task that was told to do so ((( YURII

2 answers 2

You have а local variable. Logically, the other function knows nothing about it. Save the value to the element itself using the data() method

 jQuery(document).ready(function($) { $('div').hover( function() { var el = $(this); el.data({color: el.css('backgroundColor')}) .css('backgroundColor', 'navy'); }, function() { var el = $(this); el.css('backgroundColor', el.data('color')); } ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>Div1</div> <div>Div2</div> 

But a CSS :hover pseudo- :hover solution is much better.

    This is done in CSS using the hover pseudo-class.

     const originalBackgorund = js.style.backgroundColor; js.onmouseover = e => e.target.style.backgroundColor = 'green'; js.onmouseout = e => e.target.style.backgroundColor = originalBackgorund; 
     div{ width: 100px; height: 100px; background-color: black; } div:hover{ background-color: red; } 
     <div></div> <div id=js></div> 

    • Thank. But so I know how to do it. The task is to make it through jQuery, without using new classes or css - YURII
    • @YURII updated the answer - Darth
    • And how can you, when you hover, determine the current color of the element and write it to a variable, and then use it? - YURII
    • one
      @YURII updated the answer. it is better to do this not when pointing (at every ..), but in advance - Darth