jQuery on resize, clone div, detach and append again

1.7k Views Asked by At

I'm working on a full responsive website and I'm having an issue with one thing - maybe you could help me with it.

Basic structure:

<div id="content">
<div id="content_left"></div><!--end content_left-->

<div id="content_right">
<div class="profile_box"></div><!--end profile_box-->
</div><!--end content_right-->

</div><!--end content-->

I'm trying to do these things:

  • (when I shrink the site to 600px or less)
    • clone whole #content_right
    • move .profile_box from #content_right to #content_left
    • detach whole #content_right
  • (when I stretch the site to 600 or more)

    • append #content_right to #content
    • move .profile_box back in the place (#content_right)

    $(window).resize(function(){ if($('body').width() < 600) { var cr_clone = $('#content_right').clone(true); $("#content_right .profile_box").detach().prependTo('#content_left') $("#content_right").detach(); } else{ cr_clone.appendTo('#content'); } });

It's working in one way - when I shrink the site, .profile_box is moved to #content_left, and whole #content_right is detached - so it's working great, but...

In the other way, there is a problem. When I'm "in shrinked" site and want to stretch to 600 or more the #content_right is not showing (after site refresh it shows up but I want to show it without refreshing).

It will work on mobile devices, so, when user rotates their cellphone, I want to work "in fly" depends on screen width.

Any help will be appreciated - thanks.

I don't want to hide or show it because it's still loading data even if it's hidden.

1

There are 1 best solutions below

3
On

Your cr_clone doesn't exists in the else statement :

var cr_clone = $('#content_right').clone(true);
if($('body').width() < 600) {
            $("#content_right .profile_box").detach().prependTo('#content_left')
    $("#content_right").detach();
}
else{
    cr_clone.appendTo('#content');
}

UPDATE

You need two if statement. You have to add the section only if it's not already there :

var cr_clone = $('#content_right').clone(true);
if($('body').width() < 600) {
    if ($("#content_left #content_right").length == 0){
        $("#content_right .profile_box").detach().prependTo('#content_left');
        $("#content_right").detach();
    }

}
else{
    if ($("#content_left #content_right").length > 0) {
        cr_clone.appendTo('#content'); 
        $("#content_left profile_box").detach().prependTo('#content_right'); 
    }

}