How to swap 2 blocks that are in different places of the code if the screen size reaches a certain width and back when the width is larger?

The first way:

jQuery.fn.swap = function(b) { b = jQuery(b)[0]; var a = this[0], a2 = a.cloneNode(true), b2 = b.cloneNode(true), stack = this; a.parentNode.replaceChild(b2, a); b.parentNode.replaceChild(a2, b); stack[0] = a2; return this.pushStack( stack ); }; $(window).resize(function() { if ($(window).width() <= '800') { $('.first').swap('.second'); } }); 

But with this method, the function is called every time the screen changes, besides, a Yandex card is connected in one of the blocks and after moving it stops working.

The second way:

  var first = $('.first'); var second = $('.second'); $(window).resize(function() { if ($(window).width() <= '800'){ first.detach().prependTo(second); second.detach().prependTo(first); }; }); 

With this method, the console gives an error:

Failed to execute 'insertBefore' on 'Node': The new child element contains the parent.

    2 answers 2

      $(function() { var first = $(".first"); var second = $(".second"); $(window).resize(function() { var i = $(".first, .second").index(first); if ($(window).width() <= "800" && !i) { var a = $("<abracadabra/>"); a.insertAfter(first); first.insertAfter(second); second.insertAfter(a); a.remove() } else if ($(window).width() > "800" && i) { var a = $("<abracadabra/>"); a.insertAfter(first); first.insertAfter(second); second.insertAfter(a); a.remove() } }).resize() }); 
    • Thank you, kind man - Alexey

    In this case, media-querries are so strongly suggested that I would, if I didn’t have absolute positioning, would probably just create two instances of each block and change their visibility through the css display property

     <style> .first { display: block; } .first800 { display: none; } .second{ display: block; } .second800 { display: none; } @media (max-width: 800px) { .first { display: none; } .first800 { display: block; } .second{ display: none; } .second800 { display: block; } } </style>