I used this line in my jQuery plugin.But i didn't understand what does this line do.Below is that plugin code.
Kindly explain me briefly.
(function ($) {
$.simpleSlideShow = function (selector, settings) {
// settings
var config = {
'delay': 2000,
'fadeSpeed': 500
};
if (settings) { $.extend(config, settings); }
// variables
var obj = $(selector);
var img = obj.children('img');
var count = img.length;
var i = 0;
// show first image
img.eq(0).show();
// run slideshow
setInterval(function () {
img.eq(i).fadeOut(config.fadeSpeed);
i = (i + 1 == count) ? 0 : i + 1;
img.eq(i).fadeIn(config.fadeSpeed);
}, config.delay);
return this;
};
})(jQuery);
I used this line in my jQuery plugin.But i didn't understand what does this line do.Below is that plugin code.
Kindly explain me briefly.
(function ($) {
$.simpleSlideShow = function (selector, settings) {
// settings
var config = {
'delay': 2000,
'fadeSpeed': 500
};
if (settings) { $.extend(config, settings); }
// variables
var obj = $(selector);
var img = obj.children('img');
var count = img.length;
var i = 0;
// show first image
img.eq(0).show();
// run slideshow
setInterval(function () {
img.eq(i).fadeOut(config.fadeSpeed);
i = (i + 1 == count) ? 0 : i + 1;
img.eq(i).fadeIn(config.fadeSpeed);
}, config.delay);
return this;
};
})(jQuery);
Share
Improve this question
edited Aug 25, 2014 at 7:31
hjpotter92
80.7k36 gold badges148 silver badges187 bronze badges
asked Aug 25, 2014 at 7:27
SaadSaad
978 bronze badges
1
-
It is more mon to write this as
i++; if(i===count) i=0;
, ori=(i+1) % count;
. The first option is simple, and the second one is somewhat idiomatic. – Kobi Commented Aug 25, 2014 at 7:31
5 Answers
Reset to default 6This is simple Conditional (ternary) Operator which is same as
if(i + 1 == count){
i = 0;
}
else{
i = i+1;
}
Just a suggestion it could be just
i = (i+1) % count;
in English, it means: if i+1 is equal to count, then i=0. Else, i = i+1.
It's a shorthand notation in a lot of languages.
The a ? b : c
syntax is a ternary operator.
This will be the same as
if(i + 1 == count)
i = 0;
else
i = i + 1;
See more information here: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
This is simple ternary operator as guys said already, but I would use this instead: i = ++i % count
.
This is short form of if
and else
. Meaning of this statement
i = (i + 1 == count) ? 0 : i + 1;
is same as
if (i + 1 == count) {
i = 0;
} else {
i = i+1;
}