good_evening good_evening - 5 months ago 25
jQuery Question

Change background color on mouseover and remove it after mouseout

I have table which class is

forum
. My jquery code:

<script type="text/javascript">
$(document).ready(function() {
$('.forum').bind("mouseover", function(){
var color = $(this).css("background-color");

$(this).css("background", "#380606");

$(this).bind("mouseout", function(){
$(this).css("background", color);
})
})
})
</script>


It perfectly works, but is it possible to do it in more efficient way without
var color = $(this).css("background-color");
. Just after
mouseout
leave the previous background-color and remove
#380606
? Thank you.

Answer

If you don't care about IE ≤6, you could use pure CSS ...

.forum:hover { background-color: #380606; }

With jQuery, usually it is better to create a specific class for this style:

.forum_hover { background-color: #380606; }

and then apply the class on mouseover, and remove it on mouseout.

$('.forum').hover(function(){$(this).toggleClass('forum_hover');});

If you must not modify the class, you could save the original background color in .data():

  $('.forum').data('bgcolor', '#380606').hover(function(){
    var $this = $(this);
    var newBgc = $this.data('bgcolor');
    $this.data('bgcolor', $this.css('background-color')).css('background-color', newBgc);
  });

or

  $('.forum').hover(
    function(){
      var $this = $(this);
      $this.data('bgcolor', $this.css('background-color')).css('background-color', '#380606');
    },
    function(){
      var $this = $(this);
      $this.css('background-color', $this.data('bgcolor'));
    }
  );   

$(document).ready(function(){
  $('.forum').hover(
    function(){
      var $this = $(this);
      $this.data('bgcolor', $this.css('background-color')).css('background-color', '#380606');
    },
    function(){
      var $this = $(this);
      $this.css('background-color', $this.data('bgcolor'));
    }
  );    
});
.forum { color: white; }
#blue { background-color: blue; }
<meta charset=utf-8>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="forum" style="background-color:red;">Red</p>
<p class="forum" style="background:green;">Green</p>
<p class="forum" id="blue">Blue</p>