Ad

How Do You Toggle InsertBefore Or InsertAfter?

- 1 answer

I have a tab button. With a upward pointing arrow and text underneith. When you click the tab. The header of the site is hidden and the arrow icon turns upside down.

I would also like the arrow to change its positioning in html.

I can accomplish this with just fine using the following script:

<script>    
    $('.contentTab').on('click', function(e) {
      $('.mainContent').toggleClass("closeHeader");
      $('.triangle-up').toggleClass("triangle-down");
      $(".triangle-down").insertAfter(".contentTab h1")
      e.preventDefault();
    });
</script>

//

My question is: How do I toggle this feature. So that if the contentTab is clicked again. The arrow reverts to its old positioning. Do i create an if statment? I am pretty new with JS

Thanks!

Ad

Answer

Since you're toggling a class on the element, you could simply use the :not() pseudo class to select .triangle-up if it doesn't have a .triangle-down class:

Example Here

$(".triangle-down").insertAfter(".contentTab h1");
$(".triangle-up:not(.triangle-down)").insertBefore(".contentTab h1");

Full code snippet:

$('.contentTab').on('click', function(e) {
  $('.mainContent').toggleClass("closeHeader");
  $('.triangle-up').toggleClass("triangle-down");
  $(".triangle-down").insertAfter(".contentTab h1");
  $(".triangle-up:not(.triangle-down)").insertBefore(".contentTab h1");
  e.preventDefault();
});
h1 {
  display: inline-block;
}
.triangle-down {
  color: #f00;
  display: inline-block;
  transform: rotate(180deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="contentTab">
  <span class="triangle-up">▲</span>
  <h1>Content tab header</h1>
</div>

Ad
source: stackoverflow.com
Ad