Search code examples
javascriptjqueryappendto

jQuery - issue with appendTo()


I have a problem with the appendTo function. I am currently working on a responsive design. If the window is smaller than a certain size, login and search are appended to another div. If it gets bigger again, they will be moved to where they come from, theoretically.

And what happens instead? With ".login", it works perfectly. But the ".search" is f*cking things up. Everytime you resize the window, instead of being appended TO, it just get appended, so resize the window with 100px and you will have a 2^100 of those ".search"-forms. Funny thing is, they are all the same.

HTML

...
<div class="wrap1">
  <div class="login">
    <form method="post" action="#">
      <input type="text" name="user" placeholder="Username"/>
      <input type="text" name="pass" placeholder="Password"/>
      <input type="submit" value="Submit"/>
    </form>
  </div>
</div>
<div class="wrap2">
  <div class="search">
    <form method="get" action="#">
      <input type="text" name="search" placeholder="Search"/>
      <input type="submit" value="Search"/>
    </form>
  </div>
</div>
<div class="wrap3">
</div>
...

JavaScript / jQuery

$(document).ready(function(){
  $(window).resize(function(){
    if ($(window).width() < 461) {
      $(".login, .search").prependTo($(".wrap3"));
    } else {
      $(".login").appendTo(".wrap1");
      $(".search").appendTo(".wrap2");
    }
  })
})

Any ideas? I'd be happy with jQ but pure JS answers are also welcome.


Solution

  • Found it!

    @nnnnnn was actually right:

    There were multiple wraps. My JS is actually $(".login").appendTo(".wrap1 .centerwrap")

    (it's still called wrap1 for comprehension)

    So there wouldn't be any problems, but I forgot that there were multiple nested (bc of pos:abs navigation) centerwraps in .wrap2. That's why the .wrap1 .login worked perfectly but the .wrap2 .search didn't.

    Solved it with

    $(".login").appendTo(".wrap1 > .centerwrap");
    $(".search").appendTo(".wrap2 > .centerwrap");
    

    And yes, I feel dumb. Have been looking for the answer for 2 days now.