Search code examples
jquerywindow-resizeinsertafter

Move divs around on window resize with if then


I am trying to move some divs around when the window gets resized, shouldn't this if then statement work:

$(window).resize(function() {
if ($(window).width() < 1024) {
    $('.div1').insertAfter('.div2');
}
else ($(window).width() > 1024) {
    $('.div1').insertBefore('.div2');
}
});

Also, can I trigger this when the page is loaded using .resize OR when the page is first loaded?


Solution

  • Else statements can't have a condition attached.

    else ($(window).width() > 1024) {
        $('.div1').insertBefore('.div2');
    }
    });
    

    has to be

    else {
        $('.div1').insertBefore('.div2');
    }
    });
    

    If you wan't to call this during page load, you can put it into a function and call the function both on resize and on page load.