Search code examples
jqueryslidetoggle

Set jQuery toggle type as variable


Is there a way to set the toggle type as a variable? I have a function that fires the below markup; but sometimes I need it to be 'slideToggle' instead of 'fadeToggle'. I can easily set this as a conditional; but then I have to repeat markup.

Obviously the below code does not work; but it shows kind of what I'm going for.

var toggleType = ( _settings.toggleType == 'fade' ? 'fadeToggle' : 'slideToggle'  );

jQuery(_settings.target).stop(true, true).toggleType(function(){
    // callback after animation completes
});

Jason P led me to a working solution.

// set toggle type
var toggleType = ( _settings.toggleType == 'fade' ? 'fadeToggle' : 'slideToggle'  );

// toggle action
jQuery(_settings.target).stop(true, true)[toggleType](function(){

Solution

  • You can use bracket notation:

    jQuery(_settings.target).stop(true, true)[toggleType](function(){