user2999177 user2999177 - 2 months ago 6
jQuery Question

Unexpected behavior in simple jquery selector script

I have a jquery script that is supposed to highlight elements in a from-to manner. It should work backwards as well.
Here is working fiddle: https://jsfiddle.net/qmgob1d5/

It works fine, until I select zero (first box) as second element. Then the

var Start = Math.min(ClickOne, ClickTwo || 16);
doesn't seems to work as expected. What went wrong?

Here is the script:

var FirstClick;
var ClickOne;
var ClickTwo;
$('.ColorPreview').on('click',function() {

var ColorId = $(this).attr('id');
ColorId = Number(ColorId.split('_')[1]);

if (!FirstClick) {
//reset function
for (var i = 0; i < 16; i++) {
$('#Color_' + i).removeClass('SelectColor'); }
var ClickTwo;

ClickOne = ColorId;
FirstClick = true;
}

else {
ClickTwo = ColorId;
FirstClick = false; }

console.log('ClickOne ' + ClickOne)
console.log('Clicktwo ' + ClickTwo)

var Start = Math.min(ClickOne, ClickTwo || 16);
var End = Math.max(ClickOne, ClickTwo || 0);

console.log('start ' + Start)
console.log('end ' + End)

for (var i = Start; i <= End; i++) {
$('#Color_' + i).addClass('SelectColor'); }

});

Answer

When ClickTwo is 0, the expression ClickTwo || 16 will evaluate to 16.

Try

var Start = Math.min(ClickOne, ClickTwo == null ? 16 : ClickTwo);

Or else initialize ClickTwo to 16 at the beginning of the function.

Comments