raduken
raduken

Reputation: 2119

Jquery add and remove multiple classes of a div

I have 3 divs:

I would like remove the blue background in <h4> if I click in the next ou prev div.

I would like insert a class into my <i class="fa fa-lg fa-gamepad"></i> if <h4> has blue blackground (above).

but if I just click in the icon <i> the icon color change for that specific div.

I hope i did make that clear.

html:

<div class="box"><i class="fa fa-lg fa-gamepad"></i><h4>div 1 </h4></div>
<div class="box"><i class="fa fa-lg fa-gamepad"></i><h4>div 2 </h4></div>
<div class="box"><i class="fa fa-lg fa-gamepad"></i><h4>div 3</h4></div>

js:

$(document).ready(function() {
  var $box = $('.box').mousedown(function() {
    $('h4',this).toggleClass('highlight');
    var flag = $(this).hasClass('highlight')
    $box.on('mouseenter.highlight', function() {
      $('h4',this).toggleClass('highlight', flag);
    });
  });
  $(document).mouseup(function() {
    $box.off('mouseenter.highlight')
  })
});

css:

.box {
  float: left;
  height: 100px;
  width: 100px;
  border: 1px solid #000;
  margin-right: 10px;
}

.highlight {
  background: #0000FF;
}


.fa-gamepad {
  color: red;
}

https://jsfiddle.net/wv4f2hda/12/

Upvotes: 1

Views: 393

Answers (2)

MaXiNoM
MaXiNoM

Reputation: 36

You can use the .removeClass, and .addClass to help here and toggle between what is selected and what is not. I took out your h4 and just remove all the classes first, then add to the one selected

$(document).ready(function() {
  var $box = $('.box').mousedown(function() {
  $(".box").removeClass('highlight'); //removeing class
  $(this).addClass('highlight'); //adding to selected
  var flag = $(this).hasClass('highlight')
  $box.on('mouseenter.highlight', function() {
  $('h4',this).toggleClass('highlight', flag);
   });
  });
$(document).mouseup(function() {
$box.off('mouseenter.highlight')
  })
});

https://jsfiddle.net/MaXiNoM/8upn5kcv/2/

Upvotes: 2

Satpal
Satpal

Reputation: 133403

You need to traverse DOM using various methods and remove class from h4 element which is not child of current box element i.e. this

$('.box').mousedown(function() {
    //Toggle css for current element
    $('h4',this).toggleClass('highlight');

    //remove class from h4 element which is not child of current box element
    $box.not(this).find('h4').removeClass('highlight');
});

DEMO

Upvotes: 2

Related Questions