PepeW
PepeW

Reputation: 607

jQuery: Detach and Append at the same time

I have 2 menus. I want to display the menu1 when the screen size is < 500px and the menu2 when the screen size is > 500px. Also, I HAVE to use the detach() function and not functions like hide().

Here's my code:

$(window).on('load resize', function(){
    if ( $("body").outerWidth() < 500) {
      $(".menu1").detach();
      $(".action-menu2").append($(".menu2"));
    }
    else {
      $(".menu2").detach();
      $(".action-menu1").append($(".menu1"));
    }
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

<body>
  
  <div class="action-menu1">
    <p class="menu1">menu1</p>
  </div>

  <div class="action-menu2">
    <p class="menu2">menu2</p>
  </div>
  
</body>

Upvotes: 0

Views: 1701

Answers (1)

Cornel Raiu
Cornel Raiu

Reputation: 3005

According to the documentation here: jQuery detach you have to assign the detached element in a variable for being able to reinsert it into the DOM later.

Your code will become something like:

var menu1,
    menu2;

$(window).on('load', function(){
    menu1 = $(".menu1");
    menu2 = $(".menu2");
});

$(window).on('load resize', function(){
    if ( $("body").outerWidth() < 500) {
      if( menu1 ) {
          $(".menu1").remove();
      } else {
          menu1 = $(".menu1").detach();
      }
      $(".action-menu2").append(menu2);
    }
    else {

      if( menu2  ) {
          $(".menu2").remove();
      } else {
          menu2 = $(".menu2").detach();
      }

      $(".action-menu1").append(menu1);
    }
});

I did not test this code, but I guess it should work. I know it can be done better, but at least it gives you a head start

Upvotes: 2

Related Questions