jQquery - the elements first class was changed, but jquery still calls the elements first class.

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

  •  24-09-2022
  •  | 
  •  

Question

I have a problem and I really searched for answers and I asked some persons.. but no solution. I have 3 'td' elements, they all belong to a class = "moreSpace" ... so when I click on a td element.. it changes its class to "deactivateAssignments" ... but the $(".moreSpace").mouseOver/mouseOut functions still have an effect on the element which its class was changed.. Why? please help me :(

(sorry for this mess, it is the first time that I post a problem here)

//DG

$(".moreSpace").mouseover(function(event) {
    var id = event.target.id;
    $('#'+id).css('color','#B5EABC')
});

$(".moreSpace").mouseout(function(event) {
    var id = event.target.id;
    $('#'+id).css('color','#24C635')
});

 function reclass(){
  $('#dg306').attr('class','moreSpace');
  $('#dg632').attr('class','moreSpace');
  $('#dg291').attr('class','moreSpace');
  alert('in');

}

var actId = 2;
$(".moreSpace").click(function(event) {
  reclass();
  var id = event.target.id;
  if (id == 'dg306'){
     actId = 1;
  } else if (id == 'dg632'){
     actId = 2;
  }else if (id == 'dg291'){
     actId = 3;
  }



switch (actId) {
       case 1:
            $('#dg306').toggleClass('moreSpace deactivateAssignments');
            break;
       case 2:
            $('#dg632').toggleClass('moreSpace deactivateAssignments');
            break;
       case 3:
            $('#dg291').toggleClass('moreSpace deactivateAssignments');
            break;

  }
Was it helpful?

Solution

You are using direct binding on the element. So whatever you are changing on this element, the binding will still be there.

2 solutions. You can unbind the binding with off inside the mouse event :

$(this).off('mouseover mouseout');

Or use delegation :

$(document).on({
    mouseover : function(){},
    mouseout : function(){}
}, '.moreSpace');

OTHER TIPS

Instead of using $('#'+id).css('color','#24C635') to change the colour of your element, use the CSS :hover property

.moreSpace{
color:#24C635;
}

.moreSpace:hover{
color:#B5EABC;
}

You can check to see if the class is present in the event handler and simple return if it isn't like this

$(".moreSpace").mouseover(function(event) {
    if(!this.hassClass(".moreSpace") 
       return; 

    var id = event.target.id;
    $('#'+id).css('color','#B5EABC')
}); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top