user4973992
user4973992

Reputation:

How to condense this jquery code?

Looking for help to shorten this code block:

Edit: This is a portion of the "list" (3 shown here) but my actual code has 6.

<script>
 $('.clickme-newyork, #link4, #link8, #link9').hover(function() {
   $(".card-cp").addClass("card-bg-cp");
   $(".card-gv").addClass("card-bg-gv");
   $(".card-hcm").addClass("card-bg-hcm");   
 }); 
</script>

This did NOT work correctly:

<script>
 $('.clickme-newyork, #link4, #link8, #link9').hover(function() {
   $(".card-cp, .card-gv, .card-hcm").addClass("card-bg-cp, card-bg-gv, card-bg-hcm");
 }); 
</script>

Upvotes: 0

Views: 55

Answers (3)

Red2678
Red2678

Reputation: 3287

$('.clickme').hover(function() {
   $(".card-cp, .card-gv, .card-hcm").addClass(function(index, className){
      switch(className){
        case 'card-cp': return 'card-bg-cp';
        case 'card-gv': return 'card-bg-gv';
        case 'card-hcm': return 'card-bg-hcm';
      }
   });
 });

Fiddle: https://jsfiddle.net/red2678/20Lurcx2/8/

Upvotes: 0

Dev Ops
Dev Ops

Reputation: 96

You can try

var classMap = [
    [".card-cp","card-bg-cp"],[".card-gv","card-bg-gv"],[".card-hcm","card-bg-hcm"]
];

$(".clickme-newyork, #link4, #link8, #link9").hover(
  function() {  // when the mouse pointer enters the element.
    $.map( classMap, function( c, i  ) { $( c[0] ).addClass( c[1] ); });
  });

made a JSFiddle to see the result https://jsfiddle.net/sysdevcode/u7kfsf65/

Link to Jquery Map: http://api.jquery.com/map/

Upvotes: 0

WillardSolutions
WillardSolutions

Reputation: 2314

Extrapolating the comments, you need to decide whether "condensing" your code is really necessary. As @Mojtaba said, you can write a function that does this work programatically. For instance:

function myAddClass(target, classname) {
    $(target).addClass(classname);
}

Then you would do...

<script>
 $('.clickme-newyork, #link4, #link8, #link9').hover(function() {
      myAddClass(".card-cp","card-bg-cp");
      .... 
 }); 
</script>

Not very 'shortened', is it?

However if you have a lot of these to do, you can put them into an array and loop through them with your myAddClass() function. That might save you some space - but the real question is this: does the shortcut make code shorter (or easier to read)? Generally speaking, the jQuery library already provides great shortcuts to what would otherwise be verbose code blocks. So maybe your best bet is to leave your code as it is.

Upvotes: 1

Related Questions