Jim22150 Jim22150 - 1 month ago 7
jQuery Question

Conditional Chain jQuery

Syntax question; is it possible to do the following:

var home_page_feed;
var videos = $get_utoob_videos;
for each(video in videos) {
if(video.special_interests)
$(home_page_feed).prepend(video.thumbnail);
else
$(home_page_feed).append(video.censornail);
}


...but in a single ternary operation, like this:

for each(video in videos)
$(home_page_feed) .CHAIN.
video.special_interests ?
// true - chain this
.prepend(video.thumbnail) :
// false - chain this instead
.append(video.censornail);


I put .CHAIN. as a placeholder. Is there a jQuery function that would chain to a incomplete statement by means of ternary operation assignment? I enjoy using ternary for statements and operations because of it's simplicity, so any help would be appreciated.

EDIT:
Here is a dirty solution I've come up with in the past for PHP scripts where trying to do the same thing. I don't like it because it relies heavily successful page load runtime.

for each($video in $videos) {
$chain =
$video.special_interests ?
".phpPrepend(video.thumbnail)" :
".phpAppend(video.censornail)";
$home_page_feed . $chain;
}


ANSWER
Thanks to @Barmar, who suggested the use of the eval() function, I was able to wrap it around the ternary operation.

$.each(videos, function(i, video) {
eval ("$(home_page_feed)" +
video.special_interest ?
".prepend(video.thumbnail)" :
".prepend(video.censornail)"
);
});

Answer

You can put the ternary in the argument to .append()

$.each(videos, function(i, video) {
    $(home_page_feed).append(video.special_interests ? video.thumbnail : video.censornail);
});

Or you can put it in the index:

$.each(videos, function(i, video) {
    $(home_page_feed).append(video[video.special_interests ? "thumbnail" : "censornail"]);
});

Note the quotes in the last version.

You could do your code using eval()

$.each(videos, function(i, video) {
    var chain = video.special_interest ? 
        ".prepend(video.thumbnail)" :
        ".prepend(video.censornail)";
    eval ("$(home_page_feed)" + chain);
});