Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery conditional chaining

Tags:

jquery

Let's say I have the following jQuery code. It works great, but then I need to include the .after($('<div />')) only if var insertAfter equals true. Is there an elegant jQuery way of doing this?

$('#whatEver')
    .parent()
    .show()
    .width(123)
    .addClass('bebo')
    .before($('<div />'))
    .after($('<div />'))
    .parent()
    .addClass('bla');
like image 872
user1032531 Avatar asked Dec 14 '12 14:12

user1032531


2 Answers

Try this using ternary operator:

.after(insertAfter ? $('<div />') : '')
like image 124
antyrat Avatar answered Sep 19 '22 12:09

antyrat


You can extend jQuery library like this:

$(function () {
    $.fn.afterif = function (param, condition) {
        if (condition) {
            $(this).after(param);
        }
        return this;
    }
}(jQuery));

And use it like this:

var insertAfter = true;
$('#whatEver').afterif($('<div />'), insertAfter);
like image 23
Musa Hafalır Avatar answered Sep 21 '22 12:09

Musa Hafalır