How to return the block to its original position after the page loads, if the condition does not work?

function windowSize() { if ($(window).width() <= '767') { $("#cart").appendTo("#mobile-cart"); } } $(window).on('load resize', windowSize); 

That is, if you increase the width of the browser window, then #cart must be removed from #mobile-cart and returned to its original in .header-cart .

  • one
    Perhaps with the help of else { $("#cart").appendTo(".header-cart"); } else { $("#cart").appendTo(".header-cart"); } ? - Regent
  • Yes, what you need, most importantly wrote the same thing but forgot to put braces for else. - Denis
  • If there is one expression in an else , then braces are optional. else $("#cart").appendTo(".header-cart"); equivalent to else { $("#cart").appendTo(".header-cart"); } else { $("#cart").appendTo(".header-cart"); } . - Regent

1 answer 1

 function windowSize() { if ($(window).width() <= 767) { $("#cart").appendTo("#mobile-cart"); $(".header-cart #cart").detach(); } else { $("#cart").appendTo(".header-cart"); $("#mobile-cart #cart").detach(); } } 
  • And why in the code are specified .detach() ? - Regent
  • Something is not right here. Then detach first, then appendTo for it. - Qwertiy
  • @Qwertiy detach is generally superfluous here. - Regent