Július Ľuptovec
Július Ľuptovec

Reputation: 337

jQuery detach, prepend and condition

I have two div elements that are clickable. When I click one that contains "1" it will give it class="active", when I click one that contains "2" it will give it class="active" and remove class="active" from the 1st one. Basically it is like switch.

<div class="active">1</div>
<div class="">2</div>

then this block:

<div class="carousel-inner">
  <div class="carousel-item " data-id="1" data="carousel-item"></div>
  <div class="carousel-item " data-id="2" data="carousel-item"></div>
</div>

and after all this code: which is supposed to detach div that don't have data-id of "active" div. When switched, it's supposed to re-attach detached div and detach the second one.

<script>
$(document).ready(function(){
    var a = $("div:contains('1')"), 
        b; 
      if (a.hasClass('active')){ 
        b = $("[data-id!='1'][data='carousel-item']").detach(); 
      } 
      else{ 
         $(".carousel-inner").prepend(b);
      } 
}); 
</script>

however, it is not working. when I switch (class active moves from one div to another) nothing happens. only first div is detached but on switch it is not reattaching. Any ideas why ? Thanks for any help !

PS: 1. For certain reasons (FU mobirise) I'm not able to manipulate with those two divs with active class(give them onclick() attribute, new class or id and so on). 2. Sorry for my English.

Upvotes: 0

Views: 711

Answers (1)

Taplar
Taplar

Reputation: 24965

Here is one possible solution. I changed around how you were doing the swap so it isn't doing a detach. But it should give you an idea of how to potentially do it, if you did want to do the detach anyway.

//emulate the external logic that swaps the active class
$(function(){
  var $elements = $('.top');
  
  $elements.on('click', function(){
    $elements.not(this).removeClass('active');
    $(this).addClass('active');
  });
});

$(function(){
  var $top = $('.top');
  var $carousel = $('.carousel-inner');
  var $carouselItems = $carousel.find('.carousel-item');
  
  $top.on('click', function(){
    var $this = $(this);
    
    $carousel.prepend($carouselItems.filter(function(){
      return $this.data('id') === $(this).data('id');
    }));
  });
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top active" data-id="1">1</div>
<div class="top" data-id="2">2</div>

<div class="carousel-inner">
  <div class="carousel-item " data-id="1" data="carousel-item">Number 1</div>
  <div class="carousel-item " data-id="2" data="carousel-item">Number 2</div>
</div>

Upvotes: 1

Related Questions