Sergio Sergio - 1 year ago 82
HTML Question

Jquery mouseover change background color

Jquery code:

$(".menu_clickable").mouseover(function() {
$(this).css({'background-color' : '#F00'}).mouseout(function(){
$(this).css({'background-color' : '#FFF'});

$(".menu_clickable").live('click', function() {
$(this).css({'background-color' : '#FCC'});

HTML source:

<div class="menu_clickable prof_info2" id="prof_info" >first</div>
<div class="menu_clickable prof_info3" id="prof_info" >second</div>
<div class="menu_clickable prof_info3" id="prof_info" >third</div>

I'm trying to make the hover efect using Jquery and it is working fine but if I want to change the DIV background color when it's clicked it's not working, actually the clicked DIV change background color but it is stay like that while the cursor is on it. If I move it out it will restore the original background color. Why?

Luc Luc
Answer Source
  1. You are attaching way too many mouseout handlers. Every time you move the mouse over your menu_clickable, you change bacgkround and then you attach another mouseout event. That's bad.

  2. You are attaching click event "live" and mouse* with normal procedure. Why? Basically if you need live attaching use it, otherwise better stay clear (better performance).

  3. It is much easier to use css classes to change UI. Like


.menu_clickable { background-color: #FFF; /* default color */ }
.clicked { background-color: #FCC; /* color for clicked button */ }
.mouseover { background-color: #F00; /* color when hovered */ }


<div class="menu_clickable prof_info2" id="prof_info">first</div>
<div class="menu_clickable prof_info3" id="prof_info">second</div>
<div class="menu_clickable prof_info3" id="prof_info">third</div>


$(document).ready(function () {
        .mouseover(function () {
            var t = $(this);
            if (!t.hasClass("clicked")) {  // very easy to check if element has a set of styles
        .mouseout(function () {  // attach event here instead of inside mouse over

    $(".menu_clickable").click(function () {
        var t = $(this);
        if (t.hasClass("clicked")) {
        } else {

This will have a hover effect if button is not clicked; when clicked it stays #FCC until clicked again.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download