1

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/

2 Answers 2

2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, but what I am trying to do is: make just the h4 with blue background, and if i click in the icon turns the icon to red.
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.