-1

I have repeating code of $("#id").addClass('disabled'); and $("#li-hzd").removeClass('disabled'); in my code for multiple ids in multiple functions. So I am trying to write some generic routine something like,

function toggleClass(id,classname,action){
    $("#"+ id") +"." + classname+"("+action+") 
}

which can be called something like,

toggleClass(id,'addClass','disabled');
toggleClass(id,'removeClass','disabled');

I believe something can be done using eval() but I also read it's bad practice to use eval. So any idea how to accomplish ?

Ris
  • 1,152
  • 7
  • 29
  • 63

3 Answers3

2

You can also get the jQuery methods by using bracket notation.

function toggleClass(id, action, classname){
    $("#"+ id)[action](classname) 
}

toggleClass(id,'addClass','disabled');
toggleClass(id,'removeClass','disabled');
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

You can access object properties via bracket notation []:

function toggleClass(id, classname, action) {
    $("#" + id)[classname](action) 
}

Side note: You seem to have gotten the naming of the parameters classname and action wrong. Should probably be the other way round to make more sense! The function name should be the action and the class name should be the classname. :-)

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
0

Instead of using addClass and removeClass,use can just use toggleClass which adds the class name if not present else removes it

so change your toggleclass method to the following

function toggleClass(id,classname){
    $("#"+ id).toggleClass(classname) 
}
Geeky
  • 7,420
  • 2
  • 24
  • 50