wobbily_col
wobbily_col

Reputation: 11891

JQuery / JavaScript , dynamically storing / applying functions

I currently have a piece of code as follow:.

var nextSibling = $(this.parentNode).next();

what I would like to do is potentially change the next() function to prev(), depending on the keypress. (I expect this to be an input element in a table).

How do I put the next() / prev() functions into variables (I am guessing you access it through some prototype object, but I am not sure which one).

if (keypressRight){ 
    var nexOrPrev =  SomeObject.prototype.next
}else{
    var nextOrPrev =  SomeObject.prototype.prev
}

Then to call it , I assume I would do the following :

 var nextSibling = $(this.parentNode).nextOrPrev()

Does that look like the correct way of doing things? I am open to suggestions of better ways. (I saw somewhere else suggesting using apply for the function call, but I don't currently see any benefit in using this).

Upvotes: 0

Views: 34

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123387

you may write

var nextOrPrev =  SomeObject.prototype[keypressRight?"next":"prev"];

using the ternary operator

and this can be done also for

$(this.parentNode)[keypressRight?"next":"prev"]();

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use bracket notation to call function on a jQuery object. Try this:

var funcName = keypressRight ? 'next' : 'prev';
var nextSibling = $(this.parentNode)[funcName]();

Upvotes: 3

Related Questions