Home > OS >  Relocate element based on screen size
Relocate element based on screen size

Time:10-03

I need to place an element on a page based on the browser size. I cannot hide and show this element because it can only be once in the dom. Seems pretty straight forward but I'm stuck. It seems to be working partially. Do I need to do some sort of detach/attach? Sorry, it' been a while since i tinkered with plain JS.

srPos();
window.onresize = srPos();

function srPos() {
    var ww = window.innerWidth,
        sr = document.getElementById("gcs-box"),
        pp = document.getElementById("primary-panel"),
        sp = document.getElementById("secondary-panel");
    
    if (ww > 991) {
        sp.prepend(sr);
    } else {
        pp.prepend(sr);
    }        
}

What am I missing?

CodePudding user response:

You are assigning the value returned by srPos rather than the function itself to the onresize property.

Remove the brackets:

srPos();
window.onresize = srPos;

function srPos() {
    var ww = window.innerWidth,
        sr = document.getElementById("gcs-box"),
        pp = document.getElementById("primary-panel"),
        sp = document.getElementById("secondary-panel");
    
    if (ww > 991) {
        sp.prepend(sr);
    } else {
        pp.prepend(sr);
    }        
}
  • Related