1

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

2 Answers 2

3

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')}
);
Sign up to request clarification or add additional context in comments.

Comments

0

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')
  }
);

2 Comments

I think you are meaning to split on the class attribute, not the element itself
@JustinBicknell You are right.. Thanks and corrected the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.