$(window).resize(function() { if($(window).width() < 992) { $('.logo').append($('.logo1')); } else{ $('.logo1').appendTo($('body')); } }); 
 .logo{ background: #ccc; width: 300px; height: 300px; } .logo1{ background: #444; width: 150px; height: 150px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="logo"> </div> <div class="logo1"> </div> 

When searching the Internet I found a lot of options, I tried, but they all had some kind of crutches or something. I am interested in how to do this in the most correct and universal way for any situation using jquery.

  • You can create two elements and hide through media query. - Alex78191

2 answers 2

In jquery there is a resize event that fires when the window is resized. Here is a sample code, I do not know what to explain in it? It seems everything is elementary.

 $(window).resize(function(){ if($(window).width < 700){ $('.block-2').append($('.inner')); } }); $(document).ready(function(){ if($(window).width < 700){ $('.block-2').append($('.inner')); } }); 
 .block-1{ width: 100px; height: 50px; background: red; } .block-2{ width: 100px; height: 50px; background: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="block-1"> <div class="inner"> Лорэм ипсум </div> </div> <div class="block-2"> </div> 

  • But as far as I understand, it will not work, if I, for example, immediately open the site on a small device? - Kellok
  • @Kellok Made a change, now work. - Raz Galstyan
  • Thank you very much for the answer. - Kellok
  • For some reason, the block begins to "jump" back and forth, when the screen reaches close to 992, and then calms down. Why it happens? ps updated the code, but for some reason it doesn't work here at all. - Kellok
  • Understand what the problem was - the scroll bar, then added, then removed. - Kellok

This is even easier and by the way, here is the link to JSFiddle, since there you can reduce the frame size https://jsfiddle.net/bq04yot4/ :

  function resizeBlock(){ if(window.matchMedia("screen and (max-width: 992px)").matches) { $('.logo').append($('.logo1')); } else if (window.matchMedia("screen and (min-width: 992px)").matches){ $('.logo1').appendTo($('body')); } } $(window).resize(function() { resizeBlock(); }); $(document).ready(function(){ resizeBlock(); }); 
 .logo{ background: #ccc; width: 300px; height: 300px; } .logo1{ background: #444; width: 150px; height: 150px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="logo"> </div> <div class="logo1"> </div>