Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer equal to 3 not meeting ==3 condition

I have some javascript/jQuery code used to make image transitions. $(obj) is a box containing two images, which is the size of each image. The following snippet of code is used to choose a new location outside of $(obj)'s borders, which is different from the previous location used (since one image sliding to the right while a new one comes from the left looks a lot better than one sliding to the right while another comes from the right.)

            var newLoc = Math.floor((Math.random() * 4));
            if ($(obj).data('lastloc') == newLoc) {
                console.log("FIXED "+newLoc);
                if (newLoc == 3) newLoc = 2;
                if (newLoc == 2) newLoc = 3;
                if (newLoc == 0) newLoc = 1;
                if (newLoc == 1) newLoc = 0;
                console.log("WITH "+newLoc);
            }

The issue I'm having is that both Chrome and Firefox are outputting this in the JavaScript console:

FIXED 3
WITH 3

How is this possible?

like image 670
Eric Dubé Avatar asked Mar 27 '26 05:03

Eric Dubé


1 Answers

You need else if. It is just falling through here

if (newLoc == 3) newLoc = 2;
if (newLoc == 2) newLoc = 3;

Try this instead

if (newLoc == 3) newLoc = 2;
else if (newLoc == 2) newLoc = 3;
else if (newLoc == 0) newLoc = 1;
else if (newLoc == 1) newLoc = 0;

or use a proper switch

like image 70
Daniel A. White Avatar answered Mar 29 '26 19:03

Daniel A. White