Reputation: 497
I know similar to this was asked allready, but my exampe is quite different, and can't manage to make it work.
Example: http://jsfiddle.net/xhUZd/
<ul id="list">
<li>
<div class="box1">
<span class="one"></span>
<span class="two"></span>
<span class="three"></span>
</div>
<div class="box2">
<span class="one"></span>
<span class="two"></span>
<span class="three"></span>
</div>
</li>
<li>
<div class="box1">
<span class="one"></span>
<span class="two"></span>
<span class="three"></span>
</div>
<div class="box2">
<span class="one"></span>
<span class="two"></span>
<span class="three"></span>
</div>
</li>
</ul>
Mission:
When HOVER
span.one from "Box2" - ADD CLASS "bg1" to span.one from "Box1"
span.two from "Box2" - ADD CLASS "bg2" to span.two from "Box1"
span.three from "Box2" - ADD CLASS "bg3" to span.three from "Box1"
This must work in EACH "li" individually.
Please help!
Upvotes: 1
Views: 1657
Reputation:
Apparently I missed requirements entirely. Here's a new attempt that assumes you want the hover behaviour to follow all SPANs across all DIVs across all LIs - hovering over span.two in .box3 would add class bg2 to span.two in .box2.
$(function () {
var classMap = {
one: 'bg1',
two: 'bg2',
three: 'bg3'
};
$('#list').on('mouseenter mouseleave', 'li div span', function () {
var $this = $(this);
$this
.closest('div')
.prev('div')
.find('span.' + $this.attr('class'))
.toggleClass(classMap[$this.attr('class')]);
});
});
Upvotes: 0
Reputation: 253308
I'd suggest:
$('#list').on('click', '.box2 span', function(){
var self = $(this),
box1 = self.closest('li').find('.box1'),
i = self.index();
box1.find('span').eq(i).addClass('bg' + (i + 1));
});
If you'd like to have a second click (or alternate clicks) toggle the class-name, replace addClass()
with toggleClass()
:
$('#list').on('click', '.box2 span', function(){
var self = $(this),
box1 = self.closest('li').find('.box1'),
i = self.index();
box1.find('span').eq(i).toggleClass('bg' + (i + 1));
});
Somehow I'd managed to miss the requirement for classes to be manipulated on hovering the elements, rather than clicking; so with that acknowledged the actual working answer would be as follows:
$('#list').on('mouseenter mouseleave', '.box2 span', function(){
var self = $(this),
box1 = self.closest('li').find('.box1'),
i = self.index();
box1.find('span').eq(i).toggleClass('bg' + (i + 1));
});
JS Fiddle demo, as adapted/corrected by the OP himself.
References:
Upvotes: 3