0

I have the a method and the following code to get an array id divs

arr = $('.card.recipe-slider');

which returns me (for the first time)

[<div class=​"card recipe-slider active" data-id=​"1">​…​</div>​, 
<div class=​"card recipe-slider" data-id=​"2">​…​</div>​, 
<div class=​"card recipe-slider" data-id=​"3">​…​</div>​] 

But when I call the same method again, ( for the second time), my Jquery DOM array gets duplicated as follows

[<div class=​"card recipe-slider active" data-id=​"1">​…​</div>​, 
<div class=​"card recipe-slider" data-id=​"2">​…​</div>​, 
<div class=​"card recipe-slider" data-id=​"3">​…​</div>​
<div class=​"card recipe-slider" data-id=​"1">​…​</div>​, 
<div class=​"card recipe-slider" data-id=​"2">​…​</div>​, 
<div class=​"card recipe-slider" data-id=​"3">​…​</div>​
]

So my question is how can I avoid this duplication?

I tried followings

1 ) make the array blank

arr = []
... code

2 ) Get the unique

$.unique($('.card.recipe-slider'))

3 ) Clearing the array first

  $('.card.recipe-slider').empty();
   arr = $('.card.recipe-slider')

4 ) and I have seen some solutions with cloning and replacing , which I'm not quite clear and don't know if that's the way to go.

Edit

Complete code , almost... :), this works as a wizard where each div will display when user clicks next

#html
<div class='card recipe-slider active' data-id='1'>
   .. html
   <a class="btn btn-warning button-full button-large icon-left next">Next..</a> 
</div>
<div class='card recipe-slider' data-id='2'>
  .. html
   <a class="btn btn-warning button-full button-large icon-left next">Next..</a> 
</div>
<div class='card recipe-slider' data-id='3'>
  .. html
   <a class="btn btn-warning button-full button-large icon-left next">Next..</a> 
</div>

JS code

$(document).on('click', 'a.next', function(e){
    arr = [];
    arr = $('.card.recipe-slider');
    current_card = $(this).closest('.card')[0];
    id = current_card.dataset.id;

    $(arr[id]).addClass('active');
    $(current_card).removeClass('active');

  })
halfer
  • 19,824
  • 17
  • 99
  • 186
sameera207
  • 16,547
  • 19
  • 87
  • 152

0 Answers0