0

Let's say I have the following code

var $variable = $('<li/>', { 
    tabindex: 0,
    click: function() {
        //more code in here
    }
}

is it possible to define the click: with a variable? Baring in mind it is already inside a variable and will also include an if statement, like so:

if(condition) {
    var functiontype = 'click';
}
else {
    var functiontype = 'hover';
}
var $variable = $('<li/>', { 
    tabindex: 0,
    functiontype: function() {
        //more code in here
    }
}

I tried doing this but it didn't work. Can someone please point me in the right direction?

2 Answers 2

2
if(condition) {
    var functiontype = 'click';
}
else {
    var functiontype = 'hover';
}

var options = {};
options["tabindex"] = 0;
options[functiontype] = function(){
    // your code
}
var $variable = $('<li/>', options);
Sign up to request clarification or add additional context in comments.

Comments

0

You may do the reverse :

var $variable = $('<li/>', { 
    tabindex: 0
};
$variable[condition?'click':'hover'] = function(){
   // the code here
}

Comments

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.