Reputation: 183
I'm trying to make my jQuery code less repetitive by constructing a selector out of two variables.
I would like to put the class 'legend' and the second classname in two separate variables and combine them as one selector.
My HTML
<div class="legend a">
<div class="icon"></div>
<p class="description">Autmotive</p>
<div class="switch"></div>
</div>
<div class="legend b">
<div class="icon"></div>
<p class="description">Power Conversion</p>
<div class="switch"></div>
</div>
<div class="legend c">
<div class="icon"></div>
<p class="description">Charger Switches</p>
<div class="switch"></div>
</div>
My jQuery
$('.legend.a').hover(
function () { $('.call-out.a').find('.icon').addClass('hover')},
function () { $('.call-out.a').find('.icon').removeClass('hover')}
);
$('.legend.b').hover(
function () { $('.call-out.b').find('.icon').addClass('hover')},
function () { $('.call-out.b').find('.icon').removeClass('hover')}
);
$('.legend.c').hover(
function () { $('.call-out.c').find('.icon').addClass('hover')},
function () { $('.call-out.c').find('.icon').removeClass('hover')}
);
I tried:
var firstClass = $('.legend').attr('class').split(' ')[0];
var secondClass = $('.legend').attr('class').split(' ')[1];
var legend = $('.'+ firstClass +'.'+ secondClass +'');
But it's targeting all elements. How can I target legend.a, b or c separately?
Thanks
Upvotes: 1
Views: 214
Reputation: 79830
How about generalizing the hover function like below,
// v-- Seleact all legend
$('.legend').hover(
function () {
var targ = $(this)[0].className.split(' ')[1];
$('.call-out.' + targ).find('.icon').addClass('hover')
},
function () {
var targ = $(this)[0].className.split(' ')[1];
$('.call-out.' + targ).find('.icon').removeClass('hover')
}
);
Upvotes: 0
Reputation: 4808
I would add a data attribute to specify the target class:
<div class="legend a" data-target="a">
Then your js can be more generic, like:
$('.legend').hover(
var target = $(this).data('target');
function () { $('.call-out.' + target).find('.icon').addClass('hover')},
function () { $('.call-out.' + target).find('.icon').removeClass('hover')}
);
Upvotes: 3