0

I am trying to make jQuery update the values in the selector after they are passed. What I mean is this.

I am passing the selector like this.

var items = ['.item-1','.item-2'...];
$(items[1]).click(function(){....});

And then in the end of the function I change the order of the items array.

var items = ['.item-1','.item-2'...];
$(items[1]).click(function(){
    // ... function
    items = ['.item-3', '.item-1' ...];
});

Now the problem is that the function is binded to the inital items[1], so my changing of the array does not really matter. I am pretty sure there should be a not too complicated solution, so can you please point me in the right direction ?

vshotarov
  • 145
  • 9
  • Could you explain the higher level goal? You may be going about this the wrong way, but it's hard to tell what you're trying to do with it. – Barmar Jun 29 '15 at 21:33
  • @Barmar I am creating a animation between 3 items, where if you click the middle one the animation is triggered and the movement is as follows: First -> Middle Middle -> Third Third -> First – vshotarov Jun 29 '15 at 21:49
  • How about using event delegation and changing the classes of the elements. – Barmar Jun 29 '15 at 21:50
  • Is it any beneficial ? Because Claudio's solution works perfect. – vshotarov Jun 29 '15 at 21:55
  • It's more idiomatic. You can write the event handler once, it doesn't need to redefine itself each time. – Barmar Jun 29 '15 at 21:55
  • Fair enough, I will look into it. Thank you ! – vshotarov Jun 29 '15 at 22:00

2 Answers2

1

You could one method in combination with a recursion schema

var items = ['.item-1','.item-2','.item-3'];
$(items[1]).one('click', clickHandler);

function clickHandler() {
    items = //re-sort items;
    $(items[1]).one('click', clickHandler);
}

Take into account that arrays index is zero based so you're using the second item and not the first when doing items[1].

Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
1

I think you have to use a recursive method.

It could be:

   var items = ['.item-1','.item-2'];
    function redefine(){
        $(items[1]).click(function(){
            items = ['.item-3', '.item-1'];
            $(this).unbind("click");
            redefine();
        });
    }
    redefine()