Search code examples
javascriptjquerypositiongallery

JQuery position issue?


So I am building a small gallery in jQuery.

var picwidth = $('.gallery-window ul li').width();
var left1 = $('.gallery-window ul').position().left;
var length = $('.gallery-window ul li').length;
var picnum = 1;

As you can see, I made 4 variables, the first one that gets the image width (so I don't need separate code for each device, since the website is responsive), the second one gets the left position (the problematic one), the third one gets me number of images (since there will be more than one gallery of this kind) and the final one is simply iteration.

Now, the code for the "next" button is the following

$('.gallery-next').click(function() {
  if (picnum === length) {
  $('.gallery-window ul').css("left", "0px").animate({left: left1 -= picwidth}, 500);
    picnum = 2;
  }
  else {
    $('.gallery-window ul').animate({left: left1 -= picwidth}, 500);
    picnum++;
  }

  console.log("number" + picnum);
  console.log("position" + left1);
});

Based on the two console logs I have at the very end, the issue appears to be that the position property does not return to 0 when the "if" condition is met. Don't get me wrong, jQuery does follow the "CSS" property orders and moves my list back to the beginning, but the position property remains at a minus.

Here is my console log info copied, hopefully you get what I mean:

number2 position-320

number3 position-640

number4 position-960

number2 position-960

There are 4 images so far, 3 regular ones and the 4th one is the same as the first one, because of transition effects. But when I am on the 4th one and I click next, everything looks alright, but my "position" property remains at -960. So if I click "next" after that, instead of taking me from 0 (where the css property set it) to -320 again, it instantly takes me to -1280, which, needless to say, messes up my gallery.

Any idea what could be causing this, and how can I fix it?


Solution

  • You may have noticed by now, but you are not setting left1 to 0, so why would it be 0? In both branches of the if, you are setting left1 -= picwidth, hence the console.logs that you see.

    If I was you, I'd change the variable value inside the if, and then do whatever you want after that:

    $('.gallery-next').click(function() {
        if (picnum === length) {
            left1 = 0;
            picnum = 2;
        }
        else {
            left1 -= picwidth;
            picnum++;
        }
    
        $('.gallery-window ul').animate({left: left1 }, 500);
    
        console.log("number" + picnum);
        console.log("position" + left1);
    });