0

Is there a way to replace jQuery event name with variable like the following? If there is, how? If not, why?

Thank you very much. The original code:

var menu = $('.menu');
var search_bar = $('#search_bar');
var bar = $('#bar');
var icon = $('.myicon');

search_bar.focusin(function(){
    search_bar.css('width','20%');
    menu.css('width','80%');
    bar.css('color', '#000);
    icon.css('color', '#000);
});

The code I'd like to have:

function doSomething(tag, tagAction, actionAttributes) {
    if ((tag) && (tagAction)) {
        $(tag).???tagAction(actionAttributes.key, actionAttributes.val);
    }
}

???tagAction stands for 'css', is there a wildcard symbol that can replace event name, or I should have to use 'switch' to let the code below work correctly?

doSomething(".menu", "css", "{'width':'80%'}");
Tao Wang
  • 186
  • 1
  • 18

1 Answers1

3

You can use bracket notation

function doSomething(tag, tagAction, actionAttributes) {
    if ((tag) && (tagAction)) {
        $(tag)[tagAction](actionAttributes.key, actionAttributes.val);
    }
}

Notice, the way you are trying to call doSomething won't work, as the actionAttributes variable is a string, not an object. Calling it like this will work.

doSomething(".menu", "css", {key:'width', val:'80%'});
tcigrand
  • 2,357
  • 2
  • 14
  • 24