PortalP PortalP - 9 days ago 7
Javascript Question

How to activate .insertBefore on screen width change?

I have this snippet which switches the position of the secondary wrapper above the primary wrapper if the screen width is below 767px. This works great however it only works on refresh. How do I get it to work automatically when the screen width is changed?

Thanks! Total novice here.

jQuery(document).ready(function(){

if(screen.width<=767){

jQuery('body.single #secondary').insertBefore('#primary');
}

});

Answer

It seems like you are using jquery so I would recommend the .resize() method.

https://api.jquery.com/resize/

This will fire whenever the window is resized. You can have it do whatever you need at that point.

$(window).resize(function(){
    If (myWindow.width() >= windowThreshold){
        //do all the things...
    }
});
Comments