disable mouse events on click for (this) and re-enable them for ('.class').not(this) - jquery

StackOverflow https://stackoverflow.com/questions/19432069

Domanda

I need to keep the color of the clicked div until another div of the same class gets clicked. Right now I have this code:

$('.aaa').mouseenter(function () {
    $(this).css('background', '#dddddd');
});
$('.aaa').mouseleave(function () {
    $(this).css('background', '#888888');
});
$('.aaa').click(function () {
    $(this).css('background', '#555555');
    $('.aaa').not(this).css('background', '#111111');
    $(this).off('mouseenter mouseleave');
    $('.aaa').not(this).on('mouseenter mouseleave');
});

http://jsfiddle.net/5jUP7/

Only problem here is that I can't re-enable previously disabled events (for previously clicked elements).

How can this be achieved?

È stato utile?

Soluzione

Put your handlers in functions, to make it easy to refer to them in multiple places.

$(".aaa").on({
    mouseenter: mouseEnter,
    mouseleave: mouseLeave
});

function mouseEnter() {
    $(this).css('background', '#dddddd');
}
function mouseLeave() {
    $(this).css('background', '#888888');
}
$(".aaa").click(function() {
    $(this).css('background', '#555555');
    $(".aaa").not(this).css('background', '#111111');
    $(this).off('mouseenter mouseleave');
    $(".aaa").not(this).on({
        mouseenter: mouseEnter,
        mouseleave: mouseLeave
    });
});

FIDDLE

Altri suggerimenti

Have a look at this fiddle

You can do most of your work using simple CSS

HTML

<div class="aaa"></div>
<div class="aaa"></div>
<div class="aaa"></div>
<div class="aaa"></div>
<div class="aaa"></div>
<div class="aaa"></div>
<div class="aaa"></div>

CSS

.aaa {
    display:block;
    background:#888;
    width: 300px;
    height: 30px;
    border: 1px solid #000;
}
.aaa:hover,
.aaa.disabled:hover{
    display:block;
    background:#ddd;
}
.aaa.active {
    background:#111;
}
.aaa.disabled {
    background:#555;
}

JAVASCRIPT

$('.aaa').click(function () {
    $('.aaa').removeClass('active disabled');
    $(this).addClass('active');
    $('.aaa').not($(this)).addClass('disabled');
});

Don't disable anything. Just keep track of the previously clicked element.

var lastObjClicked;
function clicked(this){
  var thisClass = this.className;

  if( lastObjClicked.className == thisClass){
    document.getElementById(lastObjClicked.id).style.color = '#FF0000';
    document.getElementById(this.id).style.color = '#FF0000';

  }else{
    lastObjClicked = this;
  }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top